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.

54187 lines
1.9MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. /*
  24. ==============================================================================
  25. This header contains the entire Juce source tree, and can be #included in
  26. all your source files.
  27. As well as including this in your files, you should also add juce_inline.cpp
  28. to your project (or juce_inline.mm on the Mac).
  29. ==============================================================================
  30. */
  31. #ifndef __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  32. #define __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  33. #define DONT_AUTOLINK_TO_JUCE_LIBRARY 1
  34. /********* Start of inlined file: juce.h *********/
  35. #ifndef __JUCE_JUCEHEADER__
  36. #define __JUCE_JUCEHEADER__
  37. /*
  38. This is the main JUCE header file that applications need to include.
  39. */
  40. // (this includes things that need defining outside of the JUCE namespace)
  41. /********* Start of inlined file: juce_StandardHeader.h *********/
  42. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  43. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  44. /** Current Juce version number.
  45. See also SystemStats::getJUCEVersion() for a string version.
  46. */
  47. #define JUCE_MAJOR_VERSION 1
  48. #define JUCE_MINOR_VERSION 46
  49. /** Current Juce version number.
  50. Bits 16 to 32 = major version.
  51. Bits 8 to 16 = minor version.
  52. Bits 0 to 8 = point release (not currently used).
  53. See also SystemStats::getJUCEVersion() for a string version.
  54. */
  55. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8))
  56. /********* Start of inlined file: juce_Config.h *********/
  57. #ifndef __JUCE_CONFIG_JUCEHEADER__
  58. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  59. /*
  60. This file contains macros that enable/disable various JUCE features.
  61. */
  62. /** The name of the namespace that all Juce classes and functions will be
  63. put inside. If this is not defined, no namespace will be used.
  64. */
  65. #ifndef JUCE_NAMESPACE
  66. #define JUCE_NAMESPACE juce
  67. #endif
  68. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  69. but if you define this value, you can override this can force it to be true or
  70. false.
  71. */
  72. #ifndef JUCE_FORCE_DEBUG
  73. //#define JUCE_FORCE_DEBUG 1
  74. #endif
  75. /** If this flag is enabled, the the jassert and jassertfalse macros will
  76. always use Logger::writeToLog() to write a message when an assertion happens.
  77. Enabling it will also leave this turned on in release builds. When it's disabled,
  78. however, the jassert and jassertfalse macros will not be compiled in a
  79. release build.
  80. @see jassert, jassertfalse, Logger
  81. */
  82. #ifndef JUCE_LOG_ASSERTIONS
  83. // #define JUCE_LOG_ASSERTIONS 1
  84. #endif
  85. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  86. which the ASIOAudioIODevice class can't be built. See the comments in the
  87. ASIOAudioIODevice class's header file for more info about this.
  88. (This only affects a Win32 build)
  89. */
  90. #ifndef JUCE_ASIO
  91. #define JUCE_ASIO 1
  92. #endif
  93. /** Comment out this macro to disable building of ALSA device support on Linux.
  94. */
  95. #ifndef JUCE_ALSA
  96. #define JUCE_ALSA 1
  97. #endif
  98. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  99. have the SDK installed.
  100. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  101. classes will be unavailable.
  102. On Windows, if you enable this, you'll need to have the QuickTime SDK
  103. installed, and its header files will need to be on your include path.
  104. */
  105. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  106. #define JUCE_QUICKTIME 1
  107. #endif
  108. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  109. have the appropriate headers and libraries available. If it's not enabled, the
  110. OpenGLComponent class will be unavailable.
  111. */
  112. #ifndef JUCE_OPENGL
  113. #define JUCE_OPENGL 1
  114. #endif
  115. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  116. If you're not going to need either of these formats, turn off the flags to
  117. avoid bloating your codebase with them.
  118. */
  119. #ifndef JUCE_USE_FLAC
  120. #define JUCE_USE_FLAC 1
  121. #endif
  122. #ifndef JUCE_USE_OGGVORBIS
  123. #define JUCE_USE_OGGVORBIS 1
  124. #endif
  125. /** This flag lets you enable support for CD-burning. You might want to disable
  126. it to build without the MS SDK under windows.
  127. */
  128. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  129. #define JUCE_USE_CDBURNER 1
  130. #endif
  131. /** Enabling this macro means that all regions that get repainted will have a coloured
  132. line drawn around them.
  133. This is handy if you're trying to optimise drawing, because it lets you easily see
  134. when anything is being repainted unnecessarily.
  135. */
  136. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  137. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  138. #endif
  139. /** Enable this under Linux to use Xinerama for multi-monitor support.
  140. */
  141. #ifndef JUCE_USE_XINERAMA
  142. #define JUCE_USE_XINERAMA 1
  143. #endif
  144. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  145. */
  146. #ifndef JUCE_USE_XSHM
  147. #define JUCE_USE_XSHM 1
  148. #endif
  149. /** Enabling this builds support for VST audio plugins.
  150. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  151. */
  152. #ifndef JUCE_PLUGINHOST_VST
  153. // #define JUCE_PLUGINHOST_VST 1
  154. #endif
  155. /** Enabling this builds support for AudioUnit audio plugins.
  156. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  157. */
  158. #ifndef JUCE_PLUGINHOST_AU
  159. // #define JUCE_PLUGINHOST_AU 1
  160. #endif
  161. /** Enabling this will avoid including any UI code in the build. This is handy for
  162. writing command-line utilities, e.g. on linux boxes which don't have some
  163. of the UI libraries installed.
  164. */
  165. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  166. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  167. #endif
  168. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  169. */
  170. #ifndef JUCE_WEB_BROWSER
  171. #define JUCE_WEB_BROWSER 1
  172. #endif
  173. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  174. codebase - you might need to use this if you're linking to some of these libraries
  175. yourself.
  176. */
  177. #ifndef JUCE_INCLUDE_ZLIB_CODE
  178. #define JUCE_INCLUDE_ZLIB_CODE 1
  179. #endif
  180. #ifndef JUCE_INCLUDE_FLAC_CODE
  181. #define JUCE_INCLUDE_FLAC_CODE 1
  182. #endif
  183. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  184. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  185. #endif
  186. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  187. #define JUCE_INCLUDE_PNGLIB_CODE 1
  188. #endif
  189. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  190. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  191. #endif
  192. /** Enable this to add extra memory-leak info to the new and delete operators.
  193. (Currently, this only affects Windows builds in debug mode).
  194. */
  195. #ifndef JUCE_CHECK_MEMORY_LEAKS
  196. #define JUCE_CHECK_MEMORY_LEAKS 1
  197. #endif
  198. /** Enable this to turn on juce's internal catching of exceptions.
  199. Turning it off will avoid any exception catching. With it on, all exceptions
  200. are passed to the JUCEApplication::unhandledException() callback for logging.
  201. */
  202. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  204. #endif
  205. /** If this macro is set, the Juce String class will use unicode as its
  206. internal representation. If it isn't set, it'll use ANSI.
  207. */
  208. #ifndef JUCE_STRINGS_ARE_UNICODE
  209. #define JUCE_STRINGS_ARE_UNICODE 1
  210. #endif
  211. #endif
  212. /********* End of inlined file: juce_Config.h *********/
  213. #ifdef JUCE_NAMESPACE
  214. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  215. #define END_JUCE_NAMESPACE }
  216. #else
  217. #define BEGIN_JUCE_NAMESPACE
  218. #define END_JUCE_NAMESPACE
  219. #endif
  220. // This sets up the JUCE_WIN32, JUCE_MAC, or JUCE_LINUX macros
  221. /********* Start of inlined file: juce_PlatformDefs.h *********/
  222. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  223. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  224. /* This file figures out which platform is being built, and defines some macros
  225. that the rest of the code can use for OS-specific compilation.
  226. Macros that will be set here are:
  227. - One of JUCE_WIN32, JUCE_MAC or JUCE_LINUX.
  228. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  229. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  230. - Either JUCE_INTEL or JUCE_PPC
  231. - Either JUCE_GCC or JUCE_MSVC
  232. On the Mac, it also defines MACOS_10_2_OR_EARLIER if the build is targeting OSX10.2,
  233. and MACOS_10_3_OR_EARLIER if it is targeting either 10.2 or 10.3
  234. It also includes a set of macros for debug console output and assertions.
  235. */
  236. #if (defined (_WIN32) || defined (_WIN64))
  237. #define JUCE_WIN32 1
  238. #else
  239. #if defined (LINUX) || defined (__linux__)
  240. #define JUCE_LINUX 1
  241. #else
  242. #define JUCE_MAC 1
  243. #endif
  244. #endif
  245. #if JUCE_WIN32
  246. #ifdef _MSC_VER
  247. #ifdef _WIN64
  248. #define JUCE_64BIT 1
  249. #else
  250. #define JUCE_32BIT 1
  251. #endif
  252. #endif
  253. #ifdef _DEBUG
  254. #define JUCE_DEBUG 1
  255. #endif
  256. /** If defined, this indicates that the processor is little-endian. */
  257. #define JUCE_LITTLE_ENDIAN 1
  258. #define JUCE_INTEL 1
  259. #endif
  260. #if JUCE_MAC
  261. #include <CoreFoundation/CoreFoundation.h>
  262. #ifndef NDEBUG
  263. #define JUCE_DEBUG 1
  264. #endif
  265. #ifdef __LITTLE_ENDIAN__
  266. #define JUCE_LITTLE_ENDIAN 1
  267. #else
  268. #define JUCE_BIG_ENDIAN 1
  269. #endif
  270. #if defined (__ppc__) || defined (__ppc64__)
  271. #define JUCE_PPC 1
  272. #else
  273. #define JUCE_INTEL 1
  274. #endif
  275. #ifdef __LP64__
  276. #define JUCE_64BIT 1
  277. #else
  278. #define JUCE_32BIT 1
  279. #endif
  280. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
  281. #define MACOS_10_2_OR_EARLIER 1
  282. #endif
  283. #if (! defined (MAC_OS_X_VERSION_10_4)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
  284. #define MACOS_10_3_OR_EARLIER 1
  285. #endif
  286. #if (! defined (MAC_OS_X_VERSION_10_5)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
  287. #define MACOS_10_4_OR_EARLIER 1
  288. #endif
  289. #endif
  290. #if JUCE_LINUX
  291. #ifdef _DEBUG
  292. #define JUCE_DEBUG 1
  293. #endif
  294. // Allow override for big-endian Linux platforms
  295. #ifndef JUCE_BIG_ENDIAN
  296. #define JUCE_LITTLE_ENDIAN 1
  297. #endif
  298. #if defined (__LP64__) || defined (_LP64)
  299. #define JUCE_64BIT 1
  300. #else
  301. #define JUCE_32BIT 1
  302. #endif
  303. #define JUCE_INTEL 1
  304. #endif
  305. #ifdef JUCE_FORCE_DEBUG
  306. #undef JUCE_DEBUG
  307. #if JUCE_FORCE_DEBUG
  308. #define JUCE_DEBUG 1
  309. #endif
  310. #endif
  311. // Compiler type macros.
  312. #ifdef __GNUC__
  313. #define JUCE_GCC 1
  314. #elif defined (_MSC_VER)
  315. #define JUCE_MSVC 1
  316. #if _MSC_VER >= 1400
  317. #define JUCE_USE_INTRINSICS 1
  318. #endif
  319. #else
  320. #error unknown compiler
  321. #endif
  322. /** This macro defines the C calling convention used as the standard for Juce calls. */
  323. #if JUCE_MSVC
  324. #define JUCE_CALLTYPE __stdcall
  325. #else
  326. #define JUCE_CALLTYPE
  327. #endif
  328. // Debugging and assertion macros
  329. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  330. #if JUCE_LOG_ASSERTIONS
  331. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  332. #elif defined (JUCE_DEBUG)
  333. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  334. #else
  335. #define juce_LogCurrentAssertion
  336. #endif
  337. #ifdef JUCE_DEBUG
  338. // If debugging is enabled..
  339. /** Writes a string to the standard error stream.
  340. This is only compiled in a debug build.
  341. @see Logger::outputDebugString
  342. */
  343. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  344. /** Printf's a string to the standard error stream.
  345. This is only compiled in a debug build.
  346. @see Logger::outputDebugString
  347. */
  348. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  349. // Assertions..
  350. #if JUCE_WIN32 || DOXYGEN
  351. #if JUCE_USE_INTRINSICS
  352. #pragma intrinsic (__debugbreak)
  353. /** This will try to break the debugger if one is currently hosting this app.
  354. @see jassert()
  355. */
  356. #define juce_breakDebugger __debugbreak();
  357. #elif JUCE_GCC
  358. /** This will try to break the debugger if one is currently hosting this app.
  359. @see jassert()
  360. */
  361. #define juce_breakDebugger asm("int $3");
  362. #else
  363. /** This will try to break the debugger if one is currently hosting this app.
  364. @see jassert()
  365. */
  366. #define juce_breakDebugger { __asm int 3 }
  367. #endif
  368. #elif JUCE_MAC
  369. #define juce_breakDebugger Debugger();
  370. #elif JUCE_LINUX
  371. #define juce_breakDebugger kill (0, SIGTRAP);
  372. #endif
  373. /** This will always cause an assertion failure.
  374. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  375. in juce_Config.h).
  376. @see jassert()
  377. */
  378. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  379. /** Platform-independent assertion macro.
  380. This gets optimised out when not being built with debugging turned on.
  381. Be careful not to call any functions within its arguments that are vital to
  382. the behaviour of the program, because these won't get called in the release
  383. build.
  384. @see jassertfalse
  385. */
  386. #define jassert(expression) { if (! (expression)) jassertfalse }
  387. #else
  388. // If debugging is disabled, these dummy debug and assertion macros are used..
  389. #define DBG(dbgtext)
  390. #define DBG_PRINTF(dbgprintf)
  391. #define jassertfalse { juce_LogCurrentAssertion }
  392. #if JUCE_LOG_ASSERTIONS
  393. #define jassert(expression) { if (! (expression)) jassertfalse }
  394. #else
  395. #define jassert(a) { }
  396. #endif
  397. #endif
  398. #ifndef DOXYGEN
  399. template <bool b> struct JuceStaticAssert;
  400. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  401. #endif
  402. /** A compile-time assertion macro.
  403. If the expression parameter is false, the macro will cause a compile error.
  404. */
  405. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  406. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  407. #define JUCE_TRY try
  408. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  409. object so they can be logged by the application if it wants to.
  410. */
  411. #define JUCE_CATCH_EXCEPTION \
  412. catch (const std::exception& e) \
  413. { \
  414. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  415. } \
  416. catch (...) \
  417. { \
  418. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  419. }
  420. #define JUCE_CATCH_ALL catch (...) {}
  421. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  422. #else
  423. #define JUCE_TRY
  424. #define JUCE_CATCH_EXCEPTION
  425. #define JUCE_CATCH_ALL
  426. #define JUCE_CATCH_ALL_ASSERT
  427. #endif
  428. // Macros for inlining.
  429. #if JUCE_MSVC
  430. /** A platform-independent way of forcing an inline function.
  431. Use the syntax: @code
  432. forcedinline void myfunction (int x)
  433. @endcode
  434. */
  435. #ifdef JUCE_DEBUG
  436. #define forcedinline __forceinline
  437. #else
  438. #define forcedinline inline
  439. #endif
  440. /** A platform-independent way of stopping the compiler inlining a function.
  441. Use the syntax: @code
  442. juce_noinline void myfunction (int x)
  443. @endcode
  444. */
  445. #define juce_noinline
  446. #else
  447. /** A platform-independent way of forcing an inline function.
  448. Use the syntax: @code
  449. forcedinline void myfunction (int x)
  450. @endcode
  451. */
  452. #ifndef JUCE_DEBUG
  453. #define forcedinline inline __attribute__((always_inline))
  454. #else
  455. #define forcedinline inline
  456. #endif
  457. /** A platform-independent way of stopping the compiler inlining a function.
  458. Use the syntax: @code
  459. juce_noinline void myfunction (int x)
  460. @endcode
  461. */
  462. #define juce_noinline __attribute__((noinline))
  463. #endif
  464. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  465. /********* End of inlined file: juce_PlatformDefs.h *********/
  466. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  467. #if JUCE_MSVC
  468. #pragma warning (push)
  469. #pragma warning (disable: 4514 4245 4100)
  470. #endif
  471. #include <cstdlib>
  472. #include <cstdarg>
  473. #include <climits>
  474. #include <cmath>
  475. #include <cwchar>
  476. #include <stdexcept>
  477. #include <typeinfo>
  478. #include <cstring>
  479. #include <cstdio>
  480. #if JUCE_MAC || JUCE_LINUX
  481. #include <pthread.h>
  482. #endif
  483. #if JUCE_USE_INTRINSICS
  484. #include <intrin.h>
  485. #endif
  486. #if JUCE_MAC
  487. #if MACOS_10_3_OR_EARLIER
  488. #include <CoreServices/CoreServices.h>
  489. #else
  490. #include <libkern/OSAtomic.h>
  491. #endif
  492. #endif
  493. #if JUCE_LINUX
  494. #include <signal.h>
  495. #endif
  496. #if JUCE_MSVC && JUCE_DEBUG
  497. #include <crtdbg.h>
  498. #endif
  499. #if JUCE_MSVC
  500. #pragma warning (pop)
  501. #endif
  502. // DLL building settings on Win32
  503. #if JUCE_MSVC
  504. #ifdef JUCE_DLL_BUILD
  505. #define JUCE_API __declspec (dllexport)
  506. #pragma warning (disable: 4251)
  507. #elif defined (JUCE_DLL)
  508. #define JUCE_API __declspec (dllimport)
  509. #pragma warning (disable: 4251)
  510. #endif
  511. #endif
  512. #ifndef JUCE_API
  513. /** This macro is added to all juce public class declarations. */
  514. #define JUCE_API
  515. #endif
  516. /** This macro is added to all juce public function declarations. */
  517. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  518. // Now include some basics that are needed by most of the Juce classes...
  519. BEGIN_JUCE_NAMESPACE
  520. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  521. #if JUCE_LOG_ASSERTIONS
  522. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  523. #endif
  524. /********* Start of inlined file: juce_Memory.h *********/
  525. #ifndef __JUCE_MEMORY_JUCEHEADER__
  526. #define __JUCE_MEMORY_JUCEHEADER__
  527. /*
  528. This file defines the various juce_malloc(), juce_free() macros that should be used in
  529. preference to the standard calls.
  530. */
  531. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  532. #ifndef JUCE_DLL
  533. // Win32 debug non-DLL versions..
  534. /** This should be used instead of calling malloc directly. */
  535. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  536. /** This should be used instead of calling calloc directly. */
  537. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  538. /** This should be used instead of calling realloc directly. */
  539. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  540. /** This should be used instead of calling free directly. */
  541. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  542. #else
  543. // Win32 debug DLL versions..
  544. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  545. // way all juce calls in the DLL and in the host API will all use the same allocator.
  546. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  547. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  548. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  549. extern JUCE_API void juce_DebugFree (void* const block);
  550. /** This should be used instead of calling malloc directly. */
  551. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  552. /** This should be used instead of calling calloc directly. */
  553. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  554. /** This should be used instead of calling realloc directly. */
  555. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  556. /** This should be used instead of calling free directly. */
  557. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  558. #endif
  559. #if ! defined (_AFXDLL)
  560. /** This macro can be added to classes to add extra debugging information to the memory
  561. allocated for them, so you can see the type of objects involved when there's a dump
  562. of leaked objects at program shutdown. (Only works on win32 at the moment).
  563. */
  564. #define juce_UseDebuggingNewOperator \
  565. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  566. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  567. static void operator delete (void* p) { juce_free (p); }
  568. #endif
  569. #elif defined (JUCE_DLL)
  570. // Win32 DLL (release) versions..
  571. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  572. // way all juce calls in the DLL and in the host API will all use the same allocator.
  573. extern JUCE_API void* juce_Malloc (const int size);
  574. extern JUCE_API void* juce_Calloc (const int size);
  575. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  576. extern JUCE_API void juce_Free (void* const block);
  577. /** This should be used instead of calling malloc directly. */
  578. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  579. /** This should be used instead of calling calloc directly. */
  580. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  581. /** This should be used instead of calling realloc directly. */
  582. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  583. /** This should be used instead of calling free directly. */
  584. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  585. #define juce_UseDebuggingNewOperator \
  586. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  587. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  588. static void operator delete (void* p) { juce_free (p); }
  589. #else
  590. // Mac, Linux and Win32 (release) versions..
  591. /** This should be used instead of calling malloc directly. */
  592. #define juce_malloc(numBytes) malloc (numBytes)
  593. /** This should be used instead of calling calloc directly. */
  594. #define juce_calloc(numBytes) calloc (1, numBytes)
  595. /** This should be used instead of calling realloc directly. */
  596. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  597. /** This should be used instead of calling free directly. */
  598. #define juce_free(location) free (location)
  599. #endif
  600. /** This macro can be added to classes to add extra debugging information to the memory
  601. allocated for them, so you can see the type of objects involved when there's a dump
  602. of leaked objects at program shutdown. (Only works on win32 at the moment).
  603. Note that if you create a class that inherits from a class that uses this macro,
  604. your class must also use the macro, otherwise you'll probably get compile errors
  605. because of ambiguous new operators.
  606. Most of the JUCE classes use it, so see these for examples of where it should go.
  607. */
  608. #ifndef juce_UseDebuggingNewOperator
  609. #define juce_UseDebuggingNewOperator
  610. #endif
  611. #if JUCE_MSVC
  612. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  613. E.g.
  614. @code
  615. juce_ThreadLocal int myVariable;
  616. @endcode
  617. */
  618. #define juce_ThreadLocal __declspec(thread)
  619. #else
  620. #define juce_ThreadLocal __thread
  621. #endif
  622. /** Clears a block of memory. */
  623. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  624. /** Clears a reference to a local structure. */
  625. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  626. /** A handy macro that calls delete on a pointer if it's non-zero, and
  627. then sets the pointer to null.
  628. */
  629. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  630. #endif // __JUCE_MEMORY_JUCEHEADER__
  631. /********* End of inlined file: juce_Memory.h *********/
  632. /********* Start of inlined file: juce_MathsFunctions.h *********/
  633. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  634. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  635. /*
  636. This file sets up some handy mathematical typdefs and functions.
  637. */
  638. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  639. /** A platform-independent 8-bit signed integer type. */
  640. typedef signed char int8;
  641. /** A platform-independent 8-bit unsigned integer type. */
  642. typedef unsigned char uint8;
  643. /** A platform-independent 16-bit signed integer type. */
  644. typedef signed short int16;
  645. /** A platform-independent 16-bit unsigned integer type. */
  646. typedef unsigned short uint16;
  647. /** A platform-independent 32-bit signed integer type. */
  648. typedef signed int int32;
  649. /** A platform-independent 32-bit unsigned integer type. */
  650. typedef unsigned int uint32;
  651. #if JUCE_MSVC
  652. /** A platform-independent 64-bit integer type. */
  653. typedef __int64 int64;
  654. /** A platform-independent 64-bit unsigned integer type. */
  655. typedef unsigned __int64 uint64;
  656. /** A platform-independent macro for writing 64-bit literals, needed because
  657. different compilers have different syntaxes for this.
  658. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  659. GCC, or 0x1000000000 for MSVC.
  660. */
  661. #define literal64bit(longLiteral) ((__int64) longLiteral)
  662. #else
  663. /** A platform-independent 64-bit integer type. */
  664. typedef long long int64;
  665. /** A platform-independent 64-bit unsigned integer type. */
  666. typedef unsigned long long uint64;
  667. /** A platform-independent macro for writing 64-bit literals, needed because
  668. different compilers have different syntaxes for this.
  669. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  670. GCC, or 0x1000000000 for MSVC.
  671. */
  672. #define literal64bit(longLiteral) (longLiteral##LL)
  673. #endif
  674. #if JUCE_64BIT
  675. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  676. typedef int64 pointer_sized_int;
  677. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  678. typedef uint64 pointer_sized_uint;
  679. #elif _MSC_VER >= 1300
  680. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  681. typedef _W64 int pointer_sized_int;
  682. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  683. typedef _W64 unsigned int pointer_sized_uint;
  684. #else
  685. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  686. typedef int pointer_sized_int;
  687. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  688. typedef unsigned int pointer_sized_uint;
  689. #endif
  690. /** A platform-independent unicode character type. */
  691. typedef wchar_t juce_wchar;
  692. // Some indispensible min/max functions
  693. /** Returns the larger of two values. */
  694. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  695. /** Returns the larger of two values. */
  696. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  697. /** Returns the larger of two values. */
  698. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  699. /** Returns the larger of two values. */
  700. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  701. /** Returns the larger of three values. */
  702. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  703. /** Returns the larger of three values. */
  704. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  705. /** Returns the larger of three values. */
  706. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  707. /** Returns the larger of three values. */
  708. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  709. /** Returns the larger of four values. */
  710. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  711. /** Returns the larger of four values. */
  712. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  713. /** Returns the larger of four values. */
  714. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  715. /** Returns the larger of four values. */
  716. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  717. /** Returns the smaller of two values. */
  718. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  719. /** Returns the smaller of two values. */
  720. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  721. /** Returns the smaller of two values. */
  722. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  723. /** Returns the smaller of two values. */
  724. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  725. /** Returns the smaller of three values. */
  726. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  727. /** Returns the smaller of three values. */
  728. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  729. /** Returns the smaller of three values. */
  730. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  731. /** Returns the smaller of three values. */
  732. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  733. /** Returns the smaller of four values. */
  734. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  735. /** Returns the smaller of four values. */
  736. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  737. /** Returns the smaller of four values. */
  738. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  739. /** Returns the smaller of four values. */
  740. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  741. /** Constrains a value to keep it within a given range.
  742. This will check that the specified value lies between the lower and upper bounds
  743. specified, and if not, will return the nearest value that would be in-range. Effectively,
  744. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  745. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  746. the results will be unpredictable.
  747. @param lowerLimit the minimum value to return
  748. @param upperLimit the maximum value to return
  749. @param valueToConstrain the value to try to return
  750. @returns the closest value to valueToConstrain which lies between lowerLimit
  751. and upperLimit (inclusive)
  752. @see jlimit0To, jmin, jmax
  753. */
  754. template <class Type>
  755. inline Type jlimit (const Type lowerLimit,
  756. const Type upperLimit,
  757. const Type valueToConstrain) throw()
  758. {
  759. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  760. return (valueToConstrain < lowerLimit) ? lowerLimit
  761. : ((valueToConstrain > upperLimit) ? upperLimit
  762. : valueToConstrain);
  763. }
  764. /** Handy function to swap two values over.
  765. */
  766. template <class Type>
  767. inline void swapVariables (Type& variable1, Type& variable2) throw()
  768. {
  769. const Type tempVal = variable1;
  770. variable1 = variable2;
  771. variable2 = tempVal;
  772. }
  773. /** Handy macro for getting the number of elements in a simple const C array.
  774. E.g.
  775. @code
  776. static int myArray[] = { 1, 2, 3 };
  777. int numElements = numElementsInArray (myArray) // returns 3
  778. @endcode
  779. */
  780. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  781. // Some useful maths functions that aren't always present with all compilers and build settings.
  782. #if JUCE_WIN32 || defined (DOXYGEN)
  783. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  784. versions of these functions of various platforms and compilers. */
  785. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  786. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  787. versions of these functions of various platforms and compilers. */
  788. forcedinline float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  789. #elif MACOS_10_2_OR_EARLIER
  790. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  791. versions of these functions of various platforms and compilers. */
  792. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  793. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  794. versions of these functions of various platforms and compilers. */
  795. forcedinline float juce_hypotf (float a, float b) { return (float) hypot (a, b); }
  796. forcedinline float sinf (const float a) { return (float) sin (a); }
  797. forcedinline float cosf (const float a) { return (float) cos (a); }
  798. forcedinline float tanf (const float a) { return (float) tan (a); }
  799. forcedinline float atan2f (const float a, const float b) { return (float) atan2 (a, b); }
  800. forcedinline float sqrtf (const float a) { return (float) sqrt (a); }
  801. forcedinline float logf (const float a) { return (float) log (a); }
  802. forcedinline float powf (const float a, const float b) { return (float) pow (a, b); }
  803. forcedinline float expf (const float a) { return (float) exp (a); }
  804. #else
  805. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  806. versions of these functions of various platforms and compilers. */
  807. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  808. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  809. versions of these functions of various platforms and compilers. */
  810. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  811. #endif
  812. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  813. /** A predefined value for Pi, at double-precision.
  814. @see float_Pi
  815. */
  816. const double double_Pi = 3.1415926535897932384626433832795;
  817. /** A predefined value for Pi, at sngle-precision.
  818. @see double_Pi
  819. */
  820. const float float_Pi = 3.14159265358979323846f;
  821. /** The isfinite() method seems to vary greatly between platforms, so this is a
  822. platform-independent macro for it.
  823. */
  824. #if JUCE_LINUX
  825. #define juce_isfinite(v) std::isfinite(v)
  826. #elif JUCE_MAC
  827. #if MACOS_10_2_OR_EARLIER
  828. #define juce_isfinite(v) __isfinite(v)
  829. #elif MACOS_10_3_OR_EARLIER
  830. #ifdef isfinite
  831. #define juce_isfinite(v) isfinite(v)
  832. #else
  833. // no idea why the isfinite macro is sometimes impossible to include, so just copy the built-in one..
  834. static __inline__ int juce_isfinite (double __x) { return __x == __x && __builtin_fabs (__x) != __builtin_inf(); }
  835. #endif
  836. #else
  837. #define juce_isfinite(v) std::isfinite(v)
  838. #endif
  839. #elif JUCE_WIN32 && ! defined (isfinite)
  840. #define juce_isfinite(v) _finite(v)
  841. #else
  842. #define juce_isfinite(v) isfinite(v)
  843. #endif
  844. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  845. /********* End of inlined file: juce_MathsFunctions.h *********/
  846. /********* Start of inlined file: juce_DataConversions.h *********/
  847. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  848. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  849. #if JUCE_USE_INTRINSICS
  850. #pragma intrinsic (_byteswap_ulong)
  851. #endif
  852. // Endianness conversions..
  853. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  854. forcedinline uint32 swapByteOrder (uint32 n) throw()
  855. {
  856. #if JUCE_MAC
  857. // Mac version
  858. return CFSwapInt32 (n);
  859. #elif JUCE_GCC
  860. // Inpenetrable GCC version..
  861. asm("bswap %%eax" : "=a"(n) : "a"(n));
  862. return n;
  863. #elif JUCE_USE_INTRINSICS
  864. // Win32 intrinsics version..
  865. return _byteswap_ulong (n);
  866. #else
  867. // Win32 version..
  868. __asm {
  869. mov eax, n
  870. bswap eax
  871. mov n, eax
  872. }
  873. return n;
  874. #endif
  875. }
  876. /** Swaps the byte-order of a 16-bit short. */
  877. inline uint16 swapByteOrder (const uint16 n) throw()
  878. {
  879. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  880. // Win32 intrinsics version..
  881. return (uint16) _byteswap_ushort (n);
  882. #else
  883. return (uint16) ((n << 8) | (n >> 8));
  884. #endif
  885. }
  886. inline uint64 swapByteOrder (const uint64 value) throw()
  887. {
  888. #if JUCE_MAC
  889. return CFSwapInt64 (value);
  890. #elif JUCE_USE_INTRINSICS
  891. return _byteswap_uint64 (value);
  892. #else
  893. return (((int64) swapByteOrder ((uint32) value)) << 32)
  894. | swapByteOrder ((uint32) (value >> 32));
  895. #endif
  896. }
  897. #if JUCE_LITTLE_ENDIAN
  898. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  899. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  900. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  901. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  902. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  903. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  904. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  905. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  906. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  907. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  908. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  909. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  910. /** Turns 4 bytes into a little-endian integer. */
  911. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  912. /** Turns 2 bytes into a little-endian integer. */
  913. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  914. /** Turns 4 bytes into a big-endian integer. */
  915. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  916. /** Turns 2 bytes into a big-endian integer. */
  917. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  918. #else
  919. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  920. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  921. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  922. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  923. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  924. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  925. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  926. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  927. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  928. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  929. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  930. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  931. /** Turns 4 bytes into a little-endian integer. */
  932. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  933. /** Turns 2 bytes into a little-endian integer. */
  934. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  935. /** Turns 4 bytes into a big-endian integer. */
  936. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  937. /** Turns 2 bytes into a big-endian integer. */
  938. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  939. #endif
  940. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  941. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  942. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  943. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  944. /** Copies a 24-bit number to 3 little-endian bytes. */
  945. inline void littleEndian24BitToChars (const int value, char* const destBytes) throw() { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); }
  946. /** Copies a 24-bit number to 3 big-endian bytes. */
  947. inline void bigEndian24BitToChars (const int value, char* const destBytes) throw() { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); }
  948. /** Fast floating-point-to-integer conversion.
  949. This is faster than using the normal c++ cast to convert a double to an int, and
  950. it will round the value to the nearest integer, rather than rounding it down
  951. like the normal cast does.
  952. Note that this routine gets its speed at the expense of some accuracy, and when
  953. rounding values whose floating point component is exactly 0.5, odd numbers and
  954. even numbers will be rounded up or down differently. For a more accurate conversion,
  955. see roundDoubleToIntAccurate().
  956. */
  957. inline int roundDoubleToInt (const double value) throw()
  958. {
  959. union { int asInt[2]; double asDouble; } n;
  960. n.asDouble = value + 6755399441055744.0;
  961. #if JUCE_BIG_ENDIAN
  962. return n.asInt [1];
  963. #else
  964. return n.asInt [0];
  965. #endif
  966. }
  967. /** Fast floating-point-to-integer conversion.
  968. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  969. fine for values above zero, but negative numbers are rounded the wrong way.
  970. */
  971. inline int roundDoubleToIntAccurate (const double value) throw()
  972. {
  973. return roundDoubleToInt (value + 1.5e-8);
  974. }
  975. /** Fast floating-point-to-integer conversion.
  976. This is faster than using the normal c++ cast to convert a float to an int, and
  977. it will round the value to the nearest integer, rather than rounding it down
  978. like the normal cast does.
  979. Note that this routine gets its speed at the expense of some accuracy, and when
  980. rounding values whose floating point component is exactly 0.5, odd numbers and
  981. even numbers will be rounded up or down differently.
  982. */
  983. inline int roundFloatToInt (const float value) throw()
  984. {
  985. union { int asInt[2]; double asDouble; } n;
  986. n.asDouble = value + 6755399441055744.0;
  987. #if JUCE_BIG_ENDIAN
  988. return n.asInt [1];
  989. #else
  990. return n.asInt [0];
  991. #endif
  992. }
  993. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  994. /********* End of inlined file: juce_DataConversions.h *********/
  995. /********* Start of inlined file: juce_Logger.h *********/
  996. #ifndef __JUCE_LOGGER_JUCEHEADER__
  997. #define __JUCE_LOGGER_JUCEHEADER__
  998. /********* Start of inlined file: juce_String.h *********/
  999. #ifndef __JUCE_STRING_JUCEHEADER__
  1000. #define __JUCE_STRING_JUCEHEADER__
  1001. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1002. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1003. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1004. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1005. (in the default system encoding) as its internal representation.
  1006. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1007. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1008. literals in the T("abcd") macro, so that it all works nicely either way round.
  1009. */
  1010. #if JUCE_STRINGS_ARE_UNICODE
  1011. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1012. typedef juce_wchar tchar;
  1013. #define juce_tcharToWideChar(c) (c)
  1014. #else
  1015. #define JUCE_T(stringLiteral) (stringLiteral)
  1016. typedef char tchar;
  1017. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1018. #endif
  1019. #if ! JUCE_DONT_DEFINE_MACROS
  1020. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1021. or unicode.
  1022. If you write your string literals in the form T("xyz"), this will either be compiled
  1023. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1024. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1025. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1026. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1027. the juce/src directory) to avoid defining this macro. See the comments in
  1028. juce_withoutMacros.h for more info.
  1029. */
  1030. #define T(stringLiteral) JUCE_T(stringLiteral)
  1031. #endif
  1032. /**
  1033. A set of methods for manipulating characters and character strings, with
  1034. duplicate methods to handle 8-bit and unicode characters.
  1035. These are defined as wrappers around the basic C string handlers, to provide
  1036. a clean, cross-platform layer, (because various platforms differ in the
  1037. range of C library calls that they provide).
  1038. @see String
  1039. */
  1040. class JUCE_API CharacterFunctions
  1041. {
  1042. public:
  1043. static int length (const char* const s) throw();
  1044. static int length (const juce_wchar* const s) throw();
  1045. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1046. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1047. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1048. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1049. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1050. static void append (char* dest, const char* src) throw();
  1051. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1052. static int compare (const char* const s1, const char* const s2) throw();
  1053. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1054. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1055. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1056. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1057. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1058. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1059. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1060. static const char* find (const char* const haystack, const char* const needle) throw();
  1061. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1062. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1063. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1064. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1065. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1066. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1067. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1068. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1069. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1070. static int getIntValue (const char* const s) throw();
  1071. static int getIntValue (const juce_wchar* s) throw();
  1072. static int64 getInt64Value (const char* s) throw();
  1073. static int64 getInt64Value (const juce_wchar* s) throw();
  1074. static double getDoubleValue (const char* const s) throw();
  1075. static double getDoubleValue (const juce_wchar* const s) throw();
  1076. static char toUpperCase (const char character) throw();
  1077. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1078. static void toUpperCase (char* s) throw();
  1079. static void toUpperCase (juce_wchar* s) throw();
  1080. static bool isUpperCase (const char character) throw();
  1081. static bool isUpperCase (const juce_wchar character) throw();
  1082. static char toLowerCase (const char character) throw();
  1083. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1084. static void toLowerCase (char* s) throw();
  1085. static void toLowerCase (juce_wchar* s) throw();
  1086. static bool isLowerCase (const char character) throw();
  1087. static bool isLowerCase (const juce_wchar character) throw();
  1088. static bool isWhitespace (const char character) throw();
  1089. static bool isWhitespace (const juce_wchar character) throw();
  1090. static bool isDigit (const char character) throw();
  1091. static bool isDigit (const juce_wchar character) throw();
  1092. static bool isLetter (const char character) throw();
  1093. static bool isLetter (const juce_wchar character) throw();
  1094. static bool isLetterOrDigit (const char character) throw();
  1095. static bool isLetterOrDigit (const juce_wchar character) throw();
  1096. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1097. hex digit.
  1098. */
  1099. static int getHexDigitValue (const tchar digit) throw();
  1100. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1101. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1102. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1103. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1104. };
  1105. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1106. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1107. /**
  1108. The JUCE String class!
  1109. Using a reference-counted internal representation, these strings are fast
  1110. and efficient, and there are methods to do just about any operation you'll ever
  1111. dream of.
  1112. @see StringArray, StringPairArray
  1113. */
  1114. class JUCE_API String
  1115. {
  1116. public:
  1117. /** Creates an empty string.
  1118. @see empty
  1119. */
  1120. String() throw();
  1121. /** Creates a copy of another string. */
  1122. String (const String& other) throw();
  1123. /** Creates a string from a zero-terminated text string.
  1124. The string is assumed to be stored in the default system encoding.
  1125. */
  1126. String (const char* const text) throw();
  1127. /** Creates a string from an string of characters.
  1128. This will use up the the first maxChars characters of the string (or
  1129. less if the string is actually shorter)
  1130. */
  1131. String (const char* const text,
  1132. const int maxChars) throw();
  1133. /** Creates a string from a zero-terminated unicode text string. */
  1134. String (const juce_wchar* const unicodeText) throw();
  1135. /** Creates a string from a unicode text string.
  1136. This will use up the the first maxChars characters of the string (or
  1137. less if the string is actually shorter)
  1138. */
  1139. String (const juce_wchar* const unicodeText,
  1140. const int maxChars) throw();
  1141. /** Creates a string from a single character. */
  1142. static const String charToString (const tchar character) throw();
  1143. /** Destructor. */
  1144. ~String() throw();
  1145. /** This is an empty string that can be used whenever one is needed.
  1146. It's better to use this than String() because it explains what's going on
  1147. and is more efficient.
  1148. */
  1149. static const String empty;
  1150. /** Generates a probably-unique 32-bit hashcode from this string. */
  1151. int hashCode() const throw();
  1152. /** Generates a probably-unique 64-bit hashcode from this string. */
  1153. int64 hashCode64() const throw();
  1154. /** Returns the number of characters in the string. */
  1155. int length() const throw();
  1156. // Assignment and concatenation operators..
  1157. /** Replaces this string's contents with another string. */
  1158. const String& operator= (const tchar* const other) throw();
  1159. /** Replaces this string's contents with another string. */
  1160. const String& operator= (const String& other) throw();
  1161. /** Appends another string at the end of this one. */
  1162. const String& operator+= (const tchar* const textToAppend) throw();
  1163. /** Appends another string at the end of this one. */
  1164. const String& operator+= (const String& stringToAppend) throw();
  1165. /** Appends a character at the end of this string. */
  1166. const String& operator+= (const char characterToAppend) throw();
  1167. /** Appends a character at the end of this string. */
  1168. const String& operator+= (const juce_wchar characterToAppend) throw();
  1169. /** Appends a string at the end of this one.
  1170. @param textToAppend the string to add
  1171. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1172. */
  1173. void append (const tchar* const textToAppend,
  1174. const int maxCharsToTake) throw();
  1175. /** Appends a string at the end of this one.
  1176. @returns the concatenated string
  1177. */
  1178. const String operator+ (const String& stringToAppend) const throw();
  1179. /** Appends a string at the end of this one.
  1180. @returns the concatenated string
  1181. */
  1182. const String operator+ (const tchar* const textToAppend) const throw();
  1183. /** Appends a character at the end of this one.
  1184. @returns the concatenated string
  1185. */
  1186. const String operator+ (const tchar characterToAppend) const throw();
  1187. /** Appends a character at the end of this string. */
  1188. String& operator<< (const char n) throw();
  1189. /** Appends a character at the end of this string. */
  1190. String& operator<< (const juce_wchar n) throw();
  1191. /** Appends another string at the end of this one. */
  1192. String& operator<< (const char* const text) throw();
  1193. /** Appends another string at the end of this one. */
  1194. String& operator<< (const juce_wchar* const text) throw();
  1195. /** Appends another string at the end of this one. */
  1196. String& operator<< (const String& text) throw();
  1197. /** Appends a decimal number at the end of this string. */
  1198. String& operator<< (const short number) throw();
  1199. /** Appends a decimal number at the end of this string. */
  1200. String& operator<< (const int number) throw();
  1201. /** Appends a decimal number at the end of this string. */
  1202. String& operator<< (const unsigned int number) throw();
  1203. /** Appends a decimal number at the end of this string. */
  1204. String& operator<< (const float number) throw();
  1205. /** Appends a decimal number at the end of this string. */
  1206. String& operator<< (const double number) throw();
  1207. // Comparison methods..
  1208. /** Returns true if the string contains no characters.
  1209. Note that there's also an isNotEmpty() method to help write readable code.
  1210. @see containsNonWhitespaceChars()
  1211. */
  1212. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1213. /** Returns true if the string contains at least one character.
  1214. Note that there's also an isEmpty() method to help write readable code.
  1215. @see containsNonWhitespaceChars()
  1216. */
  1217. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1218. /** Case-sensitive comparison with another string. */
  1219. bool operator== (const String& other) const throw();
  1220. /** Case-sensitive comparison with another string. */
  1221. bool operator== (const tchar* const other) const throw();
  1222. /** Case-sensitive comparison with another string. */
  1223. bool operator!= (const String& other) const throw();
  1224. /** Case-sensitive comparison with another string. */
  1225. bool operator!= (const tchar* const other) const throw();
  1226. /** Case-insensitive comparison with another string. */
  1227. bool equalsIgnoreCase (const String& other) const throw();
  1228. /** Case-insensitive comparison with another string. */
  1229. bool equalsIgnoreCase (const tchar* const other) const throw();
  1230. /** Case-sensitive comparison with another string. */
  1231. bool operator> (const String& other) const throw();
  1232. /** Case-sensitive comparison with another string. */
  1233. bool operator< (const tchar* const other) const throw();
  1234. /** Case-sensitive comparison with another string. */
  1235. bool operator>= (const String& other) const throw();
  1236. /** Case-sensitive comparison with another string. */
  1237. bool operator<= (const tchar* const other) const throw();
  1238. /** Case-sensitive comparison with another string.
  1239. @returns 0 if the two strings are identical; negative if this string
  1240. comes before the other one alphabetically, or positive if it
  1241. comes after it.
  1242. */
  1243. int compare (const tchar* const other) const throw();
  1244. /** Case-insensitive comparison with another string.
  1245. @returns 0 if the two strings are identical; negative if this string
  1246. comes before the other one alphabetically, or positive if it
  1247. comes after it.
  1248. */
  1249. int compareIgnoreCase (const tchar* const other) const throw();
  1250. /** Lexicographic comparison with another string.
  1251. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1252. characters, making it good for sorting human-readable strings.
  1253. @returns 0 if the two strings are identical; negative if this string
  1254. comes before the other one alphabetically, or positive if it
  1255. comes after it.
  1256. */
  1257. int compareLexicographically (const tchar* const other) const throw();
  1258. /** Tests whether the string begins with another string.
  1259. Uses a case-sensitive comparison.
  1260. */
  1261. bool startsWith (const tchar* const text) const throw();
  1262. /** Tests whether the string begins with a particular character.
  1263. Uses a case-sensitive comparison.
  1264. */
  1265. bool startsWithChar (const tchar character) const throw();
  1266. /** Tests whether the string begins with another string.
  1267. Uses a case-insensitive comparison.
  1268. */
  1269. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1270. /** Tests whether the string ends with another string.
  1271. Uses a case-sensitive comparison.
  1272. */
  1273. bool endsWith (const tchar* const text) const throw();
  1274. /** Tests whether the string ends with a particular character.
  1275. Uses a case-sensitive comparison.
  1276. */
  1277. bool endsWithChar (const tchar character) const throw();
  1278. /** Tests whether the string ends with another string.
  1279. Uses a case-insensitive comparison.
  1280. */
  1281. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1282. /** Tests whether the string contains another substring.
  1283. Uses a case-sensitive comparison.
  1284. */
  1285. bool contains (const tchar* const text) const throw();
  1286. /** Tests whether the string contains a particular character.
  1287. Uses a case-sensitive comparison.
  1288. */
  1289. bool containsChar (const tchar character) const throw();
  1290. /** Tests whether the string contains another substring.
  1291. Uses a case-insensitive comparison.
  1292. */
  1293. bool containsIgnoreCase (const tchar* const text) const throw();
  1294. /** Tests whether the string contains another substring as a distict word.
  1295. @returns true if the string contains this word, surrounded by
  1296. non-alphanumeric characters
  1297. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1298. */
  1299. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1300. /** Tests whether the string contains another substring as a distict word.
  1301. @returns true if the string contains this word, surrounded by
  1302. non-alphanumeric characters
  1303. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1304. */
  1305. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1306. /** Finds an instance of another substring if it exists as a distict word.
  1307. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1308. then this will return the index of the start of the substring. If it isn't
  1309. found, then it will return -1
  1310. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1311. */
  1312. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1313. /** Finds an instance of another substring if it exists as a distict word.
  1314. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1315. then this will return the index of the start of the substring. If it isn't
  1316. found, then it will return -1
  1317. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1318. */
  1319. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1320. /** Looks for any of a set of characters in the string.
  1321. Uses a case-sensitive comparison.
  1322. @returns true if the string contains any of the characters from
  1323. the string that is passed in.
  1324. */
  1325. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1326. /** Looks for a set of characters in the string.
  1327. Uses a case-sensitive comparison.
  1328. @returns true if the all the characters in the string are also found in the
  1329. string that is passed in.
  1330. */
  1331. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1332. /** Returns true if this string contains any non-whitespace characters.
  1333. This will return false if the string contains only whitespace characters, or
  1334. if it's empty.
  1335. It is equivalent to calling "myString.trim().isNotEmpty()".
  1336. */
  1337. bool containsNonWhitespaceChars() const throw();
  1338. /** Returns true if the string matches this simple wildcard expression.
  1339. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1340. This isn't a full-blown regex though! The only wildcard characters supported
  1341. are "*" and "?". It's mainly intended for filename pattern matching.
  1342. */
  1343. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1344. // Substring location methods..
  1345. /** Searches for a character inside this string.
  1346. Uses a case-sensitive comparison.
  1347. @returns the index of the first occurrence of the character in this
  1348. string, or -1 if it's not found.
  1349. */
  1350. int indexOfChar (const tchar characterToLookFor) const throw();
  1351. /** Searches for a character inside this string.
  1352. Uses a case-sensitive comparison.
  1353. @param startIndex the index from which the search should proceed
  1354. @param characterToLookFor the character to look for
  1355. @returns the index of the first occurrence of the character in this
  1356. string, or -1 if it's not found.
  1357. */
  1358. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1359. /** Returns the index of the first character that matches one of the characters
  1360. passed-in to this method.
  1361. This scans the string, beginning from the startIndex supplied, and if it finds
  1362. a character that appears in the string charactersToLookFor, it returns its index.
  1363. If none of these characters are found, it returns -1.
  1364. If ignoreCase is true, the comparison will be case-insensitive.
  1365. @see indexOfChar, lastIndexOfAnyOf
  1366. */
  1367. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1368. const int startIndex = 0,
  1369. const bool ignoreCase = false) const throw();
  1370. /** Searches for a substring within this string.
  1371. Uses a case-sensitive comparison.
  1372. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1373. */
  1374. int indexOf (const tchar* const text) const throw();
  1375. /** Searches for a substring within this string.
  1376. Uses a case-sensitive comparison.
  1377. @param startIndex the index from which the search should proceed
  1378. @param textToLookFor the string to search for
  1379. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1380. */
  1381. int indexOf (const int startIndex,
  1382. const tchar* const textToLookFor) const throw();
  1383. /** Searches for a substring within this string.
  1384. Uses a case-insensitive comparison.
  1385. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1386. */
  1387. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1388. /** Searches for a substring within this string.
  1389. Uses a case-insensitive comparison.
  1390. @param startIndex the index from which the search should proceed
  1391. @param textToLookFor the string to search for
  1392. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1393. */
  1394. int indexOfIgnoreCase (const int startIndex,
  1395. const tchar* const textToLookFor) const throw();
  1396. /** Searches for a character inside this string (working backwards from the end of the string).
  1397. Uses a case-sensitive comparison.
  1398. @returns the index of the last occurrence of the character in this
  1399. string, or -1 if it's not found.
  1400. */
  1401. int lastIndexOfChar (const tchar character) const throw();
  1402. /** Searches for a substring inside this string (working backwards from the end of the string).
  1403. Uses a case-sensitive comparison.
  1404. @returns the index of the start of the last occurrence of the
  1405. substring within this string, or -1 if it's not found.
  1406. */
  1407. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1408. /** Searches for a substring inside this string (working backwards from the end of the string).
  1409. Uses a case-insensitive comparison.
  1410. @returns the index of the start of the last occurrence of the
  1411. substring within this string, or -1 if it's not found.
  1412. */
  1413. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1414. /** Returns the index of the last character in this string that matches one of the
  1415. characters passed-in to this method.
  1416. This scans the string backwards, starting from its end, and if it finds
  1417. a character that appears in the string charactersToLookFor, it returns its index.
  1418. If none of these characters are found, it returns -1.
  1419. If ignoreCase is true, the comparison will be case-insensitive.
  1420. @see lastIndexOf, indexOfAnyOf
  1421. */
  1422. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1423. const bool ignoreCase = false) const throw();
  1424. // Substring extraction and manipulation methods..
  1425. /** Returns the character at this index in the string.
  1426. No checks are made to see if the index is within a valid range, so be careful!
  1427. */
  1428. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1429. /** Returns a character from the string such that it can also be altered.
  1430. This can be used as a way of easily changing characters in the string.
  1431. Note that the index passed-in is not checked to see whether it's in-range, so
  1432. be careful when using this.
  1433. */
  1434. tchar& operator[] (const int index) throw();
  1435. /** Returns the final character of the string.
  1436. If the string is empty this will return 0.
  1437. */
  1438. tchar getLastCharacter() const throw();
  1439. /** Returns a subsection of the string.
  1440. If the range specified is beyond the limits of the string, as much as
  1441. possible is returned.
  1442. @param startIndex the index of the start of the substring needed
  1443. @param endIndex all characters from startIndex up to (but not including)
  1444. this index are returned
  1445. @see fromFirstOccurrenceOf, dropLastCharacters, upToFirstOccurrenceOf
  1446. */
  1447. const String substring (int startIndex,
  1448. int endIndex) const throw();
  1449. /** Returns a section of the string, starting from a given position.
  1450. @param startIndex the first character to include. If this is beyond the end
  1451. of the string, an empty string is returned. If it is zero or
  1452. less, the whole string is returned.
  1453. @returns the substring from startIndex up to the end of the string
  1454. @see dropLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1455. */
  1456. const String substring (const int startIndex) const throw();
  1457. /** Returns a version of this string with a number of characters removed
  1458. from the end.
  1459. @param numberToDrop the number of characters to drop from the end of the
  1460. string. If this is greater than the length of the string,
  1461. an empty string will be returned. If zero or less, the
  1462. original string will be returned.
  1463. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1464. */
  1465. const String dropLastCharacters (const int numberToDrop) const throw();
  1466. /** Returns a section of the string starting from a given substring.
  1467. This will search for the first occurrence of the given substring, and
  1468. return the section of the string starting from the point where this is
  1469. found (optionally not including the substring itself).
  1470. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1471. fromFirstOccurrenceOf ("34", false) would return "56".
  1472. If the substring isn't found, the method will return an empty string.
  1473. If ignoreCase is true, the comparison will be case-insensitive.
  1474. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1475. */
  1476. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1477. const bool includeSubStringInResult,
  1478. const bool ignoreCase) const throw();
  1479. /** Returns a section of the string starting from the last occurrence of a given substring.
  1480. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1481. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1482. return the whole of the original string.
  1483. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1484. */
  1485. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1486. const bool includeSubStringInResult,
  1487. const bool ignoreCase) const throw();
  1488. /** Returns the start of this string, up to the first occurrence of a substring.
  1489. This will search for the first occurrence of a given substring, and then
  1490. return a copy of the string, up to the position of this substring,
  1491. optionally including or excluding the substring itself in the result.
  1492. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1493. upTo ("34", true) would return "1234".
  1494. If the substring isn't found, this will return the whole of the original string.
  1495. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1496. */
  1497. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1498. const bool includeSubStringInResult,
  1499. const bool ignoreCase) const throw();
  1500. /** Returns the start of this string, up to the last occurrence of a substring.
  1501. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1502. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1503. */
  1504. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1505. const bool includeSubStringInResult,
  1506. const bool ignoreCase) const throw();
  1507. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1508. const String trim() const throw();
  1509. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1510. const String trimStart() const throw();
  1511. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1512. const String trimEnd() const throw();
  1513. /** Returns an upper-case version of this string. */
  1514. const String toUpperCase() const throw();
  1515. /** Returns an lower-case version of this string. */
  1516. const String toLowerCase() const throw();
  1517. /** Replaces a sub-section of the string with another string.
  1518. This will return a copy of this string, with a set of characters
  1519. from startIndex to startIndex + numCharsToReplace removed, and with
  1520. a new string inserted in their place.
  1521. Note that this is a const method, and won't alter the string itself.
  1522. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1523. it will be constrained to a valid range.
  1524. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1525. characters will be taken out.
  1526. @param stringToInsert the new string to insert at startIndex after the characters have been
  1527. removed.
  1528. */
  1529. const String replaceSection (int startIndex,
  1530. int numCharactersToReplace,
  1531. const tchar* const stringToInsert) const throw();
  1532. /** Replaces all occurrences of a substring with another string.
  1533. Returns a copy of this string, with any occurrences of stringToReplace
  1534. swapped for stringToInsertInstead.
  1535. Note that this is a const method, and won't alter the string itself.
  1536. */
  1537. const String replace (const tchar* const stringToReplace,
  1538. const tchar* const stringToInsertInstead,
  1539. const bool ignoreCase = false) const throw();
  1540. /** Returns a string with all occurrences of a character replaced with a different one. */
  1541. const String replaceCharacter (const tchar characterToReplace,
  1542. const tchar characterToInsertInstead) const throw();
  1543. /** Replaces a set of characters with another set.
  1544. Returns a string in which each character from charactersToReplace has been replaced
  1545. by the character at the equivalent position in newCharacters (so the two strings
  1546. passed in must be the same length).
  1547. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1548. Note that this is a const method, and won't affect the string itself.
  1549. */
  1550. const String replaceCharacters (const String& charactersToReplace,
  1551. const tchar* const charactersToInsertInstead) const throw();
  1552. /** Returns a version of this string that only retains a fixed set of characters.
  1553. This will return a copy of this string, omitting any characters which are not
  1554. found in the string passed-in.
  1555. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1556. Note that this is a const method, and won't alter the string itself.
  1557. */
  1558. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1559. /** Returns a version of this string with a set of characters removed.
  1560. This will return a copy of this string, omitting any characters which are
  1561. found in the string passed-in.
  1562. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1563. Note that this is a const method, and won't alter the string itself.
  1564. */
  1565. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1566. /** Returns a section from the start of the string that only contains a certain set of characters.
  1567. This returns the leftmost section of the string, up to (and not including) the
  1568. first character that doesn't appear in the string passed in.
  1569. */
  1570. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1571. /** Returns a section from the start of the string that only contains a certain set of characters.
  1572. This returns the leftmost section of the string, up to (and not including) the
  1573. first character that occurs in the string passed in.
  1574. */
  1575. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1576. /** Checks whether the string might be in quotation marks.
  1577. @returns true if the string begins with a quote character (either a double or single quote).
  1578. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1579. @see unquoted, quoted
  1580. */
  1581. bool isQuotedString() const throw();
  1582. /** Removes quotation marks from around the string, (if there are any).
  1583. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1584. at the ends of the string are not affected. If there aren't any quotes, the original string
  1585. is returned.
  1586. Note that this is a const method, and won't alter the string itself.
  1587. @see isQuotedString, quoted
  1588. */
  1589. const String unquoted() const throw();
  1590. /** Adds quotation marks around a string.
  1591. This will return a copy of the string with a quote at the start and end, (but won't
  1592. add the quote if there's already one there, so it's safe to call this on strings that
  1593. may already have quotes around them).
  1594. Note that this is a const method, and won't alter the string itself.
  1595. @param quoteCharacter the character to add at the start and end
  1596. @see isQuotedString, unquoted
  1597. */
  1598. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1599. /** Writes text into this string, using printf style-arguments.
  1600. This will replace the contents of the string with the output of this
  1601. formatted printf.
  1602. Note that using the %s token with a juce string is probably a bad idea, as
  1603. this may expect differect encodings on different platforms.
  1604. @see formatted
  1605. */
  1606. void printf (const tchar* const format, ...) throw();
  1607. /** Returns a string, created using arguments in the style of printf.
  1608. This will return a string which is the result of a sprintf using the
  1609. arguments passed-in.
  1610. Note that using the %s token with a juce string is probably a bad idea, as
  1611. this may expect differect encodings on different platforms.
  1612. @see printf, vprintf
  1613. */
  1614. static const String formatted (const tchar* const format, ...) throw();
  1615. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1616. This will replace the contents of the string with the output of this
  1617. formatted printf. Used by other methods, this is public in case it's
  1618. useful for other purposes where you want to pass a va_list through directly.
  1619. Note that using the %s token with a juce string is probably a bad idea, as
  1620. this may expect differect encodings on different platforms.
  1621. @see printf, formatted
  1622. */
  1623. void vprintf (const tchar* const format, va_list& args) throw();
  1624. /** Creates a string which is a version of a string repeated and joined together.
  1625. @param stringToRepeat the string to repeat
  1626. @param numberOfTimesToRepeat how many times to repeat it
  1627. */
  1628. static const String repeatedString (const tchar* const stringToRepeat,
  1629. int numberOfTimesToRepeat) throw();
  1630. /** Creates a string from data in an unknown format.
  1631. This looks at some binary data and tries to guess whether it's Unicode
  1632. or 8-bit characters, then returns a string that represents it correctly.
  1633. Should be able to handle Unicode endianness correctly, by looking at
  1634. the first two bytes.
  1635. */
  1636. static const String createStringFromData (const void* const data,
  1637. const int size) throw();
  1638. // Numeric conversions..
  1639. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1640. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1641. */
  1642. explicit String (const int decimalInteger) throw();
  1643. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1644. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1645. */
  1646. explicit String (const unsigned int decimalInteger) throw();
  1647. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1648. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1649. */
  1650. explicit String (const short decimalInteger) throw();
  1651. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1652. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1653. */
  1654. explicit String (const unsigned short decimalInteger) throw();
  1655. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1656. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1657. */
  1658. explicit String (const int64 largeIntegerValue) throw();
  1659. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1660. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1661. */
  1662. explicit String (const uint64 largeIntegerValue) throw();
  1663. /** Creates a string representing this floating-point number.
  1664. @param floatValue the value to convert to a string
  1665. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1666. decimal places, and will not use exponent notation. If 0 or
  1667. less, it will use exponent notation if necessary.
  1668. @see getDoubleValue, getIntValue
  1669. */
  1670. explicit String (const float floatValue,
  1671. const int numberOfDecimalPlaces = 0) throw();
  1672. /** Creates a string representing this floating-point number.
  1673. @param doubleValue the value to convert to a string
  1674. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1675. decimal places, and will not use exponent notation. If 0 or
  1676. less, it will use exponent notation if necessary.
  1677. @see getFloatValue, getIntValue
  1678. */
  1679. explicit String (const double doubleValue,
  1680. const int numberOfDecimalPlaces = 0) throw();
  1681. /** Parses this string to find its numerical value (up to 32 bits in size).
  1682. @returns the value of the string as a 32 bit signed base-10 integer.
  1683. @see getTrailingIntValue, getHexValue32, getHexValue64
  1684. */
  1685. int getIntValue() const throw();
  1686. /** Parses this string to find its numerical value (up to 64 bits in size).
  1687. @returns the value of the string as a 64 bit signed base-10 integer.
  1688. */
  1689. int64 getLargeIntValue() const throw();
  1690. /** Parses a decimal number from the end of the string.
  1691. This will look for a value at the end of the string.
  1692. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1693. Negative numbers are not handled, so "xyz-5" returns 5.
  1694. @see getIntValue
  1695. */
  1696. int getTrailingIntValue() const throw();
  1697. /** Parses this string as a floating point number.
  1698. @returns the value of the string as a 32-bit floating point value.
  1699. @see getDoubleValue
  1700. */
  1701. float getFloatValue() const throw();
  1702. /** Parses this string as a floating point number.
  1703. @returns the value of the string as a 64-bit floating point value.
  1704. @see getFloatValue
  1705. */
  1706. double getDoubleValue() const throw();
  1707. /** Parses the string as a hexadecimal number.
  1708. Non-hexadecimal characters in the string are ignored.
  1709. If the string contains too many characters, then the lowest significant
  1710. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1711. @returns a 32-bit number which is the value of the string in hex.
  1712. */
  1713. int getHexValue32() const throw();
  1714. /** Parses the string as a hexadecimal number.
  1715. Non-hexadecimal characters in the string are ignored.
  1716. If the string contains too many characters, then the lowest significant
  1717. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1718. @returns a 64-bit number which is the value of the string in hex.
  1719. */
  1720. int64 getHexValue64() const throw();
  1721. /** Creates a string representing this 32-bit value in hexadecimal. */
  1722. static const String toHexString (const int number) throw();
  1723. /** Creates a string representing this 64-bit value in hexadecimal. */
  1724. static const String toHexString (const int64 number) throw();
  1725. /** Creates a string representing this 16-bit value in hexadecimal. */
  1726. static const String toHexString (const short number) throw();
  1727. /** Creates a string containing a hex dump of a block of binary data.
  1728. @param data the binary data to use as input
  1729. @param size how many bytes of data to use
  1730. @param groupSize how many bytes are grouped together before inserting a
  1731. space into the output. e.g. group size 0 has no spaces,
  1732. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1733. like "bea1 c2ff".
  1734. */
  1735. static const String toHexString (const unsigned char* data,
  1736. const int size,
  1737. const int groupSize = 1) throw();
  1738. // Casting to character arrays..
  1739. #if JUCE_STRINGS_ARE_UNICODE
  1740. /** Returns a version of this string using the default 8-bit system encoding.
  1741. Because it returns a reference to the string's internal data, the pointer
  1742. that is returned must not be stored anywhere, as it can be deleted whenever the
  1743. string changes.
  1744. */
  1745. operator const char*() const throw();
  1746. /** Returns a unicode version of this string.
  1747. Because it returns a reference to the string's internal data, the pointer
  1748. that is returned must not be stored anywhere, as it can be deleted whenever the
  1749. string changes.
  1750. */
  1751. inline operator const juce_wchar*() const throw() { return text->text; }
  1752. #else
  1753. /** Returns a version of this string using the default 8-bit system encoding.
  1754. Because it returns a reference to the string's internal data, the pointer
  1755. that is returned must not be stored anywhere, as it can be deleted whenever the
  1756. string changes.
  1757. */
  1758. inline operator const char*() const throw() { return text->text; }
  1759. /** Returns a unicode version of this string.
  1760. Because it returns a reference to the string's internal data, the pointer
  1761. that is returned must not be stored anywhere, as it can be deleted whenever the
  1762. string changes.
  1763. */
  1764. operator const juce_wchar*() const throw();
  1765. #endif
  1766. /** Copies the string to a buffer.
  1767. @param destBuffer the place to copy it to
  1768. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1769. not including the tailing zero, so this shouldn't be
  1770. larger than the size of your destination buffer - 1
  1771. */
  1772. void copyToBuffer (char* const destBuffer,
  1773. const int maxCharsToCopy) const throw();
  1774. /** Copies the string to a unicode buffer.
  1775. @param destBuffer the place to copy it to
  1776. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1777. not including the tailing zero, so this shouldn't be
  1778. larger than the size of your destination buffer - 1
  1779. */
  1780. void copyToBuffer (juce_wchar* const destBuffer,
  1781. const int maxCharsToCopy) const throw();
  1782. /** Copies the string to a buffer as UTF-8 characters.
  1783. Returns the number of bytes copied to the buffer, including the terminating null
  1784. character.
  1785. @param destBuffer the place to copy it to; if this is a null pointer,
  1786. the method just returns the number of bytes required
  1787. (including the terminating null character).
  1788. */
  1789. int copyToUTF8 (uint8* const destBuffer) const throw();
  1790. /** Returns a pointer to a UTF-8 version of this string.
  1791. Because it returns a reference to the string's internal data, the pointer
  1792. that is returned must not be stored anywhere, as it can be deleted whenever the
  1793. string changes.
  1794. */
  1795. const char* toUTF8() const throw();
  1796. /** Creates a String from a UTF-8 encoded buffer.
  1797. If the size is < 0, it'll keep reading until it hits a zero.
  1798. */
  1799. static const String fromUTF8 (const uint8* const utf8buffer,
  1800. int bufferSizeBytes = -1) throw();
  1801. /** Increases the string's internally allocated storage.
  1802. Although the string's contents won't be affected by this call, it will
  1803. increase the amount of memory allocated internally for the string to grow into.
  1804. If you're about to make a large number of calls to methods such
  1805. as += or <<, it's more efficient to preallocate enough extra space
  1806. beforehand, so that these methods won't have to keep resizing the string
  1807. to append the extra characters.
  1808. @param numCharsNeeded the number of characters to allocate storage for. If this
  1809. value is less than the currently allocated size, it will
  1810. have no effect.
  1811. */
  1812. void preallocateStorage (const int numCharsNeeded) throw();
  1813. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1814. private:
  1815. struct InternalRefCountedStringHolder
  1816. {
  1817. int refCount;
  1818. int allocatedNumChars;
  1819. #if JUCE_STRINGS_ARE_UNICODE
  1820. wchar_t text[1];
  1821. #else
  1822. char text[1];
  1823. #endif
  1824. };
  1825. InternalRefCountedStringHolder* text;
  1826. static InternalRefCountedStringHolder emptyString;
  1827. // internal constructor that preallocates a certain amount of memory
  1828. String (const int numChars, const int dummyVariable) throw();
  1829. void deleteInternal() throw();
  1830. void createInternal (const int numChars) throw();
  1831. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1832. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1833. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1834. void dupeInternalIfMultiplyReferenced() throw();
  1835. };
  1836. /** Global operator to allow a String to be appended to a string literal.
  1837. This allows the use of expressions such as "abc" + String (x)
  1838. @see String
  1839. */
  1840. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1841. const String& string2) throw();
  1842. /** Global operator to allow a String to be appended to a string literal.
  1843. This allows the use of expressions such as "abc" + String (x)
  1844. @see String
  1845. */
  1846. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1847. const String& string2) throw();
  1848. #endif // __JUCE_STRING_JUCEHEADER__
  1849. /********* End of inlined file: juce_String.h *********/
  1850. /**
  1851. Acts as an application-wide logging class.
  1852. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1853. method and this will then be used by all calls to writeToLog.
  1854. The logger class also contains methods for writing messages to the debugger's
  1855. output stream.
  1856. @see FileLogger
  1857. */
  1858. class JUCE_API Logger
  1859. {
  1860. public:
  1861. /** Destructor. */
  1862. virtual ~Logger();
  1863. /** Sets the current logging class to use.
  1864. Note that the object passed in won't be deleted when no longer needed.
  1865. A null pointer can be passed-in to disable any logging.
  1866. If deleteOldLogger is set to true, the existing logger will be
  1867. deleted (if there is one).
  1868. */
  1869. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1870. const bool deleteOldLogger = false);
  1871. /** Writes a string to the current logger.
  1872. This will pass the string to the logger's logMessage() method if a logger
  1873. has been set.
  1874. @see logMessage
  1875. */
  1876. static void JUCE_CALLTYPE writeToLog (const String& message);
  1877. /** Writes a message to the standard error stream.
  1878. This can be called directly, or by using the DBG() macro in
  1879. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1880. */
  1881. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1882. /** Writes a message to the standard error stream.
  1883. This can be called directly, or by using the DBG_PRINTF() macro in
  1884. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1885. */
  1886. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1887. protected:
  1888. Logger();
  1889. /** This is overloaded by subclasses to implement custom logging behaviour.
  1890. @see setCurrentLogger
  1891. */
  1892. virtual void logMessage (const String& message) = 0;
  1893. };
  1894. #endif // __JUCE_LOGGER_JUCEHEADER__
  1895. /********* End of inlined file: juce_Logger.h *********/
  1896. END_JUCE_NAMESPACE
  1897. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1898. /********* End of inlined file: juce_StandardHeader.h *********/
  1899. BEGIN_JUCE_NAMESPACE
  1900. #if JUCE_MSVC
  1901. // this is set explicitly in case the app is using a different packing size.
  1902. #pragma pack (push, 8)
  1903. #pragma warning (push)
  1904. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1905. #endif
  1906. #if JUCE_MAC
  1907. #pragma align=natural
  1908. #endif
  1909. #define JUCE_PUBLIC_INCLUDES
  1910. // this is where all the class header files get brought in..
  1911. /********* Start of inlined file: juce_core_includes.h *********/
  1912. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1913. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1914. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1915. /********* Start of inlined file: juce_Atomic.h *********/
  1916. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1917. #define __JUCE_ATOMIC_JUCEHEADER__
  1918. // Atomic increment/decrement operations..
  1919. #if JUCE_MAC && ! DOXYGEN
  1920. #if ! MACOS_10_3_OR_EARLIER
  1921. forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  1922. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  1923. forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  1924. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  1925. #else
  1926. forcedinline void atomicIncrement (int& variable) throw() { OTAtomicAdd32 (1, (SInt32*) &variable); }
  1927. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (1, (SInt32*) &variable); }
  1928. forcedinline void atomicDecrement (int& variable) throw() { OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1929. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1930. #endif
  1931. #elif JUCE_GCC
  1932. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  1933. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  1934. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  1935. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  1936. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  1937. #else
  1938. /** Increments an integer in a thread-safe way. */
  1939. forcedinline void atomicIncrement (int& variable) throw()
  1940. {
  1941. __asm__ __volatile__ (
  1942. #if JUCE_64BIT
  1943. "lock incl (%%rax)"
  1944. :
  1945. : "a" (&variable)
  1946. : "cc", "memory");
  1947. #else
  1948. "lock incl %0"
  1949. : "=m" (variable)
  1950. : "m" (variable));
  1951. #endif
  1952. }
  1953. /** Increments an integer in a thread-safe way and returns the incremented value. */
  1954. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  1955. {
  1956. int result;
  1957. __asm__ __volatile__ (
  1958. #if JUCE_64BIT
  1959. "lock xaddl %%ebx, (%%rax) \n\
  1960. incl %%ebx"
  1961. : "=b" (result)
  1962. : "a" (&variable), "b" (1)
  1963. : "cc", "memory");
  1964. #else
  1965. "lock xaddl %%eax, (%%ecx) \n\
  1966. incl %%eax"
  1967. : "=a" (result)
  1968. : "c" (&variable), "a" (1)
  1969. : "memory");
  1970. #endif
  1971. return result;
  1972. }
  1973. /** Decrememts an integer in a thread-safe way. */
  1974. forcedinline void atomicDecrement (int& variable) throw()
  1975. {
  1976. __asm__ __volatile__ (
  1977. #if JUCE_64BIT
  1978. "lock decl (%%rax)"
  1979. :
  1980. : "a" (&variable)
  1981. : "cc", "memory");
  1982. #else
  1983. "lock decl %0"
  1984. : "=m" (variable)
  1985. : "m" (variable));
  1986. #endif
  1987. }
  1988. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  1989. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  1990. {
  1991. int result;
  1992. __asm__ __volatile__ (
  1993. #if JUCE_64BIT
  1994. "lock xaddl %%ebx, (%%rax) \n\
  1995. decl %%ebx"
  1996. : "=b" (result)
  1997. : "a" (&variable), "b" (-1)
  1998. : "cc", "memory");
  1999. #else
  2000. "lock xaddl %%eax, (%%ecx) \n\
  2001. decl %%eax"
  2002. : "=a" (result)
  2003. : "c" (&variable), "a" (-1)
  2004. : "memory");
  2005. #endif
  2006. return result;
  2007. }
  2008. #endif
  2009. #elif JUCE_USE_INTRINSICS
  2010. #pragma intrinsic (_InterlockedIncrement)
  2011. #pragma intrinsic (_InterlockedDecrement)
  2012. /** Increments an integer in a thread-safe way. */
  2013. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2014. {
  2015. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2016. }
  2017. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2018. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2019. {
  2020. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2021. }
  2022. /** Decrememts an integer in a thread-safe way. */
  2023. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2024. {
  2025. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2026. }
  2027. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2028. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2029. {
  2030. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2031. }
  2032. #else
  2033. /** Increments an integer in a thread-safe way. */
  2034. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2035. {
  2036. __asm {
  2037. mov ecx, dword ptr [variable]
  2038. lock inc dword ptr [ecx]
  2039. }
  2040. }
  2041. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2042. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2043. {
  2044. int result;
  2045. __asm {
  2046. mov ecx, dword ptr [variable]
  2047. mov eax, 1
  2048. lock xadd dword ptr [ecx], eax
  2049. inc eax
  2050. mov result, eax
  2051. }
  2052. return result;
  2053. }
  2054. /** Decrememts an integer in a thread-safe way. */
  2055. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2056. {
  2057. __asm {
  2058. mov ecx, dword ptr [variable]
  2059. lock dec dword ptr [ecx]
  2060. }
  2061. }
  2062. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2063. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2064. {
  2065. int result;
  2066. __asm {
  2067. mov ecx, dword ptr [variable]
  2068. mov eax, -1
  2069. lock xadd dword ptr [ecx], eax
  2070. dec eax
  2071. mov result, eax
  2072. }
  2073. return result;
  2074. }
  2075. #endif
  2076. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2077. /********* End of inlined file: juce_Atomic.h *********/
  2078. #endif
  2079. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  2080. #endif
  2081. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2082. /********* Start of inlined file: juce_FileLogger.h *********/
  2083. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2084. #define __JUCE_FILELOGGER_JUCEHEADER__
  2085. /********* Start of inlined file: juce_File.h *********/
  2086. #ifndef __JUCE_FILE_JUCEHEADER__
  2087. #define __JUCE_FILE_JUCEHEADER__
  2088. /********* Start of inlined file: juce_OwnedArray.h *********/
  2089. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2090. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2091. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2092. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2093. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2094. /** The default size of chunk in which arrays increase their storage.
  2095. Used by ArrayAllocationBase and its subclasses.
  2096. */
  2097. const int juceDefaultArrayGranularity = 8;
  2098. /**
  2099. Implements some basic array storage allocation functions.
  2100. This class isn't really for public use - it's used by the other
  2101. array classes, but might come in handy for some purposes.
  2102. @see Array, OwnedArray, ReferenceCountedArray
  2103. */
  2104. template <class ElementType>
  2105. class ArrayAllocationBase
  2106. {
  2107. protected:
  2108. /** Creates an empty array.
  2109. @param granularity_ this is the size of increment by which the internal storage
  2110. will be increased.
  2111. */
  2112. ArrayAllocationBase (const int granularity_) throw()
  2113. : elements (0),
  2114. numAllocated (0),
  2115. granularity (granularity_)
  2116. {
  2117. }
  2118. /** Destructor. */
  2119. ~ArrayAllocationBase() throw()
  2120. {
  2121. delete[] elements;
  2122. }
  2123. /** Changes the amount of storage allocated.
  2124. This will retain any data currently held in the array, and either add or
  2125. remove extra space at the end.
  2126. @param numElements the number of elements that are needed
  2127. */
  2128. void setAllocatedSize (const int numElements) throw()
  2129. {
  2130. if (numAllocated != numElements)
  2131. {
  2132. if (numElements > 0)
  2133. {
  2134. ElementType* const newElements = new ElementType [numElements];
  2135. const int itemsToRetain = jmin (numElements, numAllocated);
  2136. for (int i = 0; i < itemsToRetain; ++i)
  2137. newElements[i] = elements[i];
  2138. delete[] elements;
  2139. elements = newElements;
  2140. }
  2141. else if (elements != 0)
  2142. {
  2143. delete[] elements;
  2144. elements = 0;
  2145. }
  2146. numAllocated = numElements;
  2147. }
  2148. }
  2149. /** Increases the amount of storage allocated if it is less than a given amount.
  2150. This will retain any data currently held in the array, but will add
  2151. extra space at the end to make sure there it's at least as big as the size
  2152. passed in. If it's already bigger, no action is taken.
  2153. @param minNumElements the minimum number of elements that are needed
  2154. */
  2155. void ensureAllocatedSize (int minNumElements) throw()
  2156. {
  2157. if (minNumElements > numAllocated)
  2158. {
  2159. // for arrays with small granularity that get big, start
  2160. // increasing the size in bigger jumps
  2161. if (minNumElements > (granularity << 6))
  2162. {
  2163. minNumElements += (minNumElements / granularity);
  2164. if (minNumElements > (granularity << 8))
  2165. minNumElements += granularity << 6;
  2166. else
  2167. minNumElements += granularity << 5;
  2168. }
  2169. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2170. }
  2171. }
  2172. ElementType* elements;
  2173. int numAllocated, granularity;
  2174. private:
  2175. ArrayAllocationBase (const ArrayAllocationBase&);
  2176. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2177. };
  2178. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2179. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2180. /********* Start of inlined file: juce_ElementComparator.h *********/
  2181. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2182. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2183. /**
  2184. Sorts a range of elements in an array.
  2185. The comparator object that is passed-in must define a public method with the following
  2186. signature:
  2187. @code
  2188. int compareElements (ElementType first, ElementType second);
  2189. @endcode
  2190. ..and this method must return:
  2191. - a value of < 0 if the first comes before the second
  2192. - a value of 0 if the two objects are equivalent
  2193. - a value of > 0 if the second comes before the first
  2194. To improve performance, the compareElements() method can be declared as static or const.
  2195. @param comparator an object which defines a compareElements() method
  2196. @param array the array to sort
  2197. @param firstElement the index of the first element of the range to be sorted
  2198. @param lastElement the index of the last element in the range that needs
  2199. sorting (this is inclusive)
  2200. @param retainOrderOfEquivalentItems if true, the order of items that the
  2201. comparator deems the same will be maintained - this will be
  2202. a slower algorithm than if they are allowed to be moved around.
  2203. @see sortArrayRetainingOrder
  2204. */
  2205. template <class ElementType, class ElementComparator>
  2206. static void sortArray (ElementComparator& comparator,
  2207. ElementType* const array,
  2208. int firstElement,
  2209. int lastElement,
  2210. const bool retainOrderOfEquivalentItems)
  2211. {
  2212. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2213. // avoids getting warning messages about the parameter being unused
  2214. if (lastElement > firstElement)
  2215. {
  2216. if (retainOrderOfEquivalentItems)
  2217. {
  2218. for (int i = firstElement; i < lastElement; ++i)
  2219. {
  2220. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2221. {
  2222. const ElementType temp = array [i];
  2223. array [i] = array[i + 1];
  2224. array [i + 1] = temp;
  2225. if (i > firstElement)
  2226. i -= 2;
  2227. }
  2228. }
  2229. }
  2230. else
  2231. {
  2232. int fromStack[30], toStack[30];
  2233. int stackIndex = 0;
  2234. for (;;)
  2235. {
  2236. const int size = (lastElement - firstElement) + 1;
  2237. if (size <= 8)
  2238. {
  2239. int j = lastElement;
  2240. int maxIndex;
  2241. while (j > firstElement)
  2242. {
  2243. maxIndex = firstElement;
  2244. for (int k = firstElement + 1; k <= j; ++k)
  2245. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2246. maxIndex = k;
  2247. const ElementType temp = array [maxIndex];
  2248. array [maxIndex] = array[j];
  2249. array [j] = temp;
  2250. --j;
  2251. }
  2252. }
  2253. else
  2254. {
  2255. const int mid = firstElement + (size >> 1);
  2256. ElementType temp = array [mid];
  2257. array [mid] = array [firstElement];
  2258. array [firstElement] = temp;
  2259. int i = firstElement;
  2260. int j = lastElement + 1;
  2261. for (;;)
  2262. {
  2263. while (++i <= lastElement
  2264. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2265. {}
  2266. while (--j > firstElement
  2267. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2268. {}
  2269. if (j < i)
  2270. break;
  2271. temp = array[i];
  2272. array[i] = array[j];
  2273. array[j] = temp;
  2274. }
  2275. temp = array [firstElement];
  2276. array [firstElement] = array[j];
  2277. array [j] = temp;
  2278. if (j - 1 - firstElement >= lastElement - i)
  2279. {
  2280. if (firstElement + 1 < j)
  2281. {
  2282. fromStack [stackIndex] = firstElement;
  2283. toStack [stackIndex] = j - 1;
  2284. ++stackIndex;
  2285. }
  2286. if (i < lastElement)
  2287. {
  2288. firstElement = i;
  2289. continue;
  2290. }
  2291. }
  2292. else
  2293. {
  2294. if (i < lastElement)
  2295. {
  2296. fromStack [stackIndex] = i;
  2297. toStack [stackIndex] = lastElement;
  2298. ++stackIndex;
  2299. }
  2300. if (firstElement + 1 < j)
  2301. {
  2302. lastElement = j - 1;
  2303. continue;
  2304. }
  2305. }
  2306. }
  2307. if (--stackIndex < 0)
  2308. break;
  2309. jassert (stackIndex < numElementsInArray (fromStack));
  2310. firstElement = fromStack [stackIndex];
  2311. lastElement = toStack [stackIndex];
  2312. }
  2313. }
  2314. }
  2315. }
  2316. /**
  2317. Searches a sorted array of elements, looking for the index at which a specified value
  2318. should be inserted for it to be in the correct order.
  2319. The comparator object that is passed-in must define a public method with the following
  2320. signature:
  2321. @code
  2322. int compareElements (ElementType first, ElementType second);
  2323. @endcode
  2324. ..and this method must return:
  2325. - a value of < 0 if the first comes before the second
  2326. - a value of 0 if the two objects are equivalent
  2327. - a value of > 0 if the second comes before the first
  2328. To improve performance, the compareElements() method can be declared as static or const.
  2329. @param comparator an object which defines a compareElements() method
  2330. @param array the array to search
  2331. @param newElement the value that is going to be inserted
  2332. @param firstElement the index of the first element to search
  2333. @param lastElement the index of the last element in the range (this is non-inclusive)
  2334. */
  2335. template <class ElementType, class ElementComparator>
  2336. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2337. ElementType* const array,
  2338. const ElementType newElement,
  2339. int firstElement,
  2340. int lastElement)
  2341. {
  2342. jassert (firstElement <= lastElement);
  2343. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2344. // avoids getting warning messages about the parameter being unused
  2345. while (firstElement < lastElement)
  2346. {
  2347. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2348. {
  2349. ++firstElement;
  2350. break;
  2351. }
  2352. else
  2353. {
  2354. const int halfway = (firstElement + lastElement) >> 1;
  2355. if (halfway == firstElement)
  2356. {
  2357. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2358. ++firstElement;
  2359. break;
  2360. }
  2361. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2362. {
  2363. firstElement = halfway;
  2364. }
  2365. else
  2366. {
  2367. lastElement = halfway;
  2368. }
  2369. }
  2370. }
  2371. return firstElement;
  2372. }
  2373. /**
  2374. A simple ElementComparator class that can be used to sort an array of
  2375. integer primitive objects.
  2376. Example: @code
  2377. Array <int> myArray;
  2378. IntegerElementComparator<int> sorter;
  2379. myArray.sort (sorter);
  2380. @endcode
  2381. For floating point values, see the FloatElementComparator class instead.
  2382. @see FloatElementComparator, ElementComparator
  2383. */
  2384. template <class ElementType>
  2385. class IntegerElementComparator
  2386. {
  2387. public:
  2388. static int compareElements (const ElementType first,
  2389. const ElementType second) throw()
  2390. {
  2391. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2392. }
  2393. };
  2394. /**
  2395. A simple ElementComparator class that can be used to sort an array of numeric
  2396. double or floating point primitive objects.
  2397. Example: @code
  2398. Array <double> myArray;
  2399. FloatElementComparator<double> sorter;
  2400. myArray.sort (sorter);
  2401. @endcode
  2402. For integer values, see the IntegerElementComparator class instead.
  2403. @see IntegerElementComparator, ElementComparator
  2404. */
  2405. template <class ElementType>
  2406. class FloatElementComparator
  2407. {
  2408. public:
  2409. static int compareElements (const ElementType first,
  2410. const ElementType second) throw()
  2411. {
  2412. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2413. }
  2414. };
  2415. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2416. /********* End of inlined file: juce_ElementComparator.h *********/
  2417. /********* Start of inlined file: juce_CriticalSection.h *********/
  2418. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2419. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2420. /**
  2421. Prevents multiple threads from accessing shared objects at the same time.
  2422. @see ScopedLock, Thread, InterProcessLock
  2423. */
  2424. class JUCE_API CriticalSection
  2425. {
  2426. public:
  2427. /**
  2428. Creates a CriticalSection object
  2429. */
  2430. CriticalSection() throw();
  2431. /** Destroys a CriticalSection object.
  2432. If the critical section is deleted whilst locked, its subsequent behaviour
  2433. is unpredictable.
  2434. */
  2435. ~CriticalSection() throw();
  2436. /** Locks this critical section.
  2437. If the lock is currently held by another thread, this will wait until it
  2438. becomes free.
  2439. If the lock is already held by the caller thread, the method returns immediately.
  2440. @see exit, ScopedLock
  2441. */
  2442. void enter() const throw();
  2443. /** Attempts to lock this critical section without blocking.
  2444. This method behaves identically to CriticalSection::enter, except that the caller thread
  2445. does not wait if the lock is currently held by another thread but returns false immediately.
  2446. @returns false if the lock is currently held by another thread, true otherwise.
  2447. @see enter
  2448. */
  2449. bool tryEnter() const throw();
  2450. /** Releases the lock.
  2451. If the caller thread hasn't got the lock, this can have unpredictable results.
  2452. If the enter() method has been called multiple times by the thread, each
  2453. call must be matched by a call to exit() before other threads will be allowed
  2454. to take over the lock.
  2455. @see enter, ScopedLock
  2456. */
  2457. void exit() const throw();
  2458. juce_UseDebuggingNewOperator
  2459. private:
  2460. #if JUCE_WIN32
  2461. #if JUCE_64BIT
  2462. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2463. // block of memory here that's big enough to be used internally as a windows critical
  2464. // section object.
  2465. uint8 internal [44];
  2466. #else
  2467. uint8 internal [24];
  2468. #endif
  2469. #else
  2470. mutable pthread_mutex_t internal;
  2471. #endif
  2472. CriticalSection (const CriticalSection&);
  2473. const CriticalSection& operator= (const CriticalSection&);
  2474. };
  2475. /**
  2476. A class that can be used in place of a real CriticalSection object.
  2477. This is currently used by some templated array classes, and should get
  2478. optimised out by the compiler.
  2479. @see Array, OwnedArray, ReferenceCountedArray
  2480. */
  2481. class JUCE_API DummyCriticalSection
  2482. {
  2483. public:
  2484. forcedinline DummyCriticalSection() throw() {}
  2485. forcedinline ~DummyCriticalSection() throw() {}
  2486. forcedinline void enter() const throw() {}
  2487. forcedinline void exit() const throw() {}
  2488. };
  2489. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2490. /********* End of inlined file: juce_CriticalSection.h *********/
  2491. /** An array designed for holding objects.
  2492. This holds a list of pointers to objects, and will automatically
  2493. delete the objects when they are removed from the array, or when the
  2494. array is itself deleted.
  2495. Declare it in the form: OwnedArray<MyObjectClass>
  2496. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2497. After adding objects, they are 'owned' by the array and will be deleted when
  2498. removed or replaced.
  2499. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2500. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2501. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2502. */
  2503. template <class ObjectClass,
  2504. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2505. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  2506. {
  2507. public:
  2508. /** Creates an empty array.
  2509. @param granularity this is the size of increment by which the internal storage
  2510. used by the array will grow. Only change it from the default if you know the
  2511. array is going to be very big and needs to be able to grow efficiently.
  2512. @see ArrayAllocationBase
  2513. */
  2514. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2515. : ArrayAllocationBase <ObjectClass*> (granularity),
  2516. numUsed (0)
  2517. {
  2518. }
  2519. /** Deletes the array and also deletes any objects inside it.
  2520. To get rid of the array without deleting its objects, use its
  2521. clear (false) method before deleting it.
  2522. */
  2523. ~OwnedArray()
  2524. {
  2525. clear (true);
  2526. }
  2527. /** Clears the array, optionally deleting the objects inside it first. */
  2528. void clear (const bool deleteObjects = true)
  2529. {
  2530. lock.enter();
  2531. if (deleteObjects)
  2532. {
  2533. while (numUsed > 0)
  2534. delete this->elements [--numUsed];
  2535. }
  2536. this->setAllocatedSize (0);
  2537. numUsed = 0;
  2538. lock.exit();
  2539. }
  2540. /** Returns the number of items currently in the array.
  2541. @see operator[]
  2542. */
  2543. inline int size() const throw()
  2544. {
  2545. return numUsed;
  2546. }
  2547. /** Returns a pointer to the object at this index in the array.
  2548. If the index is out-of-range, this will return a null pointer, (and
  2549. it could be null anyway, because it's ok for the array to hold null
  2550. pointers as well as objects).
  2551. @see getUnchecked
  2552. */
  2553. inline ObjectClass* operator[] (const int index) const throw()
  2554. {
  2555. lock.enter();
  2556. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2557. ? this->elements [index]
  2558. : (ObjectClass*) 0;
  2559. lock.exit();
  2560. return result;
  2561. }
  2562. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2563. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2564. it can be used when you're sure the index if always going to be legal.
  2565. */
  2566. inline ObjectClass* getUnchecked (const int index) const throw()
  2567. {
  2568. lock.enter();
  2569. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2570. ObjectClass* const result = this->elements [index];
  2571. lock.exit();
  2572. return result;
  2573. }
  2574. /** Returns a pointer to the first object in the array.
  2575. This will return a null pointer if the array's empty.
  2576. @see getLast
  2577. */
  2578. inline ObjectClass* getFirst() const throw()
  2579. {
  2580. lock.enter();
  2581. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  2582. : (ObjectClass*) 0;
  2583. lock.exit();
  2584. return result;
  2585. }
  2586. /** Returns a pointer to the last object in the array.
  2587. This will return a null pointer if the array's empty.
  2588. @see getFirst
  2589. */
  2590. inline ObjectClass* getLast() const throw()
  2591. {
  2592. lock.enter();
  2593. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  2594. : (ObjectClass*) 0;
  2595. lock.exit();
  2596. return result;
  2597. }
  2598. /** Finds the index of an object which might be in the array.
  2599. @param objectToLookFor the object to look for
  2600. @returns the index at which the object was found, or -1 if it's not found
  2601. */
  2602. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  2603. {
  2604. int result = -1;
  2605. lock.enter();
  2606. ObjectClass* const* e = this->elements;
  2607. for (int i = numUsed; --i >= 0;)
  2608. {
  2609. if (objectToLookFor == *e)
  2610. {
  2611. result = (int) (e - this->elements);
  2612. break;
  2613. }
  2614. ++e;
  2615. }
  2616. lock.exit();
  2617. return result;
  2618. }
  2619. /** Returns true if the array contains a specified object.
  2620. @param objectToLookFor the object to look for
  2621. @returns true if the object is in the array
  2622. */
  2623. bool contains (const ObjectClass* const objectToLookFor) const throw()
  2624. {
  2625. lock.enter();
  2626. ObjectClass* const* e = this->elements;
  2627. int i = numUsed;
  2628. while (i >= 4)
  2629. {
  2630. if (objectToLookFor == *e
  2631. || objectToLookFor == *++e
  2632. || objectToLookFor == *++e
  2633. || objectToLookFor == *++e)
  2634. {
  2635. lock.exit();
  2636. return true;
  2637. }
  2638. i -= 4;
  2639. ++e;
  2640. }
  2641. while (i > 0)
  2642. {
  2643. if (objectToLookFor == *e)
  2644. {
  2645. lock.exit();
  2646. return true;
  2647. }
  2648. --i;
  2649. ++e;
  2650. }
  2651. lock.exit();
  2652. return false;
  2653. }
  2654. /** Appends a new object to the end of the array.
  2655. Note that the this object will be deleted by the OwnedArray when it
  2656. is removed, so be careful not to delete it somewhere else.
  2657. Also be careful not to add the same object to the array more than once,
  2658. as this will obviously cause deletion of dangling pointers.
  2659. @param newObject the new object to add to the array
  2660. @see set, insert, addIfNotAlreadyThere, addSorted
  2661. */
  2662. void add (const ObjectClass* const newObject) throw()
  2663. {
  2664. lock.enter();
  2665. this->ensureAllocatedSize (numUsed + 1);
  2666. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2667. lock.exit();
  2668. }
  2669. /** Inserts a new object into the array at the given index.
  2670. Note that the this object will be deleted by the OwnedArray when it
  2671. is removed, so be careful not to delete it somewhere else.
  2672. If the index is less than 0 or greater than the size of the array, the
  2673. element will be added to the end of the array.
  2674. Otherwise, it will be inserted into the array, moving all the later elements
  2675. along to make room.
  2676. Be careful not to add the same object to the array more than once,
  2677. as this will obviously cause deletion of dangling pointers.
  2678. @param indexToInsertAt the index at which the new element should be inserted
  2679. @param newObject the new object to add to the array
  2680. @see add, addSorted, addIfNotAlreadyThere, set
  2681. */
  2682. void insert (int indexToInsertAt,
  2683. const ObjectClass* const newObject) throw()
  2684. {
  2685. if (indexToInsertAt >= 0)
  2686. {
  2687. lock.enter();
  2688. if (indexToInsertAt > numUsed)
  2689. indexToInsertAt = numUsed;
  2690. this->ensureAllocatedSize (numUsed + 1);
  2691. ObjectClass** const e = this->elements + indexToInsertAt;
  2692. const int numToMove = numUsed - indexToInsertAt;
  2693. if (numToMove > 0)
  2694. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  2695. *e = const_cast <ObjectClass*> (newObject);
  2696. ++numUsed;
  2697. lock.exit();
  2698. }
  2699. else
  2700. {
  2701. add (newObject);
  2702. }
  2703. }
  2704. /** Appends a new object at the end of the array as long as the array doesn't
  2705. already contain it.
  2706. If the array already contains a matching object, nothing will be done.
  2707. @param newObject the new object to add to the array
  2708. */
  2709. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  2710. {
  2711. lock.enter();
  2712. if (! contains (newObject))
  2713. add (newObject);
  2714. lock.exit();
  2715. }
  2716. /** Replaces an object in the array with a different one.
  2717. If the index is less than zero, this method does nothing.
  2718. If the index is beyond the end of the array, the new object is added to the end of the array.
  2719. Be careful not to add the same object to the array more than once,
  2720. as this will obviously cause deletion of dangling pointers.
  2721. @param indexToChange the index whose value you want to change
  2722. @param newObject the new value to set for this index.
  2723. @param deleteOldElement whether to delete the object that's being replaced with the new one
  2724. @see add, insert, remove
  2725. */
  2726. void set (const int indexToChange,
  2727. const ObjectClass* const newObject,
  2728. const bool deleteOldElement = true)
  2729. {
  2730. if (indexToChange >= 0)
  2731. {
  2732. ObjectClass* toDelete = 0;
  2733. lock.enter();
  2734. if (indexToChange < numUsed)
  2735. {
  2736. if (deleteOldElement)
  2737. toDelete = this->elements [indexToChange];
  2738. if (toDelete == newObject)
  2739. toDelete = 0;
  2740. else
  2741. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  2742. }
  2743. else
  2744. {
  2745. this->ensureAllocatedSize (numUsed + 1);
  2746. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2747. }
  2748. lock.exit();
  2749. delete toDelete;
  2750. }
  2751. }
  2752. /** Inserts a new object into the array assuming that the array is sorted.
  2753. This will use a comparator to find the position at which the new object
  2754. should go. If the array isn't sorted, the behaviour of this
  2755. method will be unpredictable.
  2756. @param comparator the comparator to use to compare the elements - see the sort method
  2757. for details about this object's structure
  2758. @param newObject the new object to insert to the array
  2759. @see add, sort, indexOfSorted
  2760. */
  2761. template <class ElementComparator>
  2762. void addSorted (ElementComparator& comparator,
  2763. ObjectClass* const newObject) throw()
  2764. {
  2765. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2766. // avoids getting warning messages about the parameter being unused
  2767. lock.enter();
  2768. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  2769. lock.exit();
  2770. }
  2771. /** Finds the index of an object in the array, assuming that the array is sorted.
  2772. This will use a comparator to do a binary-chop to find the index of the given
  2773. element, if it exists. If the array isn't sorted, the behaviour of this
  2774. method will be unpredictable.
  2775. @param comparator the comparator to use to compare the elements - see the sort()
  2776. method for details about the form this object should take
  2777. @param objectToLookFor the object to search for
  2778. @returns the index of the element, or -1 if it's not found
  2779. @see addSorted, sort
  2780. */
  2781. template <class ElementComparator>
  2782. int indexOfSorted (ElementComparator& comparator,
  2783. const ObjectClass* const objectToLookFor) const throw()
  2784. {
  2785. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2786. // avoids getting warning messages about the parameter being unused
  2787. lock.enter();
  2788. int start = 0;
  2789. int end = numUsed;
  2790. for (;;)
  2791. {
  2792. if (start >= end)
  2793. {
  2794. lock.exit();
  2795. return -1;
  2796. }
  2797. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  2798. {
  2799. lock.exit();
  2800. return start;
  2801. }
  2802. else
  2803. {
  2804. const int halfway = (start + end) >> 1;
  2805. if (halfway == start)
  2806. {
  2807. lock.exit();
  2808. return -1;
  2809. }
  2810. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  2811. start = halfway;
  2812. else
  2813. end = halfway;
  2814. }
  2815. }
  2816. }
  2817. /** Removes an object from the array.
  2818. This will remove the object at a given index (optionally also
  2819. deleting it) and move back all the subsequent objects to close the gap.
  2820. If the index passed in is out-of-range, nothing will happen.
  2821. @param indexToRemove the index of the element to remove
  2822. @param deleteObject whether to delete the object that is removed
  2823. @see removeObject, removeRange
  2824. */
  2825. void remove (const int indexToRemove,
  2826. const bool deleteObject = true)
  2827. {
  2828. lock.enter();
  2829. ObjectClass* toDelete = 0;
  2830. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2831. {
  2832. ObjectClass** const e = this->elements + indexToRemove;
  2833. if (deleteObject)
  2834. toDelete = *e;
  2835. --numUsed;
  2836. const int numToShift = numUsed - indexToRemove;
  2837. if (numToShift > 0)
  2838. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  2839. if ((numUsed << 1) < this->numAllocated)
  2840. minimiseStorageOverheads();
  2841. }
  2842. lock.exit();
  2843. delete toDelete;
  2844. }
  2845. /** Removes a specified object from the array.
  2846. If the item isn't found, no action is taken.
  2847. @param objectToRemove the object to try to remove
  2848. @param deleteObject whether to delete the object (if it's found)
  2849. @see remove, removeRange
  2850. */
  2851. void removeObject (const ObjectClass* const objectToRemove,
  2852. const bool deleteObject = true)
  2853. {
  2854. lock.enter();
  2855. ObjectClass** e = this->elements;
  2856. for (int i = numUsed; --i >= 0;)
  2857. {
  2858. if (objectToRemove == *e)
  2859. {
  2860. remove ((int) (e - this->elements), deleteObject);
  2861. break;
  2862. }
  2863. ++e;
  2864. }
  2865. lock.exit();
  2866. }
  2867. /** Removes a range of objects from the array.
  2868. This will remove a set of objects, starting from the given index,
  2869. and move any subsequent elements down to close the gap.
  2870. If the range extends beyond the bounds of the array, it will
  2871. be safely clipped to the size of the array.
  2872. @param startIndex the index of the first object to remove
  2873. @param numberToRemove how many objects should be removed
  2874. @param deleteObjects whether to delete the objects that get removed
  2875. @see remove, removeObject
  2876. */
  2877. void removeRange (int startIndex,
  2878. const int numberToRemove,
  2879. const bool deleteObjects = true)
  2880. {
  2881. lock.enter();
  2882. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  2883. startIndex = jlimit (0, numUsed, startIndex);
  2884. if (endIndex > startIndex)
  2885. {
  2886. if (deleteObjects)
  2887. {
  2888. for (int i = startIndex; i < endIndex; ++i)
  2889. {
  2890. delete this->elements [i];
  2891. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  2892. }
  2893. }
  2894. const int rangeSize = endIndex - startIndex;
  2895. ObjectClass** e = this->elements + startIndex;
  2896. int numToShift = numUsed - endIndex;
  2897. numUsed -= rangeSize;
  2898. while (--numToShift >= 0)
  2899. {
  2900. *e = e [rangeSize];
  2901. ++e;
  2902. }
  2903. if ((numUsed << 1) < this->numAllocated)
  2904. minimiseStorageOverheads();
  2905. }
  2906. lock.exit();
  2907. }
  2908. /** Removes the last n objects from the array.
  2909. @param howManyToRemove how many objects to remove from the end of the array
  2910. @param deleteObjects whether to also delete the objects that are removed
  2911. @see remove, removeObject, removeRange
  2912. */
  2913. void removeLast (int howManyToRemove = 1,
  2914. const bool deleteObjects = true)
  2915. {
  2916. lock.enter();
  2917. if (howManyToRemove >= numUsed)
  2918. {
  2919. clear (deleteObjects);
  2920. }
  2921. else
  2922. {
  2923. while (--howManyToRemove >= 0)
  2924. remove (numUsed - 1, deleteObjects);
  2925. }
  2926. lock.exit();
  2927. }
  2928. /** Swaps a pair of objects in the array.
  2929. If either of the indexes passed in is out-of-range, nothing will happen,
  2930. otherwise the two objects at these positions will be exchanged.
  2931. */
  2932. void swap (const int index1,
  2933. const int index2) throw()
  2934. {
  2935. lock.enter();
  2936. if (((unsigned int) index1) < (unsigned int) numUsed
  2937. && ((unsigned int) index2) < (unsigned int) numUsed)
  2938. {
  2939. swapVariables (this->elements [index1],
  2940. this->elements [index2]);
  2941. }
  2942. lock.exit();
  2943. }
  2944. /** Moves one of the objects to a different position.
  2945. This will move the object to a specified index, shuffling along
  2946. any intervening elements as required.
  2947. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  2948. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  2949. @param currentIndex the index of the object to be moved. If this isn't a
  2950. valid index, then nothing will be done
  2951. @param newIndex the index at which you'd like this object to end up. If this
  2952. is less than zero, it will be moved to the end of the array
  2953. */
  2954. void move (const int currentIndex,
  2955. int newIndex) throw()
  2956. {
  2957. if (currentIndex != newIndex)
  2958. {
  2959. lock.enter();
  2960. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  2961. {
  2962. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  2963. newIndex = numUsed - 1;
  2964. ObjectClass* const value = this->elements [currentIndex];
  2965. if (newIndex > currentIndex)
  2966. {
  2967. memmove (this->elements + currentIndex,
  2968. this->elements + currentIndex + 1,
  2969. (newIndex - currentIndex) * sizeof (ObjectClass*));
  2970. }
  2971. else
  2972. {
  2973. memmove (this->elements + newIndex + 1,
  2974. this->elements + newIndex,
  2975. (currentIndex - newIndex) * sizeof (ObjectClass*));
  2976. }
  2977. this->elements [newIndex] = value;
  2978. }
  2979. lock.exit();
  2980. }
  2981. }
  2982. /** This swaps the contents of this array with those of another array.
  2983. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2984. because it just swaps their internal pointers.
  2985. */
  2986. template <class OtherArrayType>
  2987. void swapWithArray (OtherArrayType& otherArray) throw()
  2988. {
  2989. lock.enter();
  2990. otherArray.lock.enter();
  2991. swapVariables <int> (this->numUsed, otherArray.numUsed);
  2992. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  2993. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  2994. otherArray.lock.exit();
  2995. lock.exit();
  2996. }
  2997. /** Reduces the amount of storage being used by the array.
  2998. Arrays typically allocate slightly more storage than they need, and after
  2999. removing elements, they may have quite a lot of unused space allocated.
  3000. This method will reduce the amount of allocated storage to a minimum.
  3001. */
  3002. void minimiseStorageOverheads() throw()
  3003. {
  3004. lock.enter();
  3005. if (numUsed == 0)
  3006. {
  3007. this->setAllocatedSize (0);
  3008. }
  3009. else
  3010. {
  3011. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3012. if (newAllocation < this->numAllocated)
  3013. this->setAllocatedSize (newAllocation);
  3014. }
  3015. lock.exit();
  3016. }
  3017. /** Increases the array's internal storage to hold a minimum number of elements.
  3018. Calling this before adding a large known number of elements means that
  3019. the array won't have to keep dynamically resizing itself as the elements
  3020. are added, and it'll therefore be more efficient.
  3021. */
  3022. void ensureStorageAllocated (const int minNumElements) throw()
  3023. {
  3024. this->ensureAllocatedSize (minNumElements);
  3025. }
  3026. /** Sorts the elements in the array.
  3027. This will use a comparator object to sort the elements into order. The object
  3028. passed must have a method of the form:
  3029. @code
  3030. int compareElements (ElementType first, ElementType second);
  3031. @endcode
  3032. ..and this method must return:
  3033. - a value of < 0 if the first comes before the second
  3034. - a value of 0 if the two objects are equivalent
  3035. - a value of > 0 if the second comes before the first
  3036. To improve performance, the compareElements() method can be declared as static or const.
  3037. @param comparator the comparator to use for comparing elements.
  3038. @param retainOrderOfEquivalentItems if this is true, then items
  3039. which the comparator says are equivalent will be
  3040. kept in the order in which they currently appear
  3041. in the array. This is slower to perform, but may
  3042. be important in some cases. If it's false, a faster
  3043. algorithm is used, but equivalent elements may be
  3044. rearranged.
  3045. @see sortArray, indexOfSorted
  3046. */
  3047. template <class ElementComparator>
  3048. void sort (ElementComparator& comparator,
  3049. const bool retainOrderOfEquivalentItems = false) const throw()
  3050. {
  3051. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3052. // avoids getting warning messages about the parameter being unused
  3053. lock.enter();
  3054. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3055. lock.exit();
  3056. }
  3057. /** Locks the array's CriticalSection.
  3058. Of course if the type of section used is a DummyCriticalSection, this won't
  3059. have any effect.
  3060. @see unlockArray
  3061. */
  3062. void lockArray() const throw()
  3063. {
  3064. lock.enter();
  3065. }
  3066. /** Unlocks the array's CriticalSection.
  3067. Of course if the type of section used is a DummyCriticalSection, this won't
  3068. have any effect.
  3069. @see lockArray
  3070. */
  3071. void unlockArray() const throw()
  3072. {
  3073. lock.exit();
  3074. }
  3075. juce_UseDebuggingNewOperator
  3076. private:
  3077. int numUsed;
  3078. TypeOfCriticalSectionToUse lock;
  3079. // disallow copy constructor and assignment
  3080. OwnedArray (const OwnedArray&);
  3081. const OwnedArray& operator= (const OwnedArray&);
  3082. };
  3083. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3084. /********* End of inlined file: juce_OwnedArray.h *********/
  3085. /********* Start of inlined file: juce_Time.h *********/
  3086. #ifndef __JUCE_TIME_JUCEHEADER__
  3087. #define __JUCE_TIME_JUCEHEADER__
  3088. /********* Start of inlined file: juce_RelativeTime.h *********/
  3089. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3090. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3091. /** A relative measure of time.
  3092. The time is stored as a number of seconds, at double-precision floating
  3093. point accuracy, and may be positive or negative.
  3094. If you need an absolute time, (i.e. a date + time), see the Time class.
  3095. */
  3096. class JUCE_API RelativeTime
  3097. {
  3098. public:
  3099. /** Creates a RelativeTime.
  3100. @param seconds the number of seconds, which may be +ve or -ve.
  3101. @see milliseconds, minutes, hours, days, weeks
  3102. */
  3103. explicit RelativeTime (const double seconds = 0.0) throw();
  3104. /** Copies another relative time. */
  3105. RelativeTime (const RelativeTime& other) throw();
  3106. /** Copies another relative time. */
  3107. const RelativeTime& operator= (const RelativeTime& other) throw();
  3108. /** Destructor. */
  3109. ~RelativeTime() throw();
  3110. /** Creates a new RelativeTime object representing a number of milliseconds.
  3111. @see minutes, hours, days, weeks
  3112. */
  3113. static const RelativeTime milliseconds (const int milliseconds) throw();
  3114. /** Creates a new RelativeTime object representing a number of milliseconds.
  3115. @see minutes, hours, days, weeks
  3116. */
  3117. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3118. /** Creates a new RelativeTime object representing a number of minutes.
  3119. @see milliseconds, hours, days, weeks
  3120. */
  3121. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3122. /** Creates a new RelativeTime object representing a number of hours.
  3123. @see milliseconds, minutes, days, weeks
  3124. */
  3125. static const RelativeTime hours (const double numberOfHours) throw();
  3126. /** Creates a new RelativeTime object representing a number of days.
  3127. @see milliseconds, minutes, hours, weeks
  3128. */
  3129. static const RelativeTime days (const double numberOfDays) throw();
  3130. /** Creates a new RelativeTime object representing a number of weeks.
  3131. @see milliseconds, minutes, hours, days
  3132. */
  3133. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3134. /** Returns the number of milliseconds this time represents.
  3135. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3136. */
  3137. int64 inMilliseconds() const throw();
  3138. /** Returns the number of seconds this time represents.
  3139. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3140. */
  3141. double inSeconds() const throw() { return seconds; }
  3142. /** Returns the number of minutes this time represents.
  3143. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3144. */
  3145. double inMinutes() const throw();
  3146. /** Returns the number of hours this time represents.
  3147. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3148. */
  3149. double inHours() const throw();
  3150. /** Returns the number of days this time represents.
  3151. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3152. */
  3153. double inDays() const throw();
  3154. /** Returns the number of weeks this time represents.
  3155. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3156. */
  3157. double inWeeks() const throw();
  3158. /** Returns a readable textual description of the time.
  3159. The exact format of the string returned will depend on
  3160. the magnitude of the time - e.g.
  3161. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3162. so that only the two most significant units are printed.
  3163. The returnValueForZeroTime value is the result that is returned if the
  3164. length is zero. Depending on your application you might want to use this
  3165. to return something more relevant like "empty" or "0 secs", etc.
  3166. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3167. */
  3168. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  3169. /** Compares two RelativeTimes. */
  3170. bool operator== (const RelativeTime& other) const throw();
  3171. /** Compares two RelativeTimes. */
  3172. bool operator!= (const RelativeTime& other) const throw();
  3173. /** Compares two RelativeTimes. */
  3174. bool operator> (const RelativeTime& other) const throw();
  3175. /** Compares two RelativeTimes. */
  3176. bool operator< (const RelativeTime& other) const throw();
  3177. /** Compares two RelativeTimes. */
  3178. bool operator>= (const RelativeTime& other) const throw();
  3179. /** Compares two RelativeTimes. */
  3180. bool operator<= (const RelativeTime& other) const throw();
  3181. /** Adds another RelativeTime to this one and returns the result. */
  3182. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3183. /** Subtracts another RelativeTime from this one and returns the result. */
  3184. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3185. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3186. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3187. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3188. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3189. /** Adds another RelativeTime to this one. */
  3190. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3191. /** Subtracts another RelativeTime from this one. */
  3192. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3193. /** Adds a number of seconds to this time. */
  3194. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3195. /** Subtracts a number of seconds from this time. */
  3196. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3197. juce_UseDebuggingNewOperator
  3198. private:
  3199. double seconds;
  3200. };
  3201. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3202. /********* End of inlined file: juce_RelativeTime.h *********/
  3203. /**
  3204. Holds an absolute date and time.
  3205. Internally, the time is stored at millisecond precision.
  3206. @see RelativeTime
  3207. */
  3208. class JUCE_API Time
  3209. {
  3210. public:
  3211. /** Creates a Time object.
  3212. This default constructor creates a time of 1st January 1970, (which is
  3213. represented internally as 0ms).
  3214. To create a time object representing the current time, use getCurrentTime().
  3215. @see getCurrentTime
  3216. */
  3217. Time() throw();
  3218. /** Creates a copy of another Time object. */
  3219. Time (const Time& other) throw();
  3220. /** Creates a time based on a number of milliseconds.
  3221. The internal millisecond count is set to 0 (1st January 1970). To create a
  3222. time object set to the current time, use getCurrentTime().
  3223. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3224. 'epoch' (midnight Jan 1st 1970).
  3225. @see getCurrentTime, currentTimeMillis
  3226. */
  3227. Time (const int64 millisecondsSinceEpoch) throw();
  3228. /** Creates a time from a set of date components.
  3229. The timezone is assumed to be whatever the system is using as its locale.
  3230. @param year the year, in 4-digit format, e.g. 2004
  3231. @param month the month, in the range 0 to 11
  3232. @param day the day of the month, in the range 1 to 31
  3233. @param hours hours in 24-hour clock format, 0 to 23
  3234. @param minutes minutes 0 to 59
  3235. @param seconds seconds 0 to 59
  3236. @param milliseconds milliseconds 0 to 999
  3237. @param useLocalTime if true, encode using the current machine's local time; if
  3238. false, it will always work in GMT.
  3239. */
  3240. Time (const int year,
  3241. const int month,
  3242. const int day,
  3243. const int hours,
  3244. const int minutes,
  3245. const int seconds = 0,
  3246. const int milliseconds = 0,
  3247. const bool useLocalTime = true) throw();
  3248. /** Destructor. */
  3249. ~Time() throw();
  3250. /** Copies this time from another one. */
  3251. const Time& operator= (const Time& other) throw();
  3252. /** Returns a Time object that is set to the current system time.
  3253. @see currentTimeMillis
  3254. */
  3255. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3256. /** Returns the time as a number of milliseconds.
  3257. @returns the number of milliseconds this Time object represents, since
  3258. midnight jan 1st 1970.
  3259. @see getMilliseconds
  3260. */
  3261. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3262. /** Returns the year.
  3263. A 4-digit format is used, e.g. 2004.
  3264. */
  3265. int getYear() const throw();
  3266. /** Returns the number of the month.
  3267. The value returned is in the range 0 to 11.
  3268. @see getMonthName
  3269. */
  3270. int getMonth() const throw();
  3271. /** Returns the name of the month.
  3272. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3273. it'll return the long form, e.g. "January"
  3274. @see getMonth
  3275. */
  3276. const String getMonthName (const bool threeLetterVersion) const throw();
  3277. /** Returns the day of the month.
  3278. The value returned is in the range 1 to 31.
  3279. */
  3280. int getDayOfMonth() const throw();
  3281. /** Returns the number of the day of the week.
  3282. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3283. */
  3284. int getDayOfWeek() const throw();
  3285. /** Returns the name of the weekday.
  3286. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3287. false, it'll return the full version, e.g. "Tuesday".
  3288. */
  3289. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3290. /** Returns the number of hours since midnight.
  3291. This is in 24-hour clock format, in the range 0 to 23.
  3292. @see getHoursInAmPmFormat, isAfternoon
  3293. */
  3294. int getHours() const throw();
  3295. /** Returns true if the time is in the afternoon.
  3296. So it returns true for "PM", false for "AM".
  3297. @see getHoursInAmPmFormat, getHours
  3298. */
  3299. bool isAfternoon() const throw();
  3300. /** Returns the hours in 12-hour clock format.
  3301. This will return a value 1 to 12 - use isAfternoon() to find out
  3302. whether this is in the afternoon or morning.
  3303. @see getHours, isAfternoon
  3304. */
  3305. int getHoursInAmPmFormat() const throw();
  3306. /** Returns the number of minutes, 0 to 59. */
  3307. int getMinutes() const throw();
  3308. /** Returns the number of seconds, 0 to 59. */
  3309. int getSeconds() const throw();
  3310. /** Returns the number of milliseconds, 0 to 999.
  3311. Unlike toMilliseconds(), this just returns the position within the
  3312. current second rather than the total number since the epoch.
  3313. @see toMilliseconds
  3314. */
  3315. int getMilliseconds() const throw();
  3316. /** Returns true if the local timezone uses a daylight saving correction. */
  3317. bool isDaylightSavingTime() const throw();
  3318. /** Returns a 3-character string to indicate the local timezone. */
  3319. const String getTimeZone() const throw();
  3320. /** Quick way of getting a string version of a date and time.
  3321. For a more powerful way of formatting the date and time, see the formatted() method.
  3322. @param includeDate whether to include the date in the string
  3323. @param includeTime whether to include the time in the string
  3324. @param includeSeconds if the time is being included, this provides an option not to include
  3325. the seconds in it
  3326. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3327. hour notation.
  3328. @see formatted
  3329. */
  3330. const String toString (const bool includeDate,
  3331. const bool includeTime,
  3332. const bool includeSeconds = true,
  3333. const bool use24HourClock = false) const throw();
  3334. /** Converts this date/time to a string with a user-defined format.
  3335. This uses the C strftime() function to format this time as a string. To save you
  3336. looking it up, these are the escape codes that strftime uses (other codes might
  3337. work on some platforms and not others, but these are the common ones):
  3338. %a is replaced by the locale's abbreviated weekday name.
  3339. %A is replaced by the locale's full weekday name.
  3340. %b is replaced by the locale's abbreviated month name.
  3341. %B is replaced by the locale's full month name.
  3342. %c is replaced by the locale's appropriate date and time representation.
  3343. %d is replaced by the day of the month as a decimal number [01,31].
  3344. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3345. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3346. %j is replaced by the day of the year as a decimal number [001,366].
  3347. %m is replaced by the month as a decimal number [01,12].
  3348. %M is replaced by the minute as a decimal number [00,59].
  3349. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3350. %S is replaced by the second as a decimal number [00,61].
  3351. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3352. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3353. %W is replaced by the week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
  3354. %x is replaced by the locale's appropriate date representation.
  3355. %X is replaced by the locale's appropriate time representation.
  3356. %y is replaced by the year without century as a decimal number [00,99].
  3357. %Y is replaced by the year with century as a decimal number.
  3358. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3359. %% is replaced by %.
  3360. @see toString
  3361. */
  3362. const String formatted (const tchar* const format) const throw();
  3363. /** Adds a RelativeTime to this time and returns the result. */
  3364. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3365. /** Subtracts a RelativeTime from this time and returns the result. */
  3366. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3367. /** Returns the relative time difference between this time and another one. */
  3368. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  3369. /** Compares two Time objects. */
  3370. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  3371. /** Compares two Time objects. */
  3372. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  3373. /** Compares two Time objects. */
  3374. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  3375. /** Compares two Time objects. */
  3376. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3377. /** Compares two Time objects. */
  3378. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3379. /** Compares two Time objects. */
  3380. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3381. /** Tries to set the computer's clock.
  3382. @returns true if this succeeds, although depending on the system, the
  3383. application might not have sufficient privileges to do this.
  3384. */
  3385. bool setSystemTimeToThisTime() const throw();
  3386. /** Returns the name of a day of the week.
  3387. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3388. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3389. false, it'll return the full version, e.g. "Tuesday".
  3390. */
  3391. static const String getWeekdayName (int dayNumber,
  3392. const bool threeLetterVersion) throw();
  3393. /** Returns the name of one of the months.
  3394. @param monthNumber the month, 0 to 11
  3395. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3396. it'll return the long form, e.g. "January"
  3397. */
  3398. static const String getMonthName (int monthNumber,
  3399. const bool threeLetterVersion) throw();
  3400. // Static methods for getting system timers directly..
  3401. /** Returns the current system time.
  3402. Returns the number of milliseconds since midnight jan 1st 1970.
  3403. Should be accurate to within a few millisecs, depending on platform,
  3404. hardware, etc.
  3405. */
  3406. static int64 currentTimeMillis() throw();
  3407. /** Returns the number of millisecs since system startup.
  3408. Should be accurate to within a few millisecs, depending on platform,
  3409. hardware, etc.
  3410. @see getApproximateMillisecondCounter
  3411. */
  3412. static uint32 getMillisecondCounter() throw();
  3413. /** Returns the number of millisecs since system startup.
  3414. Same as getMillisecondCounter(), but returns a more accurate value, using
  3415. the high-res timer.
  3416. @see getMillisecondCounter
  3417. */
  3418. static double getMillisecondCounterHiRes() throw();
  3419. /** Waits until the getMillisecondCounter() reaches a given value.
  3420. This will make the thread sleep as efficiently as it can while it's waiting.
  3421. */
  3422. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3423. /** Less-accurate but faster version of getMillisecondCounter().
  3424. This will return the last value that getMillisecondCounter() returned, so doesn't
  3425. need to make a system call, but is less accurate - it shouldn't be more than
  3426. 100ms away from the correct time, though, so is still accurate enough for a
  3427. lot of purposes.
  3428. @see getMillisecondCounter
  3429. */
  3430. static uint32 getApproximateMillisecondCounter() throw();
  3431. // High-resolution timers..
  3432. /** Returns the current high-resolution counter's tick-count.
  3433. This is a similar idea to getMillisecondCounter(), but with a higher
  3434. resolution.
  3435. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3436. secondsToHighResolutionTicks
  3437. */
  3438. static int64 getHighResolutionTicks() throw();
  3439. /** Returns the resolution of the high-resolution counter in ticks per second.
  3440. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3441. secondsToHighResolutionTicks
  3442. */
  3443. static int64 getHighResolutionTicksPerSecond() throw();
  3444. /** Converts a number of high-resolution ticks into seconds.
  3445. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3446. secondsToHighResolutionTicks
  3447. */
  3448. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3449. /** Converts a number seconds into high-resolution ticks.
  3450. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3451. highResolutionTicksToSeconds
  3452. */
  3453. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3454. private:
  3455. int64 millisSinceEpoch;
  3456. };
  3457. #endif // __JUCE_TIME_JUCEHEADER__
  3458. /********* End of inlined file: juce_Time.h *********/
  3459. /********* Start of inlined file: juce_StringArray.h *********/
  3460. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3461. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3462. /********* Start of inlined file: juce_VoidArray.h *********/
  3463. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3464. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3465. /********* Start of inlined file: juce_Array.h *********/
  3466. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3467. #define __JUCE_ARRAY_JUCEHEADER__
  3468. /**
  3469. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3470. Examples of arrays are: Array<int> or Array<MyClass*>
  3471. Note that when holding pointers to objects, the array doesn't take any ownership
  3472. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3473. If you're using a class or struct as the element type, it must be
  3474. capable of being copied or moved with a straightforward memcpy, rather than
  3475. needing construction and destruction code.
  3476. For holding lists of strings, use the specialised class StringArray.
  3477. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3478. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3479. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3480. */
  3481. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3482. class Array : private ArrayAllocationBase <ElementType>
  3483. {
  3484. public:
  3485. /** Creates an empty array.
  3486. @param granularity this is the size of increment by which the internal storage
  3487. used by the array will grow. Only change it from the default if you know the
  3488. array is going to be very big and needs to be able to grow efficiently.
  3489. @see ArrayAllocationBase
  3490. */
  3491. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3492. : ArrayAllocationBase <ElementType> (granularity),
  3493. numUsed (0)
  3494. {
  3495. }
  3496. /** Creates a copy of another array.
  3497. @param other the array to copy
  3498. */
  3499. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3500. : ArrayAllocationBase <ElementType> (other.granularity)
  3501. {
  3502. other.lockArray();
  3503. numUsed = other.numUsed;
  3504. this->setAllocatedSize (other.numUsed);
  3505. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  3506. other.unlockArray();
  3507. }
  3508. /** Initalises from a null-terminated C array of values.
  3509. @param values the array to copy from
  3510. */
  3511. Array (const ElementType* values) throw()
  3512. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3513. numUsed (0)
  3514. {
  3515. while (*values != 0)
  3516. add (*values++);
  3517. }
  3518. /** Initalises from a C array of values.
  3519. @param values the array to copy from
  3520. @param numValues the number of values in the array
  3521. */
  3522. Array (const ElementType* values, int numValues) throw()
  3523. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3524. numUsed (numValues)
  3525. {
  3526. this->setAllocatedSize (numValues);
  3527. memcpy (this->elements, values, numValues * sizeof (ElementType));
  3528. }
  3529. /** Destructor. */
  3530. ~Array() throw()
  3531. {
  3532. }
  3533. /** Copies another array.
  3534. @param other the array to copy
  3535. */
  3536. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3537. {
  3538. if (this != &other)
  3539. {
  3540. other.lockArray();
  3541. lock.enter();
  3542. this->granularity = other.granularity;
  3543. this->ensureAllocatedSize (other.size());
  3544. numUsed = other.numUsed;
  3545. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  3546. minimiseStorageOverheads();
  3547. lock.exit();
  3548. other.unlockArray();
  3549. }
  3550. return *this;
  3551. }
  3552. /** Compares this array to another one.
  3553. Two arrays are considered equal if they both contain the same set of
  3554. elements, in the same order.
  3555. @param other the other array to compare with
  3556. */
  3557. template <class OtherArrayType>
  3558. bool operator== (const OtherArrayType& other) const throw()
  3559. {
  3560. lock.enter();
  3561. if (this->numUsed != other.numUsed)
  3562. {
  3563. lock.exit();
  3564. return false;
  3565. }
  3566. for (int i = numUsed; --i >= 0;)
  3567. {
  3568. if (this->elements [i] != other.elements [i])
  3569. {
  3570. lock.exit();
  3571. return false;
  3572. }
  3573. }
  3574. lock.exit();
  3575. return true;
  3576. }
  3577. /** Compares this array to another one.
  3578. Two arrays are considered equal if they both contain the same set of
  3579. elements, in the same order.
  3580. @param other the other array to compare with
  3581. */
  3582. template <class OtherArrayType>
  3583. bool operator!= (const OtherArrayType& other) const throw()
  3584. {
  3585. return ! operator== (other);
  3586. }
  3587. /** Removes all elements from the array.
  3588. This will remove all the elements, and free any storage that the array is
  3589. using. To clear the array without freeing the storage, use the clearQuick()
  3590. method instead.
  3591. @see clearQuick
  3592. */
  3593. void clear() throw()
  3594. {
  3595. lock.enter();
  3596. this->setAllocatedSize (0);
  3597. numUsed = 0;
  3598. lock.exit();
  3599. }
  3600. /** Removes all elements from the array without freeing the array's allocated storage.
  3601. @see clear
  3602. */
  3603. void clearQuick() throw()
  3604. {
  3605. lock.enter();
  3606. numUsed = 0;
  3607. lock.exit();
  3608. }
  3609. /** Returns the current number of elements in the array.
  3610. */
  3611. inline int size() const throw()
  3612. {
  3613. return numUsed;
  3614. }
  3615. /** Returns one of the elements in the array.
  3616. If the index passed in is beyond the range of valid elements, this
  3617. will return zero.
  3618. If you're certain that the index will always be a valid element, you
  3619. can call getUnchecked() instead, which is faster.
  3620. @param index the index of the element being requested (0 is the first element in the array)
  3621. @see getUnchecked, getFirst, getLast
  3622. */
  3623. inline ElementType operator[] (const int index) const throw()
  3624. {
  3625. lock.enter();
  3626. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  3627. ? this->elements [index]
  3628. : ElementType();
  3629. lock.exit();
  3630. return result;
  3631. }
  3632. /** Returns one of the elements in the array, without checking the index passed in.
  3633. Unlike the operator[] method, this will try to return an element without
  3634. checking that the index is within the bounds of the array, so should only
  3635. be used when you're confident that it will always be a valid index.
  3636. @param index the index of the element being requested (0 is the first element in the array)
  3637. @see operator[], getFirst, getLast
  3638. */
  3639. inline ElementType getUnchecked (const int index) const throw()
  3640. {
  3641. lock.enter();
  3642. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3643. const ElementType result = this->elements [index];
  3644. lock.exit();
  3645. return result;
  3646. }
  3647. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3648. This is like getUnchecked, but returns a direct reference to the element, so that
  3649. you can alter it directly. Obviously this can be dangerous, so only use it when
  3650. absolutely necessary.
  3651. @param index the index of the element being requested (0 is the first element in the array)
  3652. @see operator[], getFirst, getLast
  3653. */
  3654. inline ElementType& getReference (const int index) const throw()
  3655. {
  3656. lock.enter();
  3657. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3658. ElementType& result = this->elements [index];
  3659. lock.exit();
  3660. return result;
  3661. }
  3662. /** Returns the first element in the array, or 0 if the array is empty.
  3663. @see operator[], getUnchecked, getLast
  3664. */
  3665. inline ElementType getFirst() const throw()
  3666. {
  3667. lock.enter();
  3668. const ElementType result = (numUsed > 0) ? this->elements [0]
  3669. : ElementType();
  3670. lock.exit();
  3671. return result;
  3672. }
  3673. /** Returns the last element in the array, or 0 if the array is empty.
  3674. @see operator[], getUnchecked, getFirst
  3675. */
  3676. inline ElementType getLast() const throw()
  3677. {
  3678. lock.enter();
  3679. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  3680. : ElementType();
  3681. lock.exit();
  3682. return result;
  3683. }
  3684. /** Finds the index of the first element which matches the value passed in.
  3685. This will search the array for the given object, and return the index
  3686. of its first occurrence. If the object isn't found, the method will return -1.
  3687. @param elementToLookFor the value or object to look for
  3688. @returns the index of the object, or -1 if it's not found
  3689. */
  3690. int indexOf (const ElementType elementToLookFor) const throw()
  3691. {
  3692. int result = -1;
  3693. lock.enter();
  3694. const ElementType* e = this->elements;
  3695. for (int i = numUsed; --i >= 0;)
  3696. {
  3697. if (elementToLookFor == *e)
  3698. {
  3699. result = (int) (e - this->elements);
  3700. break;
  3701. }
  3702. ++e;
  3703. }
  3704. lock.exit();
  3705. return result;
  3706. }
  3707. /** Returns true if the array contains at least one occurrence of an object.
  3708. @param elementToLookFor the value or object to look for
  3709. @returns true if the item is found
  3710. */
  3711. bool contains (const ElementType elementToLookFor) const throw()
  3712. {
  3713. lock.enter();
  3714. const ElementType* e = this->elements;
  3715. int num = numUsed;
  3716. while (num >= 4)
  3717. {
  3718. if (*e == elementToLookFor
  3719. || *++e == elementToLookFor
  3720. || *++e == elementToLookFor
  3721. || *++e == elementToLookFor)
  3722. {
  3723. lock.exit();
  3724. return true;
  3725. }
  3726. num -= 4;
  3727. ++e;
  3728. }
  3729. while (num > 0)
  3730. {
  3731. if (elementToLookFor == *e)
  3732. {
  3733. lock.exit();
  3734. return true;
  3735. }
  3736. --num;
  3737. ++e;
  3738. }
  3739. lock.exit();
  3740. return false;
  3741. }
  3742. /** Appends a new element at the end of the array.
  3743. @param newElement the new object to add to the array
  3744. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  3745. */
  3746. void add (const ElementType newElement) throw()
  3747. {
  3748. lock.enter();
  3749. this->ensureAllocatedSize (numUsed + 1);
  3750. this->elements [numUsed++] = newElement;
  3751. lock.exit();
  3752. }
  3753. /** Inserts a new element into the array at a given position.
  3754. If the index is less than 0 or greater than the size of the array, the
  3755. element will be added to the end of the array.
  3756. Otherwise, it will be inserted into the array, moving all the later elements
  3757. along to make room.
  3758. @param indexToInsertAt the index at which the new element should be
  3759. inserted (pass in -1 to add it to the end)
  3760. @param newElement the new object to add to the array
  3761. @see add, addSorted, set
  3762. */
  3763. void insert (int indexToInsertAt, const ElementType newElement) throw()
  3764. {
  3765. lock.enter();
  3766. this->ensureAllocatedSize (numUsed + 1);
  3767. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3768. {
  3769. ElementType* const insertPos = this->elements + indexToInsertAt;
  3770. const int numberToMove = numUsed - indexToInsertAt;
  3771. if (numberToMove > 0)
  3772. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3773. *insertPos = newElement;
  3774. ++numUsed;
  3775. }
  3776. else
  3777. {
  3778. this->elements [numUsed++] = newElement;
  3779. }
  3780. lock.exit();
  3781. }
  3782. /** Inserts multiple copies of an element into the array at a given position.
  3783. If the index is less than 0 or greater than the size of the array, the
  3784. element will be added to the end of the array.
  3785. Otherwise, it will be inserted into the array, moving all the later elements
  3786. along to make room.
  3787. @param indexToInsertAt the index at which the new element should be inserted
  3788. @param newElement the new object to add to the array
  3789. @param numberOfTimesToInsertIt how many copies of the value to insert
  3790. @see insert, add, addSorted, set
  3791. */
  3792. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  3793. int numberOfTimesToInsertIt) throw()
  3794. {
  3795. if (numberOfTimesToInsertIt > 0)
  3796. {
  3797. lock.enter();
  3798. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3799. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3800. {
  3801. ElementType* insertPos = this->elements + indexToInsertAt;
  3802. const int numberToMove = numUsed - indexToInsertAt;
  3803. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3804. numUsed += numberOfTimesToInsertIt;
  3805. while (--numberOfTimesToInsertIt >= 0)
  3806. *insertPos++ = newElement;
  3807. }
  3808. else
  3809. {
  3810. while (--numberOfTimesToInsertIt >= 0)
  3811. this->elements [numUsed++] = newElement;
  3812. }
  3813. lock.exit();
  3814. }
  3815. }
  3816. /** Inserts an array of values into this array at a given position.
  3817. If the index is less than 0 or greater than the size of the array, the
  3818. new elements will be added to the end of the array.
  3819. Otherwise, they will be inserted into the array, moving all the later elements
  3820. along to make room.
  3821. @param indexToInsertAt the index at which the first new element should be inserted
  3822. @param newElements the new values to add to the array
  3823. @param numberOfElements how many items are in the array
  3824. @see insert, add, addSorted, set
  3825. */
  3826. void insertArray (int indexToInsertAt,
  3827. const ElementType* newElements,
  3828. int numberOfElements) throw()
  3829. {
  3830. if (numberOfElements > 0)
  3831. {
  3832. lock.enter();
  3833. this->ensureAllocatedSize (numUsed + numberOfElements);
  3834. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3835. {
  3836. ElementType* insertPos = this->elements + indexToInsertAt;
  3837. const int numberToMove = numUsed - indexToInsertAt;
  3838. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3839. numUsed += numberOfElements;
  3840. while (--numberOfElements >= 0)
  3841. *insertPos++ = *newElements++;
  3842. }
  3843. else
  3844. {
  3845. while (--numberOfElements >= 0)
  3846. this->elements [numUsed++] = *newElements++;
  3847. }
  3848. lock.exit();
  3849. }
  3850. }
  3851. /** Appends a new element at the end of the array as long as the array doesn't
  3852. already contain it.
  3853. If the array already contains an element that matches the one passed in, nothing
  3854. will be done.
  3855. @param newElement the new object to add to the array
  3856. */
  3857. void addIfNotAlreadyThere (const ElementType newElement) throw()
  3858. {
  3859. lock.enter();
  3860. if (! contains (newElement))
  3861. add (newElement);
  3862. lock.exit();
  3863. }
  3864. /** Replaces an element with a new value.
  3865. If the index is less than zero, this method does nothing.
  3866. If the index is beyond the end of the array, the item is added to the end of the array.
  3867. @param indexToChange the index whose value you want to change
  3868. @param newValue the new value to set for this index.
  3869. @see add, insert
  3870. */
  3871. void set (const int indexToChange,
  3872. const ElementType newValue) throw()
  3873. {
  3874. jassert (indexToChange >= 0);
  3875. if (indexToChange >= 0)
  3876. {
  3877. lock.enter();
  3878. if (indexToChange < numUsed)
  3879. {
  3880. this->elements [indexToChange] = newValue;
  3881. }
  3882. else
  3883. {
  3884. this->ensureAllocatedSize (numUsed + 1);
  3885. this->elements [numUsed++] = newValue;
  3886. }
  3887. lock.exit();
  3888. }
  3889. }
  3890. /** Replaces an element with a new value without doing any bounds-checking.
  3891. This just sets a value directly in the array's internal storage, so you'd
  3892. better make sure it's in range!
  3893. @param indexToChange the index whose value you want to change
  3894. @param newValue the new value to set for this index.
  3895. @see set, getUnchecked
  3896. */
  3897. void setUnchecked (const int indexToChange,
  3898. const ElementType newValue) throw()
  3899. {
  3900. lock.enter();
  3901. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3902. this->elements [indexToChange] = newValue;
  3903. lock.exit();
  3904. }
  3905. /** Adds elements from an array to the end of this array.
  3906. @param elementsToAdd the array of elements to add
  3907. @param numElementsToAdd how many elements are in this other array
  3908. @see add
  3909. */
  3910. void addArray (const ElementType* elementsToAdd,
  3911. int numElementsToAdd) throw()
  3912. {
  3913. lock.enter();
  3914. if (numElementsToAdd > 0)
  3915. {
  3916. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  3917. while (--numElementsToAdd >= 0)
  3918. this->elements [numUsed++] = *elementsToAdd++;
  3919. }
  3920. lock.exit();
  3921. }
  3922. /** This swaps the contents of this array with those of another array.
  3923. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3924. because it just swaps their internal pointers.
  3925. */
  3926. template <class OtherArrayType>
  3927. void swapWithArray (OtherArrayType& otherArray) throw()
  3928. {
  3929. lock.enter();
  3930. otherArray.lock.enter();
  3931. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3932. swapVariables <ElementType*> (this->elements, otherArray.elements);
  3933. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3934. otherArray.lock.exit();
  3935. lock.exit();
  3936. }
  3937. /** Adds elements from another array to the end of this array.
  3938. @param arrayToAddFrom the array from which to copy the elements
  3939. @param startIndex the first element of the other array to start copying from
  3940. @param numElementsToAdd how many elements to add from the other array. If this
  3941. value is negative or greater than the number of available elements,
  3942. all available elements will be copied.
  3943. @see add
  3944. */
  3945. template <class OtherArrayType>
  3946. void addArray (const OtherArrayType& arrayToAddFrom,
  3947. int startIndex = 0,
  3948. int numElementsToAdd = -1) throw()
  3949. {
  3950. arrayToAddFrom.lockArray();
  3951. lock.enter();
  3952. jassert (this != &arrayToAddFrom);
  3953. if (startIndex < 0)
  3954. {
  3955. jassertfalse
  3956. startIndex = 0;
  3957. }
  3958. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3959. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3960. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  3961. lock.exit();
  3962. arrayToAddFrom.unlockArray();
  3963. }
  3964. /** Inserts a new element into the array, assuming that the array is sorted.
  3965. This will use a comparator to find the position at which the new element
  3966. should go. If the array isn't sorted, the behaviour of this
  3967. method will be unpredictable.
  3968. @param comparator the comparator to use to compare the elements - see the sort()
  3969. method for details about the form this object should take
  3970. @param newElement the new element to insert to the array
  3971. @see add, sort
  3972. */
  3973. template <class ElementComparator>
  3974. void addSorted (ElementComparator& comparator,
  3975. const ElementType newElement) throw()
  3976. {
  3977. lock.enter();
  3978. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  3979. lock.exit();
  3980. }
  3981. /** Finds the index of an element in the array, assuming that the array is sorted.
  3982. This will use a comparator to do a binary-chop to find the index of the given
  3983. element, if it exists. If the array isn't sorted, the behaviour of this
  3984. method will be unpredictable.
  3985. @param comparator the comparator to use to compare the elements - see the sort()
  3986. method for details about the form this object should take
  3987. @param elementToLookFor the element to search for
  3988. @returns the index of the element, or -1 if it's not found
  3989. @see addSorted, sort
  3990. */
  3991. template <class ElementComparator>
  3992. int indexOfSorted (ElementComparator& comparator,
  3993. const ElementType elementToLookFor) const throw()
  3994. {
  3995. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3996. // avoids getting warning messages about the parameter being unused
  3997. lock.enter();
  3998. int start = 0;
  3999. int end = numUsed;
  4000. for (;;)
  4001. {
  4002. if (start >= end)
  4003. {
  4004. lock.exit();
  4005. return -1;
  4006. }
  4007. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  4008. {
  4009. lock.exit();
  4010. return start;
  4011. }
  4012. else
  4013. {
  4014. const int halfway = (start + end) >> 1;
  4015. if (halfway == start)
  4016. {
  4017. lock.exit();
  4018. return -1;
  4019. }
  4020. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  4021. start = halfway;
  4022. else
  4023. end = halfway;
  4024. }
  4025. }
  4026. }
  4027. /** Removes an element from the array.
  4028. This will remove the element at a given index, and move back
  4029. all the subsequent elements to close the gap.
  4030. If the index passed in is out-of-range, nothing will happen.
  4031. @param indexToRemove the index of the element to remove
  4032. @returns the element that has been removed
  4033. @see removeValue, removeRange
  4034. */
  4035. ElementType remove (const int indexToRemove) throw()
  4036. {
  4037. lock.enter();
  4038. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4039. {
  4040. --numUsed;
  4041. ElementType* const e = this->elements + indexToRemove;
  4042. ElementType const removed = *e;
  4043. const int numberToShift = numUsed - indexToRemove;
  4044. if (numberToShift > 0)
  4045. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4046. if ((numUsed << 1) < this->numAllocated)
  4047. minimiseStorageOverheads();
  4048. lock.exit();
  4049. return removed;
  4050. }
  4051. else
  4052. {
  4053. lock.exit();
  4054. return ElementType();
  4055. }
  4056. }
  4057. /** Removes an item from the array.
  4058. This will remove the first occurrence of the given element from the array.
  4059. If the item isn't found, no action is taken.
  4060. @param valueToRemove the object to try to remove
  4061. @see remove, removeRange
  4062. */
  4063. void removeValue (const ElementType valueToRemove) throw()
  4064. {
  4065. lock.enter();
  4066. ElementType* e = this->elements;
  4067. for (int i = numUsed; --i >= 0;)
  4068. {
  4069. if (valueToRemove == *e)
  4070. {
  4071. remove ((int) (e - this->elements));
  4072. break;
  4073. }
  4074. ++e;
  4075. }
  4076. lock.exit();
  4077. }
  4078. /** Removes a range of elements from the array.
  4079. This will remove a set of elements, starting from the given index,
  4080. and move subsequent elements down to close the gap.
  4081. If the range extends beyond the bounds of the array, it will
  4082. be safely clipped to the size of the array.
  4083. @param startIndex the index of the first element to remove
  4084. @param numberToRemove how many elements should be removed
  4085. @see remove, removeValue
  4086. */
  4087. void removeRange (int startIndex,
  4088. const int numberToRemove) throw()
  4089. {
  4090. lock.enter();
  4091. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4092. startIndex = jlimit (0, numUsed, startIndex);
  4093. if (endIndex > startIndex)
  4094. {
  4095. const int rangeSize = endIndex - startIndex;
  4096. ElementType* e = this->elements + startIndex;
  4097. int numToShift = numUsed - endIndex;
  4098. numUsed -= rangeSize;
  4099. while (--numToShift >= 0)
  4100. {
  4101. *e = e [rangeSize];
  4102. ++e;
  4103. }
  4104. if ((numUsed << 1) < this->numAllocated)
  4105. minimiseStorageOverheads();
  4106. }
  4107. lock.exit();
  4108. }
  4109. /** Removes the last n elements from the array.
  4110. @param howManyToRemove how many elements to remove from the end of the array
  4111. @see remove, removeValue, removeRange
  4112. */
  4113. void removeLast (const int howManyToRemove = 1) throw()
  4114. {
  4115. lock.enter();
  4116. numUsed = jmax (0, numUsed - howManyToRemove);
  4117. if ((numUsed << 1) < this->numAllocated)
  4118. minimiseStorageOverheads();
  4119. lock.exit();
  4120. }
  4121. /** Removes any elements which are also in another array.
  4122. @param otherArray the other array in which to look for elements to remove
  4123. @see removeValuesNotIn, remove, removeValue, removeRange
  4124. */
  4125. template <class OtherArrayType>
  4126. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4127. {
  4128. otherArray.lockArray();
  4129. lock.enter();
  4130. if (this == &otherArray)
  4131. {
  4132. clear();
  4133. }
  4134. else
  4135. {
  4136. if (otherArray.size() > 0)
  4137. {
  4138. for (int i = numUsed; --i >= 0;)
  4139. if (otherArray.contains (this->elements [i]))
  4140. remove (i);
  4141. }
  4142. }
  4143. lock.exit();
  4144. otherArray.unlockArray();
  4145. }
  4146. /** Removes any elements which are not found in another array.
  4147. Only elements which occur in this other array will be retained.
  4148. @param otherArray the array in which to look for elements NOT to remove
  4149. @see removeValuesIn, remove, removeValue, removeRange
  4150. */
  4151. template <class OtherArrayType>
  4152. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4153. {
  4154. otherArray.lockArray();
  4155. lock.enter();
  4156. if (this != &otherArray)
  4157. {
  4158. if (otherArray.size() <= 0)
  4159. {
  4160. clear();
  4161. }
  4162. else
  4163. {
  4164. for (int i = numUsed; --i >= 0;)
  4165. if (! otherArray.contains (this->elements [i]))
  4166. remove (i);
  4167. }
  4168. }
  4169. lock.exit();
  4170. otherArray.unlockArray();
  4171. }
  4172. /** Swaps over two elements in the array.
  4173. This swaps over the elements found at the two indexes passed in.
  4174. If either index is out-of-range, this method will do nothing.
  4175. @param index1 index of one of the elements to swap
  4176. @param index2 index of the other element to swap
  4177. */
  4178. void swap (const int index1,
  4179. const int index2) throw()
  4180. {
  4181. lock.enter();
  4182. if (((unsigned int) index1) < (unsigned int) numUsed
  4183. && ((unsigned int) index2) < (unsigned int) numUsed)
  4184. {
  4185. swapVariables (this->elements [index1],
  4186. this->elements [index2]);
  4187. }
  4188. lock.exit();
  4189. }
  4190. /** Moves one of the values to a different position.
  4191. This will move the value to a specified index, shuffling along
  4192. any intervening elements as required.
  4193. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4194. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4195. @param currentIndex the index of the value to be moved. If this isn't a
  4196. valid index, then nothing will be done
  4197. @param newIndex the index at which you'd like this value to end up. If this
  4198. is less than zero, the value will be moved to the end
  4199. of the array
  4200. */
  4201. void move (const int currentIndex,
  4202. int newIndex) throw()
  4203. {
  4204. if (currentIndex != newIndex)
  4205. {
  4206. lock.enter();
  4207. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4208. {
  4209. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4210. newIndex = numUsed - 1;
  4211. const ElementType value = this->elements [currentIndex];
  4212. if (newIndex > currentIndex)
  4213. {
  4214. memmove (this->elements + currentIndex,
  4215. this->elements + currentIndex + 1,
  4216. (newIndex - currentIndex) * sizeof (ElementType));
  4217. }
  4218. else
  4219. {
  4220. memmove (this->elements + newIndex + 1,
  4221. this->elements + newIndex,
  4222. (currentIndex - newIndex) * sizeof (ElementType));
  4223. }
  4224. this->elements [newIndex] = value;
  4225. }
  4226. lock.exit();
  4227. }
  4228. }
  4229. /** Reduces the amount of storage being used by the array.
  4230. Arrays typically allocate slightly more storage than they need, and after
  4231. removing elements, they may have quite a lot of unused space allocated.
  4232. This method will reduce the amount of allocated storage to a minimum.
  4233. */
  4234. void minimiseStorageOverheads() throw()
  4235. {
  4236. lock.enter();
  4237. if (numUsed == 0)
  4238. {
  4239. this->setAllocatedSize (0);
  4240. }
  4241. else
  4242. {
  4243. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  4244. if (newAllocation < this->numAllocated)
  4245. this->setAllocatedSize (newAllocation);
  4246. }
  4247. lock.exit();
  4248. }
  4249. /** Increases the array's internal storage to hold a minimum number of elements.
  4250. Calling this before adding a large known number of elements means that
  4251. the array won't have to keep dynamically resizing itself as the elements
  4252. are added, and it'll therefore be more efficient.
  4253. */
  4254. void ensureStorageAllocated (const int minNumElements) throw()
  4255. {
  4256. this->ensureAllocatedSize (minNumElements);
  4257. }
  4258. /** Sorts the elements in the array.
  4259. This will use a comparator object to sort the elements into order. The object
  4260. passed must have a method of the form:
  4261. @code
  4262. int compareElements (ElementType first, ElementType second);
  4263. @endcode
  4264. ..and this method must return:
  4265. - a value of < 0 if the first comes before the second
  4266. - a value of 0 if the two objects are equivalent
  4267. - a value of > 0 if the second comes before the first
  4268. To improve performance, the compareElements() method can be declared as static or const.
  4269. @param comparator the comparator to use for comparing elements.
  4270. @param retainOrderOfEquivalentItems if this is true, then items
  4271. which the comparator says are equivalent will be
  4272. kept in the order in which they currently appear
  4273. in the array. This is slower to perform, but may
  4274. be important in some cases. If it's false, a faster
  4275. algorithm is used, but equivalent elements may be
  4276. rearranged.
  4277. @see addSorted, indexOfSorted, sortArray
  4278. */
  4279. template <class ElementComparator>
  4280. void sort (ElementComparator& comparator,
  4281. const bool retainOrderOfEquivalentItems = false) const throw()
  4282. {
  4283. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4284. // avoids getting warning messages about the parameter being unused
  4285. lock.enter();
  4286. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4287. lock.exit();
  4288. }
  4289. /** Locks the array's CriticalSection.
  4290. Of course if the type of section used is a DummyCriticalSection, this won't
  4291. have any effect.
  4292. @see unlockArray
  4293. */
  4294. void lockArray() const throw()
  4295. {
  4296. lock.enter();
  4297. }
  4298. /** Unlocks the array's CriticalSection.
  4299. Of course if the type of section used is a DummyCriticalSection, this won't
  4300. have any effect.
  4301. @see lockArray
  4302. */
  4303. void unlockArray() const throw()
  4304. {
  4305. lock.exit();
  4306. }
  4307. juce_UseDebuggingNewOperator
  4308. private:
  4309. int numUsed;
  4310. TypeOfCriticalSectionToUse lock;
  4311. };
  4312. #endif // __JUCE_ARRAY_JUCEHEADER__
  4313. /********* End of inlined file: juce_Array.h *********/
  4314. /**
  4315. A typedef for an Array of void*'s.
  4316. VoidArrays are used in various places throughout the library instead of
  4317. more strongly-typed arrays, to keep code-size low.
  4318. */
  4319. typedef Array <void*> VoidArray;
  4320. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4321. /********* End of inlined file: juce_VoidArray.h *********/
  4322. #ifndef DOXYGEN
  4323. // (used in StringArray::appendNumbersToDuplicates)
  4324. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4325. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4326. #endif
  4327. /**
  4328. A special array for holding a list of strings.
  4329. @see String, StringPairArray
  4330. */
  4331. class JUCE_API StringArray
  4332. {
  4333. public:
  4334. /** Creates an empty string array */
  4335. StringArray() throw();
  4336. /** Creates a copy of another string array */
  4337. StringArray (const StringArray& other) throw();
  4338. /** Creates a copy of an array of string literals.
  4339. @param strings an array of strings to add. Null pointers in the array will be
  4340. treated as empty strings
  4341. @param numberOfStrings how many items there are in the array
  4342. */
  4343. StringArray (const juce_wchar** const strings,
  4344. const int numberOfStrings) throw();
  4345. /** Creates a copy of an array of string literals.
  4346. @param strings an array of strings to add. Null pointers in the array will be
  4347. treated as empty strings
  4348. @param numberOfStrings how many items there are in the array
  4349. */
  4350. StringArray (const char** const strings,
  4351. const int numberOfStrings) throw();
  4352. /** Creates a copy of a null-terminated array of string literals.
  4353. Each item from the array passed-in is added, until it encounters a null pointer,
  4354. at which point it stops.
  4355. */
  4356. StringArray (const juce_wchar** const strings) throw();
  4357. /** Creates a copy of a null-terminated array of string literals.
  4358. Each item from the array passed-in is added, until it encounters a null pointer,
  4359. at which point it stops.
  4360. */
  4361. StringArray (const char** const strings) throw();
  4362. /** Destructor. */
  4363. virtual ~StringArray() throw();
  4364. /** Copies the contents of another string array into this one */
  4365. const StringArray& operator= (const StringArray& other) throw();
  4366. /** Compares two arrays.
  4367. Comparisons are case-sensitive.
  4368. @returns true only if the other array contains exactly the same strings in the same order
  4369. */
  4370. bool operator== (const StringArray& other) const throw();
  4371. /** Compares two arrays.
  4372. Comparisons are case-sensitive.
  4373. @returns false if the other array contains exactly the same strings in the same order
  4374. */
  4375. bool operator!= (const StringArray& other) const throw();
  4376. /** Returns the number of strings in the array */
  4377. inline int size() const throw() { return strings.size(); };
  4378. /** Returns one of the strings from the array.
  4379. If the index is out-of-range, an empty string is returned.
  4380. Obviously the reference returned shouldn't be stored for later use, as the
  4381. string it refers to may disappear when the array changes.
  4382. */
  4383. const String& operator[] (const int index) const throw();
  4384. /** Searches for a string in the array.
  4385. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4386. @returns true if the string is found inside the array
  4387. */
  4388. bool contains (const String& stringToLookFor,
  4389. const bool ignoreCase = false) const throw();
  4390. /** Searches for a string in the array.
  4391. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4392. @param stringToLookFor the string to try to find
  4393. @param ignoreCase whether the comparison should be case-insensitive
  4394. @param startIndex the first index to start searching from
  4395. @returns the index of the first occurrence of the string in this array,
  4396. or -1 if it isn't found.
  4397. */
  4398. int indexOf (const String& stringToLookFor,
  4399. const bool ignoreCase = false,
  4400. int startIndex = 0) const throw();
  4401. /** Appends a string at the end of the array. */
  4402. void add (const String& stringToAdd) throw();
  4403. /** Inserts a string into the array.
  4404. This will insert a string into the array at the given index, moving
  4405. up the other elements to make room for it.
  4406. If the index is less than zero or greater than the size of the array,
  4407. the new string will be added to the end of the array.
  4408. */
  4409. void insert (const int index,
  4410. const String& stringToAdd) throw();
  4411. /** Adds a string to the array as long as it's not already in there.
  4412. The search can optionally be case-insensitive.
  4413. */
  4414. void addIfNotAlreadyThere (const String& stringToAdd,
  4415. const bool ignoreCase = false) throw();
  4416. /** Replaces one of the strings in the array with another one.
  4417. If the index is higher than the array's size, the new string will be
  4418. added to the end of the array; if it's less than zero nothing happens.
  4419. */
  4420. void set (const int index,
  4421. const String& newString) throw();
  4422. /** Appends some strings from another array to the end of this one.
  4423. @param other the array to add
  4424. @param startIndex the first element of the other array to add
  4425. @param numElementsToAdd the maximum number of elements to add (if this is
  4426. less than zero, they are all added)
  4427. */
  4428. void addArray (const StringArray& other,
  4429. int startIndex = 0,
  4430. int numElementsToAdd = -1) throw();
  4431. /** Breaks up a string into tokens and adds them to this array.
  4432. This will tokenise the given string using whitespace characters as the
  4433. token delimiters, and will add these tokens to the end of the array.
  4434. @returns the number of tokens added
  4435. */
  4436. int addTokens (const tchar* const stringToTokenise,
  4437. const bool preserveQuotedStrings) throw();
  4438. /** Breaks up a string into tokens and adds them to this array.
  4439. This will tokenise the given string (using the string passed in to define the
  4440. token delimiters), and will add these tokens to the end of the array.
  4441. @param stringToTokenise the string to tokenise
  4442. @param breakCharacters a string of characters, any of which will be considered
  4443. to be a token delimiter.
  4444. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4445. which are treated as quotes. Any text occurring
  4446. between quotes is not broken up into tokens.
  4447. @returns the number of tokens added
  4448. */
  4449. int addTokens (const tchar* const stringToTokenise,
  4450. const tchar* breakCharacters,
  4451. const tchar* quoteCharacters) throw();
  4452. /** Breaks up a string into lines and adds them to this array.
  4453. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4454. to the array. Line-break characters are omitted from the strings that are added to
  4455. the array.
  4456. */
  4457. int addLines (const tchar* stringToBreakUp) throw();
  4458. /** Removes all elements from the array. */
  4459. void clear() throw();
  4460. /** Removes a string from the array.
  4461. If the index is out-of-range, no action will be taken.
  4462. */
  4463. void remove (const int index) throw();
  4464. /** Finds a string in the array and removes it.
  4465. This will remove the first occurrence of the given string from the array. The
  4466. comparison may be case-insensitive depending on the ignoreCase parameter.
  4467. */
  4468. void removeString (const String& stringToRemove,
  4469. const bool ignoreCase = false) throw();
  4470. /** Removes any duplicated elements from the array.
  4471. If any string appears in the array more than once, only the first occurrence of
  4472. it will be retained.
  4473. @param ignoreCase whether to use a case-insensitive comparison
  4474. */
  4475. void removeDuplicates (const bool ignoreCase) throw();
  4476. /** Removes empty strings from the array.
  4477. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4478. characters will also be removed
  4479. */
  4480. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4481. /** Moves one of the strings to a different position.
  4482. This will move the string to a specified index, shuffling along
  4483. any intervening elements as required.
  4484. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4485. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4486. @param currentIndex the index of the value to be moved. If this isn't a
  4487. valid index, then nothing will be done
  4488. @param newIndex the index at which you'd like this value to end up. If this
  4489. is less than zero, the value will be moved to the end
  4490. of the array
  4491. */
  4492. void move (const int currentIndex, int newIndex) throw();
  4493. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4494. void trim() throw();
  4495. /** Adds numbers to the strings in the array, to make each string unique.
  4496. This will add numbers to the ends of groups of similar strings.
  4497. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4498. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4499. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4500. also has a number appended to it.
  4501. @param preNumberString when adding a number, this string is added before the number
  4502. @param postNumberString this string is appended after any numbers that are added
  4503. */
  4504. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4505. const bool appendNumberToFirstInstance,
  4506. const tchar* const preNumberString = defaultPreNumberString,
  4507. const tchar* const postNumberString = defaultPostNumberString) throw();
  4508. /** Joins the strings in the array together into one string.
  4509. This will join a range of elements from the array into a string, separating
  4510. them with a given string.
  4511. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4512. @param separatorString the string to insert between all the strings
  4513. @param startIndex the first element to join
  4514. @param numberOfElements how many elements to join together. If this is less
  4515. than zero, all available elements will be used.
  4516. */
  4517. const String joinIntoString (const String& separatorString,
  4518. int startIndex = 0,
  4519. int numberOfElements = -1) const throw();
  4520. /** Sorts the array into alphabetical order.
  4521. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4522. */
  4523. void sort (const bool ignoreCase) throw();
  4524. /** Reduces the amount of storage being used by the array.
  4525. Arrays typically allocate slightly more storage than they need, and after
  4526. removing elements, they may have quite a lot of unused space allocated.
  4527. This method will reduce the amount of allocated storage to a minimum.
  4528. */
  4529. void minimiseStorageOverheads() throw();
  4530. juce_UseDebuggingNewOperator
  4531. private:
  4532. VoidArray strings;
  4533. };
  4534. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4535. /********* End of inlined file: juce_StringArray.h *********/
  4536. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4537. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4538. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4539. /**
  4540. A class to hold a resizable block of raw data.
  4541. */
  4542. class JUCE_API MemoryBlock
  4543. {
  4544. public:
  4545. /** Create an uninitialised block with 0 size. */
  4546. MemoryBlock() throw();
  4547. /** Creates a memory block with a given initial size.
  4548. @param initialSize the size of block to create
  4549. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4550. */
  4551. MemoryBlock (const int initialSize,
  4552. const bool initialiseToZero = false) throw();
  4553. /** Creates a copy of another memory block. */
  4554. MemoryBlock (const MemoryBlock& other) throw();
  4555. /** Creates a memory block using a copy of a block of data.
  4556. @param dataToInitialiseFrom some data to copy into this block
  4557. @param sizeInBytes how much space to use
  4558. */
  4559. MemoryBlock (const void* const dataToInitialiseFrom,
  4560. const int sizeInBytes) throw();
  4561. /** Destructor. */
  4562. ~MemoryBlock() throw();
  4563. /** Copies another memory block onto this one.
  4564. This block will be resized and copied to exactly match the other one.
  4565. */
  4566. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4567. /** Compares two memory blocks.
  4568. @returns true only if the two blocks are the same size and have identical contents.
  4569. */
  4570. bool operator== (const MemoryBlock& other) const throw();
  4571. /** Compares two memory blocks.
  4572. @returns true if the two blocks are different sizes or have different contents.
  4573. */
  4574. bool operator!= (const MemoryBlock& other) const throw();
  4575. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4576. Note that the pointer returned will probably become invalid when the
  4577. block is resized.
  4578. */
  4579. template <class DataType>
  4580. operator DataType*() const throw() { return (DataType*) data; }
  4581. /** Returns a void pointer to the data.
  4582. Note that the pointer returned will probably become invalid when the
  4583. block is resized.
  4584. */
  4585. void* getData() const throw() { return data; }
  4586. /** Returns a byte from the memory block.
  4587. This returns a reference, so you can also use it to set a byte.
  4588. */
  4589. char& operator[] (const int offset) const throw() { return data [offset]; }
  4590. /** Returns the block's current allocated size, in bytes. */
  4591. int getSize() const throw() { return size; }
  4592. /** Resizes the memory block.
  4593. This will try to keep as much of the block's current content as it can,
  4594. and can optionally be made to clear any new space that gets allocated at
  4595. the end of the block.
  4596. @param newSize the new desired size for the block
  4597. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4598. whether to clear the new section or just leave it
  4599. uninitialised
  4600. @see ensureSize
  4601. */
  4602. void setSize (const int newSize,
  4603. const bool initialiseNewSpaceToZero = false) throw();
  4604. /** Increases the block's size only if it's smaller than a given size.
  4605. @param minimumSize if the block is already bigger than this size, no action
  4606. will be taken; otherwise it will be increased to this size
  4607. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4608. whether to clear the new section or just leave it
  4609. uninitialised
  4610. @see setSize
  4611. */
  4612. void ensureSize (const int minimumSize,
  4613. const bool initialiseNewSpaceToZero = false) throw();
  4614. /** Fills the entire memory block with a repeated byte value.
  4615. This is handy for clearing a block of memory to zero.
  4616. */
  4617. void fillWith (const uint8 valueToUse) throw();
  4618. /** Adds another block of data to the end of this one.
  4619. This block's size will be increased accordingly.
  4620. */
  4621. void append (const void* const data,
  4622. const int numBytes) throw();
  4623. /** Copies data into this MemoryBlock from a memory address.
  4624. @param srcData the memory location of the data to copy into this block
  4625. @param destinationOffset the offset in this block at which the data being copied should begin
  4626. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4627. it will be clipped so not to do anything nasty)
  4628. */
  4629. void copyFrom (const void* srcData,
  4630. int destinationOffset,
  4631. int numBytes) throw();
  4632. /** Copies data from this MemoryBlock to a memory address.
  4633. @param destData the memory location to write to
  4634. @param sourceOffset the offset within this block from which the copied data will be read
  4635. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4636. zeros will be used for that portion of the data)
  4637. */
  4638. void copyTo (void* destData,
  4639. int sourceOffset,
  4640. int numBytes) const throw();
  4641. /** Chops out a section of the block.
  4642. This will remove a section of the memory block and close the gap around it,
  4643. shifting any subsequent data downwards and reducing the size of the block.
  4644. If the range specified goes beyond the size of the block, it will be clipped.
  4645. */
  4646. void removeSection (int startByte, int numBytesToRemove) throw();
  4647. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4648. characters in the system's default encoding. */
  4649. const String toString() const throw();
  4650. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4651. The block will be resized to the number of valid bytes read from the string.
  4652. Non-hex characters in the string will be ignored.
  4653. @see String::toHexString()
  4654. */
  4655. void loadFromHexString (const String& sourceHexString) throw();
  4656. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4657. void setBitRange (int bitRangeStart,
  4658. int numBits,
  4659. int binaryNumberToApply) throw();
  4660. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4661. int getBitRange (int bitRangeStart,
  4662. int numBitsToRead) const throw();
  4663. /** Returns a string of characters that represent the binary contents of this block.
  4664. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4665. of simple non-extended characters, e.g. for storage in XML.
  4666. @see fromBase64Encoding
  4667. */
  4668. const String toBase64Encoding() const throw();
  4669. /** Takes a string of encoded characters and turns it into binary data.
  4670. The string passed in must have been created by to64BitEncoding(), and this
  4671. block will be resized to recreate the original data block.
  4672. @see toBase64Encoding
  4673. */
  4674. bool fromBase64Encoding (const String& encodedString) throw();
  4675. juce_UseDebuggingNewOperator
  4676. private:
  4677. char* data;
  4678. int size;
  4679. };
  4680. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4681. /********* End of inlined file: juce_MemoryBlock.h *********/
  4682. class FileInputStream;
  4683. class FileOutputStream;
  4684. /**
  4685. Represents a local file or directory.
  4686. This class encapsulates the absolute pathname of a file or directory, and
  4687. has methods for finding out about the file and changing its properties.
  4688. To read or write to the file, there are methods for returning an input or
  4689. output stream.
  4690. @see FileInputStream, FileOutputStream
  4691. */
  4692. class JUCE_API File
  4693. {
  4694. public:
  4695. /** Creates an (invalid) file object.
  4696. The file is initially set to an empty path, so getFullPath() will return
  4697. an empty string, and comparing the file to File::nonexistent will return
  4698. true.
  4699. You can use its operator= method to point it at a proper file.
  4700. */
  4701. File() throw() {}
  4702. /** Creates a file from an absolute path.
  4703. If the path supplied is a relative path, it is taken to be relative
  4704. to the current working directory (see File::getCurrentWorkingDirectory()),
  4705. but this isn't a recommended way of creating a file, because you
  4706. never know what the CWD is going to be.
  4707. On the Mac/Linux, the path can include "~" notation for referring to
  4708. user home directories.
  4709. */
  4710. File (const String& path) throw();
  4711. /** Creates a copy of another file object. */
  4712. File (const File& other) throw();
  4713. /** Destructor. */
  4714. ~File() throw() {}
  4715. /** Sets the file based on an absolute pathname.
  4716. If the path supplied is a relative path, it is taken to be relative
  4717. to the current working directory (see File::getCurrentWorkingDirectory()),
  4718. but this isn't a recommended way of creating a file, because you
  4719. never know what the CWD is going to be.
  4720. On the Mac/Linux, the path can include "~" notation for referring to
  4721. user home directories.
  4722. */
  4723. const File& operator= (const String& newFilePath) throw();
  4724. /** Copies from another file object. */
  4725. const File& operator= (const File& otherFile) throw();
  4726. /** This static constant is used for referring to an 'invalid' file. */
  4727. static const File nonexistent;
  4728. /** Checks whether the file actually exists.
  4729. @returns true if the file exists, either as a file or a directory.
  4730. @see existsAsFile, isDirectory
  4731. */
  4732. bool exists() const throw();
  4733. /** Checks whether the file exists and is a file rather than a directory.
  4734. @returns true only if this is a real file, false if it's a directory
  4735. or doesn't exist
  4736. @see exists, isDirectory
  4737. */
  4738. bool existsAsFile() const throw();
  4739. /** Checks whether the file is a directory that exists.
  4740. @returns true only if the file is a directory which actually exists, so
  4741. false if it's a file or doesn't exist at all
  4742. @see exists, existsAsFile
  4743. */
  4744. bool isDirectory() const throw();
  4745. /** Returns the size of the file in bytes.
  4746. @returns the number of bytes in the file, or 0 if it doesn't exist.
  4747. */
  4748. int64 getSize() const throw();
  4749. /** Utility function to convert a file size in bytes to a neat string description.
  4750. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  4751. 2000000 would produce "2 MB", etc.
  4752. */
  4753. static const String descriptionOfSizeInBytes (const int64 bytes);
  4754. /** Returns the complete, absolute path of this file.
  4755. This includes the filename and all its parent folders. On Windows it'll
  4756. also include the drive letter prefix; on Mac or Linux it'll be a complete
  4757. path starting from the root folder.
  4758. If you just want the file's name, you should use getFileName() or
  4759. getFileNameWithoutExtension().
  4760. @see getFileName, getRelativePathFrom
  4761. */
  4762. const String& getFullPathName() const throw() { return fullPath; }
  4763. /** Returns the last section of the pathname.
  4764. Returns just the final part of the path - e.g. if the whole path
  4765. is "/moose/fish/foo.txt" this will return "foo.txt".
  4766. For a directory, it returns the final part of the path - e.g. for the
  4767. directory "/moose/fish" it'll return "fish".
  4768. If the filename begins with a dot, it'll return the whole filename, e.g. for
  4769. "/moose/.fish", it'll return ".fish"
  4770. @see getFullPathName, getFileNameWithoutExtension
  4771. */
  4772. const String getFileName() const throw();
  4773. /** Creates a relative path that refers to a file relatively to a given directory.
  4774. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  4775. would return "../../foo.txt".
  4776. If it's not possible to navigate from one file to the other, an absolute
  4777. path is returned. If the paths are invalid, an empty string may also be
  4778. returned.
  4779. @param directoryToBeRelativeTo the directory which the resultant string will
  4780. be relative to. If this is actually a file rather than
  4781. a directory, its parent directory will be used instead.
  4782. If it doesn't exist, it's assumed to be a directory.
  4783. @see getChildFile, isAbsolutePath
  4784. */
  4785. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  4786. /** Returns the file's extension.
  4787. Returns the file extension of this file, also including the dot.
  4788. e.g. "/moose/fish/foo.txt" would return ".txt"
  4789. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  4790. */
  4791. const String getFileExtension() const throw();
  4792. /** Checks whether the file has a given extension.
  4793. @param extensionToTest the extension to look for - it doesn't matter whether or
  4794. not this string has a dot at the start, so ".wav" and "wav"
  4795. will have the same effect. The comparison used is
  4796. case-insensitve.
  4797. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  4798. */
  4799. bool hasFileExtension (const String& extensionToTest) const throw();
  4800. /** Returns a version of this file with a different file extension.
  4801. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  4802. @param newExtension the new extension, either with or without a dot at the start (this
  4803. doesn't make any difference). To get remove a file's extension altogether,
  4804. pass an empty string into this function.
  4805. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  4806. */
  4807. const File withFileExtension (const String& newExtension) const throw();
  4808. /** Returns the last part of the filename, without its file extension.
  4809. e.g. for "/moose/fish/foo.txt" this will return "foo".
  4810. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  4811. */
  4812. const String getFileNameWithoutExtension() const throw();
  4813. /** Returns a 32-bit hash-code that identifies this file.
  4814. This is based on the filename. Obviously it's possible, although unlikely, that
  4815. two files will have the same hash-code.
  4816. */
  4817. int hashCode() const throw();
  4818. /** Returns a 64-bit hash-code that identifies this file.
  4819. This is based on the filename. Obviously it's possible, although unlikely, that
  4820. two files will have the same hash-code.
  4821. */
  4822. int64 hashCode64() const throw();
  4823. /** Returns a file based on a relative path.
  4824. This will find a child file or directory of the current object.
  4825. e.g.
  4826. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  4827. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  4828. If the string is actually an absolute path, it will be treated as such, e.g.
  4829. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  4830. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  4831. */
  4832. const File getChildFile (String relativePath) const throw();
  4833. /** Returns a file which is in the same directory as this one.
  4834. This is equivalent to getParentDirectory().getChildFile (name).
  4835. @see getChildFile, getParentDirectory
  4836. */
  4837. const File getSiblingFile (const String& siblingFileName) const throw();
  4838. /** Returns the directory that contains this file or directory.
  4839. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  4840. */
  4841. const File getParentDirectory() const throw();
  4842. /** Checks whether a file is somewhere inside a directory.
  4843. Returns true if this file is somewhere inside a subdirectory of the directory
  4844. that is passed in. Neither file actually has to exist, because the function
  4845. just checks the paths for similarities.
  4846. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  4847. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  4848. */
  4849. bool isAChildOf (const File& potentialParentDirectory) const throw();
  4850. /** Chooses a filename relative to this one that doesn't already exist.
  4851. If this file is a directory, this will return a child file of this
  4852. directory that doesn't exist, by adding numbers to a prefix and suffix until
  4853. it finds one that isn't already there.
  4854. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  4855. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  4856. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  4857. @param prefix the string to use for the filename before the number
  4858. @param suffix the string to add to the filename after the number
  4859. @param putNumbersInBrackets if true, this will create filenames in the
  4860. format "prefix(number)suffix", if false, it will leave the
  4861. brackets out.
  4862. */
  4863. const File getNonexistentChildFile (const String& prefix,
  4864. const String& suffix,
  4865. bool putNumbersInBrackets = true) const throw();
  4866. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  4867. If this file doesn't exist, this will just return itself, otherwise it
  4868. will return an appropriate sibling that doesn't exist, e.g. if a file
  4869. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  4870. @param putNumbersInBrackets whether to add brackets around the numbers that
  4871. get appended to the new filename.
  4872. */
  4873. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  4874. /** Compares the pathnames for two files. */
  4875. bool operator== (const File& otherFile) const throw();
  4876. /** Compares the pathnames for two files. */
  4877. bool operator!= (const File& otherFile) const throw();
  4878. /** Checks whether a file can be created or written to.
  4879. @returns true if it's possible to create and write to this file. If the file
  4880. doesn't already exist, this will check its parent directory to
  4881. see if writing is allowed.
  4882. @see setReadOnly
  4883. */
  4884. bool hasWriteAccess() const throw();
  4885. /** Changes the write-permission of a file or directory.
  4886. @param shouldBeReadOnly whether to add or remove write-permission
  4887. @param applyRecursively if the file is a directory and this is true, it will
  4888. recurse through all the subfolders changing the permissions
  4889. of all files
  4890. @returns true if it manages to change the file's permissions.
  4891. @see hasWriteAccess
  4892. */
  4893. bool setReadOnly (const bool shouldBeReadOnly,
  4894. const bool applyRecursively = false) const throw();
  4895. /** Returns true if this file is a hidden or system file.
  4896. The criteria for deciding whether a file is hidden are platform-dependent.
  4897. */
  4898. bool isHidden() const throw();
  4899. /** If this file is a link, this returns the file that it points to.
  4900. If this file isn't actually link, it'll just return itself.
  4901. */
  4902. const File getLinkedTarget() const throw();
  4903. /** Returns the last modification time of this file.
  4904. @returns the time, or an invalid time if the file doesn't exist.
  4905. @see setLastModificationTime, getLastAccessTime, getCreationTime
  4906. */
  4907. const Time getLastModificationTime() const throw();
  4908. /** Returns the last time this file was accessed.
  4909. @returns the time, or an invalid time if the file doesn't exist.
  4910. @see setLastAccessTime, getLastModificationTime, getCreationTime
  4911. */
  4912. const Time getLastAccessTime() const throw();
  4913. /** Returns the time that this file was created.
  4914. @returns the time, or an invalid time if the file doesn't exist.
  4915. @see getLastModificationTime, getLastAccessTime
  4916. */
  4917. const Time getCreationTime() const throw();
  4918. /** Changes the modification time for this file.
  4919. @param newTime the time to apply to the file
  4920. @returns true if it manages to change the file's time.
  4921. @see getLastModificationTime, setLastAccessTime, setCreationTime
  4922. */
  4923. bool setLastModificationTime (const Time& newTime) const throw();
  4924. /** Changes the last-access time for this file.
  4925. @param newTime the time to apply to the file
  4926. @returns true if it manages to change the file's time.
  4927. @see getLastAccessTime, setLastModificationTime, setCreationTime
  4928. */
  4929. bool setLastAccessTime (const Time& newTime) const throw();
  4930. /** Changes the creation date for this file.
  4931. @param newTime the time to apply to the file
  4932. @returns true if it manages to change the file's time.
  4933. @see getCreationTime, setLastModificationTime, setLastAccessTime
  4934. */
  4935. bool setCreationTime (const Time& newTime) const throw();
  4936. /** Creates an empty file if it doesn't already exist.
  4937. If the file that this object refers to doesn't exist, this will create a file
  4938. of zero size.
  4939. If it already exists or is a directory, this method will do nothing.
  4940. @returns true if the file has been created (or if it already existed).
  4941. @see createDirectory
  4942. */
  4943. bool create() const throw();
  4944. /** Creates a new directory for this filename.
  4945. This will try to create the file as a directory, and fill also create
  4946. any parent directories it needs in order to complete the operation.
  4947. @returns true if the directory has been created successfully, (or if it
  4948. already existed beforehand).
  4949. @see create
  4950. */
  4951. bool createDirectory() const throw();
  4952. /** Deletes a file.
  4953. If this file is actually a directory, it may not be deleted correctly if it
  4954. contains files. See deleteRecursively() as a better way of deleting directories.
  4955. @returns true if the file has been successfully deleted (or if it didn't exist to
  4956. begin with).
  4957. @see deleteRecursively
  4958. */
  4959. bool deleteFile() const throw();
  4960. /** Deletes a file or directory and all its subdirectories.
  4961. If this file is a directory, this will try to delete it and all its subfolders. If
  4962. it's just a file, it will just try to delete the file.
  4963. @returns true if the file and all its subfolders have been successfully deleted
  4964. (or if it didn't exist to begin with).
  4965. @see deleteFile
  4966. */
  4967. bool deleteRecursively() const throw();
  4968. /** Moves this file or folder to the trash.
  4969. @returns true if the operation succeeded. It could fail if the trash is full, or
  4970. if the file is write-protected, so you should check the return value
  4971. and act appropriately.
  4972. */
  4973. bool moveToTrash() const throw();
  4974. /** Moves or renames a file.
  4975. Tries to move a file to a different location.
  4976. If the target file already exists, this will attempt to delete it first, and
  4977. will fail if this can't be done.
  4978. Note that the destination file isn't the directory to put it in, it's the actual
  4979. filename that you want the new file to have.
  4980. @returns true if the operation succeeds
  4981. */
  4982. bool moveFileTo (const File& targetLocation) const throw();
  4983. /** Copies a file.
  4984. Tries to copy a file to a different location.
  4985. If the target file already exists, this will attempt to delete it first, and
  4986. will fail if this can't be done.
  4987. @returns true if the operation succeeds
  4988. */
  4989. bool copyFileTo (const File& targetLocation) const throw();
  4990. /** Copies a directory.
  4991. Tries to copy an entire directory, recursively.
  4992. If this file isn't a directory or if any target files can't be created, this
  4993. will return false.
  4994. @param newDirectory the directory that this one should be copied to. Note that this
  4995. is the name of the actual directory to create, not the directory
  4996. into which the new one should be placed, so there must be enough
  4997. write privileges to create it if it doesn't exist. Any files inside
  4998. it will be overwritten by similarly named ones that are copied.
  4999. */
  5000. bool copyDirectoryTo (const File& newDirectory) const throw();
  5001. /** Used in file searching, to specify whether to return files, directories, or both.
  5002. */
  5003. enum TypesOfFileToFind
  5004. {
  5005. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5006. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5007. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5008. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5009. };
  5010. /** Searches inside a directory for files matching a wildcard pattern.
  5011. Assuming that this file is a directory, this method will search it
  5012. for either files or subdirectories whose names match a filename pattern.
  5013. @param results an array to which File objects will be added for the
  5014. files that the search comes up with
  5015. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5016. return files, directories, or both. If the ignoreHiddenFiles flag
  5017. is also added to this value, hidden files won't be returned
  5018. @param searchRecursively if true, all subdirectories will be recursed into to do
  5019. an exhaustive search
  5020. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5021. @returns the number of results that have been found
  5022. @see getNumberOfChildFiles, DirectoryIterator
  5023. */
  5024. int findChildFiles (OwnedArray<File>& results,
  5025. const int whatToLookFor,
  5026. const bool searchRecursively,
  5027. const String& wildCardPattern = JUCE_T("*")) const throw();
  5028. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5029. Assuming that this file is a directory, this method will search it
  5030. for either files or subdirectories whose names match a filename pattern,
  5031. and will return the number of matches found.
  5032. This isn't a recursive call, and will only search this directory, not
  5033. its children.
  5034. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5035. count files, directories, or both. If the ignoreHiddenFiles flag
  5036. is also added to this value, hidden files won't be counted
  5037. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5038. @returns the number of matches found
  5039. @see findChildFiles, DirectoryIterator
  5040. */
  5041. int getNumberOfChildFiles (const int whatToLookFor,
  5042. const String& wildCardPattern = JUCE_T("*")) const throw();
  5043. /** Returns true if this file is a directory that contains one or more subdirectories.
  5044. @see isDirectory, findChildFiles
  5045. */
  5046. bool containsSubDirectories() const throw();
  5047. /** Creates a stream to read from this file.
  5048. @returns a stream that will read from this file (initially positioned at the
  5049. start of the file), or 0 if the file can't be opened for some reason
  5050. @see createOutputStream, loadFileAsData
  5051. */
  5052. FileInputStream* createInputStream() const throw();
  5053. /** Creates a stream to write to this file.
  5054. If the file exists, the stream that is returned will be positioned ready for
  5055. writing at the end of the file, so you might want to use deleteFile() first
  5056. to write to an empty file.
  5057. @returns a stream that will write to this file (initially positioned at the
  5058. end of the file), or 0 if the file can't be opened for some reason
  5059. @see createInputStream, printf, appendData, appendText
  5060. */
  5061. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5062. /** Loads a file's contents into memory as a block of binary data.
  5063. Of course, trying to load a very large file into memory will blow up, so
  5064. it's better to check first.
  5065. @param result the data block to which the file's contents should be appended - note
  5066. that if the memory block might already contain some data, you
  5067. might want to clear it first
  5068. @returns true if the file could all be read into memory
  5069. */
  5070. bool loadFileAsData (MemoryBlock& result) const throw();
  5071. /** Reads a file into memory as a string.
  5072. Attempts to load the entire file as a zero-terminated string.
  5073. This makes use of InputStream::readEntireStreamAsString, which should
  5074. automatically cope with unicode/acsii file formats.
  5075. */
  5076. const String loadFileAsString() const throw();
  5077. /** Writes text to the end of the file.
  5078. This will try to do a printf to the file.
  5079. @returns false if it can't write to the file for some reason
  5080. */
  5081. bool printf (const tchar* format, ...) const throw();
  5082. /** Appends a block of binary data to the end of the file.
  5083. This will try to write the given buffer to the end of the file.
  5084. @returns false if it can't write to the file for some reason
  5085. */
  5086. bool appendData (const void* const dataToAppend,
  5087. const int numberOfBytes) const throw();
  5088. /** Replaces this file's contents with a given block of data.
  5089. This will delete the file and replace it with the given data.
  5090. A nice feature of this method is that it's safe - instead of deleting
  5091. the file first and then re-writing it, it creates a new temporary file,
  5092. writes the data to that, and then moves the new file to replace the existing
  5093. file. This means that if the power gets pulled out or something crashes,
  5094. you're a lot less likely to end up with an empty file..
  5095. Returns true if the operation succeeds, or false if it fails.
  5096. @see appendText
  5097. */
  5098. bool replaceWithData (const void* const dataToWrite,
  5099. const int numberOfBytes) const throw();
  5100. /** Appends a string to the end of the file.
  5101. This will try to append a text string to the file, as either 16-bit unicode
  5102. or 8-bit characters in the default system encoding.
  5103. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5104. the endianness of the file.
  5105. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5106. @see replaceWithText
  5107. */
  5108. bool appendText (const String& textToAppend,
  5109. const bool asUnicode = false,
  5110. const bool writeUnicodeHeaderBytes = false) const throw();
  5111. /** Replaces this file's contents with a given text string.
  5112. This will delete the file and replace it with the given text.
  5113. A nice feature of this method is that it's safe - instead of deleting
  5114. the file first and then re-writing it, it creates a new temporary file,
  5115. writes the text to that, and then moves the new file to replace the existing
  5116. file. This means that if the power gets pulled out or something crashes,
  5117. you're a lot less likely to end up with an empty file..
  5118. For an explanation of the parameters here, see the appendText() method.
  5119. Returns true if the operation succeeds, or false if it fails.
  5120. @see appendText
  5121. */
  5122. bool replaceWithText (const String& textToWrite,
  5123. const bool asUnicode = false,
  5124. const bool writeUnicodeHeaderBytes = false) const throw();
  5125. /** Creates a set of files to represent each file root.
  5126. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5127. to which ones are available. On the Mac/Linux, this will probably
  5128. just add a single entry for "/".
  5129. */
  5130. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5131. /** Finds the name of the drive on which this file lives.
  5132. @returns the volume label of the drive, or an empty string if this isn't possible
  5133. */
  5134. const String getVolumeLabel() const throw();
  5135. /** Returns the serial number of the volume on which this file lives.
  5136. @returns the serial number, or zero if there's a problem doing this
  5137. */
  5138. int getVolumeSerialNumber() const throw();
  5139. /** Returns the number of bytes free on the drive that this file lives on.
  5140. @returns the number of bytes free, or 0 if there's a problem finding this out
  5141. */
  5142. int64 getBytesFreeOnVolume() const throw();
  5143. /** Returns true if this file is on a CD or DVD drive. */
  5144. bool isOnCDRomDrive() const throw();
  5145. /** Returns true if this file is on a hard disk.
  5146. This will fail if it's a network drive, but will still be true for
  5147. removable hard-disks.
  5148. */
  5149. bool isOnHardDisk() const throw();
  5150. /** Returns true if this file is on a removable disk drive.
  5151. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5152. */
  5153. bool isOnRemovableDrive() const throw();
  5154. /** Launches the file as a process.
  5155. - if the file is executable, this will run it.
  5156. - if it's a document of some kind, it will launch the document with its
  5157. default viewer application.
  5158. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5159. */
  5160. bool startAsProcess (const String& parameters = String::empty) const throw();
  5161. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5162. */
  5163. enum SpecialLocationType
  5164. {
  5165. /** The user's home folder. This is the same as using File ("~"). */
  5166. userHomeDirectory,
  5167. /** The user's default documents folder. On Windows, this might be the user's
  5168. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5169. doesn't tend to have one of these, so it might just return their home folder.
  5170. */
  5171. userDocumentsDirectory,
  5172. /** The folder that contains the user's desktop objects. */
  5173. userDesktopDirectory,
  5174. /** The folder in which applications store their persistent user-specific settings.
  5175. On Windows, this might be "\Documents and Settings\username\Application Data".
  5176. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5177. always create your own sub-folder to put them in, to avoid making a mess.
  5178. */
  5179. userApplicationDataDirectory,
  5180. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5181. of the computer, rather than just the current user.
  5182. On the Mac it'll be "/Library", on Windows, it could be something like
  5183. "\Documents and Settings\All Users\Application Data".
  5184. Depending on the setup, this folder may be read-only.
  5185. */
  5186. commonApplicationDataDirectory,
  5187. /** The folder that should be used for temporary files.
  5188. Always delete them when you're finished, to keep the user's computer tidy!
  5189. */
  5190. tempDirectory,
  5191. /** Returns this application's executable file.
  5192. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5193. host app.
  5194. On the mac this will return the unix binary, not the package folder - see
  5195. currentApplicationFile for that.
  5196. */
  5197. currentExecutableFile,
  5198. /** Returns this application's location.
  5199. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5200. host app.
  5201. On the mac this will return the package folder (if it's in one), not the unix binary
  5202. that's inside it - compare with currentExecutableFile.
  5203. */
  5204. currentApplicationFile,
  5205. /** The directory in which applications normally get installed.
  5206. So on windows, this would be something like "c:\program files", on the
  5207. Mac "/Applications", or "/usr" on linux.
  5208. */
  5209. globalApplicationsDirectory,
  5210. /** The most likely place where a user might store their music files.
  5211. */
  5212. userMusicDirectory,
  5213. /** The most likely place where a user might store their movie files.
  5214. */
  5215. userMoviesDirectory,
  5216. };
  5217. /** Finds the location of a special type of file or directory, such as a home folder or
  5218. documents folder.
  5219. @see SpecialLocationType
  5220. */
  5221. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5222. /** Returns a temporary file in the system's temp directory.
  5223. This will try to return the name of a non-existent temp file.
  5224. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5225. */
  5226. static const File createTempFile (const String& fileNameEnding) throw();
  5227. /** Returns the current working directory.
  5228. @see setAsCurrentWorkingDirectory
  5229. */
  5230. static const File getCurrentWorkingDirectory() throw();
  5231. /** Sets the current working directory to be this file.
  5232. For this to work the file must point to a valid directory.
  5233. @returns true if the current directory has been changed.
  5234. @see getCurrentWorkingDirectory
  5235. */
  5236. bool setAsCurrentWorkingDirectory() const throw();
  5237. /** The system-specific file separator character.
  5238. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5239. */
  5240. static const tchar separator;
  5241. /** The system-specific file separator character, as a string.
  5242. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5243. */
  5244. static const tchar* separatorString;
  5245. /** Removes illegal characters from a filename.
  5246. This will return a copy of the given string after removing characters
  5247. that are not allowed in a legal filename, and possibly shortening the
  5248. string if it's too long.
  5249. Because this will remove slashes, don't use it on an absolute pathname.
  5250. @see createLegalPathName
  5251. */
  5252. static const String createLegalFileName (const String& fileNameToFix) throw();
  5253. /** Removes illegal characters from a pathname.
  5254. Similar to createLegalFileName(), but this won't remove slashes, so can
  5255. be used on a complete pathname.
  5256. @see createLegalFileName
  5257. */
  5258. static const String createLegalPathName (const String& pathNameToFix) throw();
  5259. /** Indicates whether filenames are case-sensitive on the current operating system.
  5260. */
  5261. static bool areFileNamesCaseSensitive();
  5262. /** Returns true if the string seems to be a fully-specified absolute path.
  5263. */
  5264. static bool isAbsolutePath (const String& path) throw();
  5265. juce_UseDebuggingNewOperator
  5266. private:
  5267. String fullPath;
  5268. // internal way of contructing a file without checking the path
  5269. friend class DirectoryIterator;
  5270. File (const String&, int) throw();
  5271. const String getPathUpToLastSlash() const throw();
  5272. };
  5273. #endif // __JUCE_FILE_JUCEHEADER__
  5274. /********* End of inlined file: juce_File.h *********/
  5275. /**
  5276. A simple implemenation of a Logger that writes to a file.
  5277. @see Logger
  5278. */
  5279. class JUCE_API FileLogger : public Logger
  5280. {
  5281. public:
  5282. /** Creates a FileLogger for a given file.
  5283. @param fileToWriteTo the file that to use - new messages will be appended
  5284. to the file. If the file doesn't exist, it will be created,
  5285. along with any parent directories that are needed.
  5286. @param welcomeMessage when opened, the logger will write a header to the log, along
  5287. with the current date and time, and this welcome message
  5288. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5289. but is larger than this number of bytes, then the start of the
  5290. file will be truncated to keep the size down. This prevents a log
  5291. file getting ridiculously large over time. The file will be truncated
  5292. at a new-line boundary. If this value is less than zero, no size limit
  5293. will be imposed; if it's zero, the file will always be deleted. Note that
  5294. the size is only checked once when this object is created - any logging
  5295. that is done later will be appended without any checking
  5296. */
  5297. FileLogger (const File& fileToWriteTo,
  5298. const String& welcomeMessage,
  5299. const int maxInitialFileSizeBytes = 128 * 1024);
  5300. /** Destructor. */
  5301. ~FileLogger();
  5302. void logMessage (const String& message);
  5303. /** Helper function to create a log file in the correct place for this platform.
  5304. On Windows this will return a logger with a path such as:
  5305. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5306. On the Mac it'll create something like:
  5307. ~/Library/Logs/[logFileName]
  5308. The method might return 0 if the file can't be created for some reason.
  5309. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5310. it's best to use the something like the name of your application here.
  5311. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5312. call it "log.txt" because if it goes in a directory with logs
  5313. from other applications (as it will do on the Mac) then no-one
  5314. will know which one is yours!
  5315. @param welcomeMessage a message that will be written to the log when it's opened.
  5316. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5317. */
  5318. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5319. const String& logFileName,
  5320. const String& welcomeMessage,
  5321. const int maxInitialFileSizeBytes = 128 * 1024);
  5322. juce_UseDebuggingNewOperator
  5323. private:
  5324. File logFile;
  5325. CriticalSection logLock;
  5326. FileOutputStream* logStream;
  5327. void trimFileSize (int maxFileSizeBytes) const;
  5328. FileLogger (const FileLogger&);
  5329. const FileLogger& operator= (const FileLogger&);
  5330. };
  5331. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5332. /********* End of inlined file: juce_FileLogger.h *********/
  5333. #endif
  5334. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5335. /********* Start of inlined file: juce_Initialisation.h *********/
  5336. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5337. #define __JUCE_INITIALISATION_JUCEHEADER__
  5338. /** Initialises Juce's GUI classes.
  5339. If you're embedding Juce into an application that uses its own event-loop rather
  5340. than using the START_JUCE_APPLICATION macro, call this function before making any
  5341. Juce calls, to make sure things are initialised correctly.
  5342. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5343. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5344. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5345. */
  5346. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5347. /** Clears up any static data being used by Juce's GUI classes.
  5348. If you're embedding Juce into an application that uses its own event-loop rather
  5349. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5350. code to clean up any juce objects that might be lying around.
  5351. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5352. */
  5353. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5354. /** Initialises the core parts of Juce.
  5355. If you're embedding Juce into either a command-line program, call this function
  5356. at the start of your main() function to make sure that Juce is initialised correctly.
  5357. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5358. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5359. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5360. */
  5361. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5362. /** Clears up any static data being used by Juce's non-gui core classes.
  5363. If you're embedding Juce into either a command-line program, call this function
  5364. at the end of your main() function if you want to make sure any Juce objects are
  5365. cleaned up correctly.
  5366. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5367. */
  5368. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5369. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5370. /********* End of inlined file: juce_Initialisation.h *********/
  5371. #endif
  5372. #ifndef __JUCE_LOGGER_JUCEHEADER__
  5373. #endif
  5374. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  5375. #endif
  5376. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5377. #endif
  5378. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  5379. #endif
  5380. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5381. /********* Start of inlined file: juce_Random.h *********/
  5382. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5383. #define __JUCE_RANDOM_JUCEHEADER__
  5384. /********* Start of inlined file: juce_BitArray.h *********/
  5385. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  5386. #define __JUCE_BITARRAY_JUCEHEADER__
  5387. class MemoryBlock;
  5388. /**
  5389. An array of on/off bits, also usable to store large binary integers.
  5390. A BitArray acts like an arbitrarily large integer whose bits can be set or
  5391. cleared, and some basic mathematical operations can be done on the number as
  5392. a whole.
  5393. */
  5394. class JUCE_API BitArray
  5395. {
  5396. public:
  5397. /** Creates an empty BitArray */
  5398. BitArray() throw();
  5399. /** Creates a BitArray containing an integer value in its low bits.
  5400. The low 32 bits of the array are initialised with this value.
  5401. */
  5402. BitArray (const unsigned int value) throw();
  5403. /** Creates a BitArray containing an integer value in its low bits.
  5404. The low 32 bits of the array are initialised with the absolute value
  5405. passed in, and its sign is set to reflect the sign of the number.
  5406. */
  5407. BitArray (const int value) throw();
  5408. /** Creates a BitArray containing an integer value in its low bits.
  5409. The low 64 bits of the array are initialised with the absolute value
  5410. passed in, and its sign is set to reflect the sign of the number.
  5411. */
  5412. BitArray (int64 value) throw();
  5413. /** Creates a copy of another BitArray. */
  5414. BitArray (const BitArray& other) throw();
  5415. /** Destructor. */
  5416. ~BitArray() throw();
  5417. /** Copies another BitArray onto this one. */
  5418. const BitArray& operator= (const BitArray& other) throw();
  5419. /** Two arrays are the same if the same bits are set. */
  5420. bool operator== (const BitArray& other) const throw();
  5421. /** Two arrays are the same if the same bits are set. */
  5422. bool operator!= (const BitArray& other) const throw();
  5423. /** Clears all bits in the BitArray to 0. */
  5424. void clear() throw();
  5425. /** Clears a particular bit in the array. */
  5426. void clearBit (const int bitNumber) throw();
  5427. /** Sets a specified bit to 1.
  5428. If the bit number is high, this will grow the array to accomodate it.
  5429. */
  5430. void setBit (const int bitNumber) throw();
  5431. /** Sets or clears a specified bit. */
  5432. void setBit (const int bitNumber,
  5433. const bool shouldBeSet) throw();
  5434. /** Sets a range of bits to be either on or off.
  5435. @param startBit the first bit to change
  5436. @param numBits the number of bits to change
  5437. @param shouldBeSet whether to turn these bits on or off
  5438. */
  5439. void setRange (int startBit,
  5440. int numBits,
  5441. const bool shouldBeSet) throw();
  5442. /** Inserts a bit an a given position, shifting up any bits above it. */
  5443. void insertBit (const int bitNumber,
  5444. const bool shouldBeSet) throw();
  5445. /** Returns the value of a specified bit in the array.
  5446. If the index is out-of-range, the result will be false.
  5447. */
  5448. bool operator[] (const int bit) const throw();
  5449. /** Returns true if no bits are set. */
  5450. bool isEmpty() const throw();
  5451. /** Returns a range of bits in the array as an integer value.
  5452. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  5453. Asking for more than 32 bits isn't allowed (obviously).
  5454. */
  5455. int getBitRangeAsInt (int startBit, int numBits) const throw();
  5456. /** Sets a range of bits in the array based on an integer value.
  5457. Copies the given integer into the array, starting at startBit,
  5458. and only using up to numBits of the available bits.
  5459. */
  5460. void setBitRangeAsInt (int startBit, int numBits,
  5461. unsigned int valueToSet) throw();
  5462. /** Performs a bitwise OR with another BitArray.
  5463. The result ends up in this array.
  5464. */
  5465. void orWith (const BitArray& other) throw();
  5466. /** Performs a bitwise AND with another BitArray.
  5467. The result ends up in this array.
  5468. */
  5469. void andWith (const BitArray& other) throw();
  5470. /** Performs a bitwise XOR with another BitArray.
  5471. The result ends up in this array.
  5472. */
  5473. void xorWith (const BitArray& other) throw();
  5474. /** Adds another BitArray's value to this one.
  5475. Treating the two arrays as large positive integers, this
  5476. adds them up and puts the result in this array.
  5477. */
  5478. void add (const BitArray& other) throw();
  5479. /** Subtracts another BitArray's value from this one.
  5480. Treating the two arrays as large positive integers, this
  5481. subtracts them and puts the result in this array.
  5482. Note that if the result should be negative, this won't be
  5483. handled correctly.
  5484. */
  5485. void subtract (const BitArray& other) throw();
  5486. /** Multiplies another BitArray's value with this one.
  5487. Treating the two arrays as large positive integers, this
  5488. multiplies them and puts the result in this array.
  5489. */
  5490. void multiplyBy (const BitArray& other) throw();
  5491. /** Divides another BitArray's value into this one and also produces a remainder.
  5492. Treating the two arrays as large positive integers, this
  5493. divides this value by the other, leaving the quotient in this
  5494. array, and the remainder is copied into the other BitArray passed in.
  5495. */
  5496. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  5497. /** Returns the largest value that will divide both this value and the one
  5498. passed-in.
  5499. */
  5500. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  5501. /** Performs a modulo operation on this value.
  5502. The result is stored in this value.
  5503. */
  5504. void modulo (const BitArray& divisor) throw();
  5505. /** Performs a combined exponent and modulo operation.
  5506. This BitArray's value becomes (this ^ exponent) % modulus.
  5507. */
  5508. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  5509. /** Performs an inverse modulo on the value.
  5510. i.e. the result is (this ^ -1) mod (modulus).
  5511. */
  5512. void inverseModulo (const BitArray& modulus) throw();
  5513. /** Shifts a section of bits left or right.
  5514. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  5515. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  5516. */
  5517. void shiftBits (int howManyBitsLeft,
  5518. int startBit = 0) throw();
  5519. /** Does a signed comparison of two BitArrays.
  5520. Return values are:
  5521. - 0 if the numbers are the same
  5522. - < 0 if this number is smaller than the other
  5523. - > 0 if this number is bigger than the other
  5524. */
  5525. int compare (const BitArray& other) const throw();
  5526. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  5527. Return values are:
  5528. - 0 if the numbers are the same
  5529. - < 0 if this number is smaller than the other
  5530. - > 0 if this number is bigger than the other
  5531. */
  5532. int compareAbsolute (const BitArray& other) const throw();
  5533. /** Returns true if the value is less than zero.
  5534. @see setNegative, negate
  5535. */
  5536. bool isNegative() const throw();
  5537. /** Changes the sign of the number to be positive or negative.
  5538. @see isNegative, negate
  5539. */
  5540. void setNegative (const bool shouldBeNegative) throw();
  5541. /** Inverts the sign of the number.
  5542. @see isNegative, setNegative
  5543. */
  5544. void negate() throw();
  5545. /** Counts the total number of set bits in the array. */
  5546. int countNumberOfSetBits() const throw();
  5547. /** Looks for the index of the next set bit after a given starting point.
  5548. searches from startIndex (inclusive) upwards for the first set bit,
  5549. and returns its index.
  5550. If no set bits are found, it returns -1.
  5551. */
  5552. int findNextSetBit (int startIndex = 0) const throw();
  5553. /** Looks for the index of the next clear bit after a given starting point.
  5554. searches from startIndex (inclusive) upwards for the first clear bit,
  5555. and returns its index.
  5556. */
  5557. int findNextClearBit (int startIndex = 0) const throw();
  5558. /** Returns the index of the highest set bit in the array.
  5559. If the array is empty, this will return -1.
  5560. */
  5561. int getHighestBit() const throw();
  5562. /** Converts the array to a number string.
  5563. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5564. */
  5565. const String toString (const int base) const throw();
  5566. /** Converts a number string to an array.
  5567. Any non-valid characters will be ignored.
  5568. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5569. */
  5570. void parseString (const String& text,
  5571. const int base) throw();
  5572. /** Turns the array into a block of binary data.
  5573. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5574. of the array, and so on.
  5575. @see loadFromMemoryBlock
  5576. */
  5577. const MemoryBlock toMemoryBlock() const throw();
  5578. /** Copies a block of raw data onto this array.
  5579. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5580. of the array, and so on.
  5581. @see toMemoryBlock
  5582. */
  5583. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  5584. juce_UseDebuggingNewOperator
  5585. private:
  5586. void ensureSize (const int numVals) throw();
  5587. unsigned int* values;
  5588. int numValues, highestBit;
  5589. bool negative;
  5590. };
  5591. #endif // __JUCE_BITARRAY_JUCEHEADER__
  5592. /********* End of inlined file: juce_BitArray.h *********/
  5593. /**
  5594. A simple pseudo-random number generator.
  5595. */
  5596. class JUCE_API Random
  5597. {
  5598. public:
  5599. /** Creates a Random object based on a seed value.
  5600. For a given seed value, the subsequent numbers generated by this object
  5601. will be predictable, so a good idea is to set this value based
  5602. on the time, e.g.
  5603. new Random (Time::currentTimeMillis())
  5604. */
  5605. Random (const int64 seedValue) throw();
  5606. /** Destructor. */
  5607. ~Random() throw();
  5608. /** Returns the next random 32 bit integer.
  5609. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  5610. */
  5611. int nextInt() throw();
  5612. /** Returns the next random number, limited to a given range.
  5613. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  5614. */
  5615. int nextInt (const int maxValue) throw();
  5616. /** Returns the next 64-bit random number.
  5617. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  5618. */
  5619. int64 nextInt64() throw();
  5620. /** Returns the next random floating-point number.
  5621. @returns a random value in the range 0 to 1.0
  5622. */
  5623. float nextFloat() throw();
  5624. /** Returns the next random floating-point number.
  5625. @returns a random value in the range 0 to 1.0
  5626. */
  5627. double nextDouble() throw();
  5628. /** Returns the next random boolean value.
  5629. */
  5630. bool nextBool() throw();
  5631. /** Returns a BitArray containing a random number.
  5632. @returns a random value in the range 0 to (maximumValue - 1).
  5633. */
  5634. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  5635. /** Sets a range of bits in a BitArray to random values. */
  5636. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  5637. /** To avoid the overhead of having to create a new Random object whenever
  5638. you need a number, this is a shared application-wide object that
  5639. can be used.
  5640. It's not thread-safe though, so threads should use their own Random object.
  5641. */
  5642. static Random& getSystemRandom() throw();
  5643. /** Resets this Random object to a given seed value. */
  5644. void setSeed (const int64 newSeed) throw();
  5645. /** Reseeds this generator using a value generated from various semi-random system
  5646. properties like the current time, etc.
  5647. Because this function convolves the time with the last seed value, calling
  5648. it repeatedly will increase the randomness of the final result.
  5649. */
  5650. void setSeedRandomly();
  5651. juce_UseDebuggingNewOperator
  5652. private:
  5653. int64 seed;
  5654. };
  5655. #endif // __JUCE_RANDOM_JUCEHEADER__
  5656. /********* End of inlined file: juce_Random.h *********/
  5657. #endif
  5658. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5659. #endif
  5660. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5661. /********* Start of inlined file: juce_Singleton.h *********/
  5662. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5663. #define __JUCE_SINGLETON_JUCEHEADER__
  5664. /********* Start of inlined file: juce_ScopedLock.h *********/
  5665. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5666. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5667. /**
  5668. Automatically locks and unlocks a CriticalSection object.
  5669. Use one of these as a local variable to control access to a CriticalSection.
  5670. e.g. @code
  5671. CriticalSection myCriticalSection;
  5672. for (;;)
  5673. {
  5674. const ScopedLock myScopedLock (myCriticalSection);
  5675. // myCriticalSection is now locked
  5676. ...do some stuff...
  5677. // myCriticalSection gets unlocked here.
  5678. }
  5679. @endcode
  5680. @see CriticalSection, ScopedUnlock
  5681. */
  5682. class JUCE_API ScopedLock
  5683. {
  5684. public:
  5685. /** Creates a ScopedLock.
  5686. As soon as it is created, this will lock the CriticalSection, and
  5687. when the ScopedLock object is deleted, the CriticalSection will
  5688. be unlocked.
  5689. Make sure this object is created and deleted by the same thread,
  5690. otherwise there are no guarantees what will happen! Best just to use it
  5691. as a local stack object, rather than creating one with the new() operator.
  5692. */
  5693. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  5694. /** Destructor.
  5695. The CriticalSection will be unlocked when the destructor is called.
  5696. Make sure this object is created and deleted by the same thread,
  5697. otherwise there are no guarantees what will happen!
  5698. */
  5699. inline ~ScopedLock() throw() { lock_.exit(); }
  5700. private:
  5701. const CriticalSection& lock_;
  5702. ScopedLock (const ScopedLock&);
  5703. const ScopedLock& operator= (const ScopedLock&);
  5704. };
  5705. /**
  5706. Automatically unlocks and re-locks a CriticalSection object.
  5707. This is the reverse of a ScopedLock object - instead of locking the critical
  5708. section for the lifetime of this object, it unlocks it.
  5709. Make sure you don't try to unlock critical sections that aren't actually locked!
  5710. e.g. @code
  5711. CriticalSection myCriticalSection;
  5712. for (;;)
  5713. {
  5714. const ScopedLock myScopedLock (myCriticalSection);
  5715. // myCriticalSection is now locked
  5716. ... do some stuff with it locked ..
  5717. while (xyz)
  5718. {
  5719. ... do some stuff with it locked ..
  5720. const ScopedUnlock unlocker (myCriticalSection);
  5721. // myCriticalSection is now unlocked for the remainder of this block,
  5722. // and re-locked at the end.
  5723. ...do some stuff with it unlocked ...
  5724. }
  5725. // myCriticalSection gets unlocked here.
  5726. }
  5727. @endcode
  5728. @see CriticalSection, ScopedLock
  5729. */
  5730. class ScopedUnlock
  5731. {
  5732. public:
  5733. /** Creates a ScopedUnlock.
  5734. As soon as it is created, this will unlock the CriticalSection, and
  5735. when the ScopedLock object is deleted, the CriticalSection will
  5736. be re-locked.
  5737. Make sure this object is created and deleted by the same thread,
  5738. otherwise there are no guarantees what will happen! Best just to use it
  5739. as a local stack object, rather than creating one with the new() operator.
  5740. */
  5741. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  5742. /** Destructor.
  5743. The CriticalSection will be unlocked when the destructor is called.
  5744. Make sure this object is created and deleted by the same thread,
  5745. otherwise there are no guarantees what will happen!
  5746. */
  5747. inline ~ScopedUnlock() throw() { lock_.enter(); }
  5748. private:
  5749. const CriticalSection& lock_;
  5750. ScopedUnlock (const ScopedLock&);
  5751. const ScopedUnlock& operator= (const ScopedUnlock&);
  5752. };
  5753. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  5754. /********* End of inlined file: juce_ScopedLock.h *********/
  5755. /**
  5756. Macro to declare member variables and methods for a singleton class.
  5757. To use this, add the line juce_DeclareSingleton (MyClass, allowOnlyOneInstance)
  5758. to the class's definition.
  5759. If allowOnlyOneInstance == true, it won't allow the object to be created
  5760. more than once in the process's lifetime.
  5761. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  5762. implementation code.
  5763. Clients can then call the static MyClass::getInstance() to get a pointer to the
  5764. singleton, or MyClass::getInstanceWithoutCreating() which may return 0 if no instance
  5765. is currently extant
  5766. it's a very good idea to also add the call clearSingletonInstance() to the
  5767. destructor of the class, in case it is deleted by other means than deleteInstance()
  5768. e.g. @code
  5769. class MySingleton
  5770. {
  5771. public:
  5772. MySingleton()
  5773. {
  5774. }
  5775. ~MySingleton()
  5776. {
  5777. // this ensures that no dangling pointers are left when the
  5778. // singleton is deleted.
  5779. clearSingletonInstance();
  5780. }
  5781. juce_DeclareSingleton (MySingleton, false)
  5782. };
  5783. juce_ImplementSingleton (MySingleton)
  5784. // example of usage:
  5785. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  5786. ...
  5787. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  5788. @endcode
  5789. If you know that your object will only be created and deleted by a single thread, you
  5790. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  5791. of this one.
  5792. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  5793. */
  5794. #define juce_DeclareSingleton(classname, allowOnlyOneInstance) \
  5795. \
  5796. static classname* _singletonInstance; \
  5797. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  5798. \
  5799. static classname* getInstance() \
  5800. { \
  5801. if (_singletonInstance == 0) \
  5802. {\
  5803. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5804. \
  5805. if (_singletonInstance == 0) \
  5806. { \
  5807. static bool alreadyInside = false; \
  5808. static bool createdOnceAlready = false; \
  5809. \
  5810. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5811. jassert (! problem); \
  5812. if (! problem) \
  5813. { \
  5814. createdOnceAlready = true; \
  5815. alreadyInside = true; \
  5816. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5817. alreadyInside = false; \
  5818. \
  5819. _singletonInstance = newObject; \
  5820. } \
  5821. } \
  5822. } \
  5823. \
  5824. return _singletonInstance; \
  5825. } \
  5826. \
  5827. static inline classname* getInstanceWithoutCreating() throw() \
  5828. { \
  5829. return _singletonInstance; \
  5830. } \
  5831. \
  5832. static void deleteInstance() \
  5833. { \
  5834. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  5835. if (_singletonInstance != 0) \
  5836. { \
  5837. classname* const old = _singletonInstance; \
  5838. _singletonInstance = 0; \
  5839. delete old; \
  5840. } \
  5841. } \
  5842. \
  5843. void clearSingletonInstance() throw() \
  5844. { \
  5845. if (_singletonInstance == this) \
  5846. _singletonInstance = 0; \
  5847. }
  5848. /** This is a counterpart to the juce_DeclareSingleton macro.
  5849. After adding the juce_DeclareSingleton to the class definition, this macro has
  5850. to be used in the cpp file.
  5851. */
  5852. #define juce_ImplementSingleton(classname) \
  5853. \
  5854. classname* classname::_singletonInstance = 0; \
  5855. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  5856. /**
  5857. Macro to declare member variables and methods for a singleton class.
  5858. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  5859. section to make access to it thread-safe. If you know that your object will
  5860. only ever be created or deleted by a single thread, then this is a
  5861. more efficient version to use.
  5862. See the documentation for juce_DeclareSingleton for more information about
  5863. how to use it, the only difference being that you have to use
  5864. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5865. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  5866. */
  5867. #define juce_DeclareSingleton_SingleThreaded(classname, allowOnlyOneInstance) \
  5868. \
  5869. static classname* _singletonInstance; \
  5870. \
  5871. static classname* getInstance() \
  5872. { \
  5873. if (_singletonInstance == 0) \
  5874. { \
  5875. static bool alreadyInside = false; \
  5876. static bool createdOnceAlready = false; \
  5877. \
  5878. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  5879. jassert (! problem); \
  5880. if (! problem) \
  5881. { \
  5882. createdOnceAlready = true; \
  5883. alreadyInside = true; \
  5884. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  5885. alreadyInside = false; \
  5886. \
  5887. _singletonInstance = newObject; \
  5888. } \
  5889. } \
  5890. \
  5891. return _singletonInstance; \
  5892. } \
  5893. \
  5894. static inline classname* getInstanceWithoutCreating() throw() \
  5895. { \
  5896. return _singletonInstance; \
  5897. } \
  5898. \
  5899. static void deleteInstance() \
  5900. { \
  5901. if (_singletonInstance != 0) \
  5902. { \
  5903. classname* const old = _singletonInstance; \
  5904. _singletonInstance = 0; \
  5905. delete old; \
  5906. } \
  5907. } \
  5908. \
  5909. void clearSingletonInstance() throw() \
  5910. { \
  5911. if (_singletonInstance == this) \
  5912. _singletonInstance = 0; \
  5913. }
  5914. /**
  5915. Macro to declare member variables and methods for a singleton class.
  5916. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  5917. for recursion or repeated instantiation. It's intended for use as a lightweight
  5918. version of a singleton, where you're using it in very straightforward
  5919. circumstances and don't need the extra checking.
  5920. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  5921. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  5922. See the documentation for juce_DeclareSingleton for more information about
  5923. how to use it, the only difference being that you have to use
  5924. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  5925. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  5926. */
  5927. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  5928. \
  5929. static classname* _singletonInstance; \
  5930. \
  5931. static classname* getInstance() \
  5932. { \
  5933. if (_singletonInstance == 0) \
  5934. _singletonInstance = new classname(); \
  5935. \
  5936. return _singletonInstance; \
  5937. } \
  5938. \
  5939. static inline classname* getInstanceWithoutCreating() throw() \
  5940. { \
  5941. return _singletonInstance; \
  5942. } \
  5943. \
  5944. static void deleteInstance() \
  5945. { \
  5946. if (_singletonInstance != 0) \
  5947. { \
  5948. classname* const old = _singletonInstance; \
  5949. _singletonInstance = 0; \
  5950. delete old; \
  5951. } \
  5952. } \
  5953. \
  5954. void clearSingletonInstance() throw() \
  5955. { \
  5956. if (_singletonInstance == this) \
  5957. _singletonInstance = 0; \
  5958. }
  5959. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  5960. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  5961. to the class definition, this macro has to be used somewhere in the cpp file.
  5962. */
  5963. #define juce_ImplementSingleton_SingleThreaded(classname) \
  5964. \
  5965. classname* classname::_singletonInstance = 0;
  5966. #endif // __JUCE_SINGLETON_JUCEHEADER__
  5967. /********* End of inlined file: juce_Singleton.h *********/
  5968. #endif
  5969. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  5970. #endif
  5971. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5972. /********* Start of inlined file: juce_SystemStats.h *********/
  5973. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  5974. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  5975. /**
  5976. Contains methods for finding out about the current hardware and OS configuration.
  5977. */
  5978. class JUCE_API SystemStats
  5979. {
  5980. public:
  5981. /** Returns the current version of JUCE,
  5982. (just in case you didn't already know at compile-time.)
  5983. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  5984. */
  5985. static const String getJUCEVersion() throw();
  5986. /** The set of possible results of the getOperatingSystemType() method.
  5987. */
  5988. enum OperatingSystemType
  5989. {
  5990. UnknownOS = 0,
  5991. MacOSX = 0x1000,
  5992. Linux = 0x2000,
  5993. Win95 = 0x4001,
  5994. Win98 = 0x4002,
  5995. WinNT351 = 0x4103,
  5996. WinNT40 = 0x4104,
  5997. Win2000 = 0x4105,
  5998. WinXP = 0x4106,
  5999. WinVista = 0x4107,
  6000. Windows = 0x4000, /**< To test whether any version of Windows is running,
  6001. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  6002. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  6003. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  6004. };
  6005. /** Returns the type of operating system we're running on.
  6006. @returns one of the values from the OperatingSystemType enum.
  6007. @see getOperatingSystemName
  6008. */
  6009. static OperatingSystemType getOperatingSystemType() throw();
  6010. /** Returns the name of the type of operating system we're running on.
  6011. @returns a string describing the OS type.
  6012. @see getOperatingSystemType
  6013. */
  6014. static const String getOperatingSystemName() throw();
  6015. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  6016. */
  6017. static bool isOperatingSystem64Bit() throw();
  6018. // CPU and memory information..
  6019. /** Returns the approximate CPU speed.
  6020. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  6021. what year you're reading this...)
  6022. */
  6023. static int getCpuSpeedInMegaherz() throw();
  6024. /** Returns a string to indicate the CPU vendor.
  6025. Might not be known on some systems.
  6026. */
  6027. static const String getCpuVendor() throw();
  6028. /** Checks whether Intel MMX instructions are available. */
  6029. static bool hasMMX() throw();
  6030. /** Checks whether Intel SSE instructions are available. */
  6031. static bool hasSSE() throw();
  6032. /** Checks whether Intel SSE2 instructions are available. */
  6033. static bool hasSSE2() throw();
  6034. /** Checks whether AMD 3DNOW instructions are available. */
  6035. static bool has3DNow() throw();
  6036. /** Returns the number of CPUs.
  6037. */
  6038. static int getNumCpus() throw();
  6039. /** Returns a clock-cycle tick counter, if available.
  6040. If the machine can do it, this will return a tick-count
  6041. where each tick is one cpu clock cycle - used for profiling
  6042. code.
  6043. @returns the tick count, or zero if not available.
  6044. */
  6045. static int64 getClockCycleCounter() throw();
  6046. /** Finds out how much RAM is in the machine.
  6047. @returns the approximate number of megabytes of memory, or zero if
  6048. something goes wrong when finding out.
  6049. */
  6050. static int getMemorySizeInMegabytes() throw();
  6051. /** Returns the system page-size.
  6052. This is only used by programmers with beards.
  6053. */
  6054. static int getPageSize() throw();
  6055. /** Returns a list of MAC addresses found on this machine.
  6056. @param addresses an array into which the MAC addresses should be copied
  6057. @param maxNum the number of elements in this array
  6058. @param littleEndian the endianness of the numbers to return. Note that
  6059. the default values of this parameter are different on
  6060. Mac/PC to avoid breaking old software that was written
  6061. before this parameter was added (when the two systems
  6062. defaulted to using different endiannesses). In newer
  6063. software you probably want to specify an explicit value
  6064. for this.
  6065. @returns the number of MAC addresses that were found
  6066. */
  6067. static int getMACAddresses (int64* addresses, int maxNum,
  6068. #if JUCE_MAC
  6069. const bool littleEndian = true) throw();
  6070. #else
  6071. const bool littleEndian = false) throw();
  6072. #endif
  6073. // not-for-public-use platform-specific method gets called at startup to initialise things.
  6074. static void initialiseStats() throw();
  6075. };
  6076. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  6077. /********* End of inlined file: juce_SystemStats.h *********/
  6078. #endif
  6079. #ifndef __JUCE_TIME_JUCEHEADER__
  6080. #endif
  6081. #ifndef __JUCE_ARRAY_JUCEHEADER__
  6082. #endif
  6083. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6084. #endif
  6085. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  6086. #endif
  6087. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  6088. #endif
  6089. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6090. #endif
  6091. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  6092. #endif
  6093. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6094. /********* Start of inlined file: juce_PropertySet.h *********/
  6095. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6096. #define __JUCE_PROPERTYSET_JUCEHEADER__
  6097. /********* Start of inlined file: juce_StringPairArray.h *********/
  6098. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6099. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6100. /**
  6101. A container for holding a set of strings which are keyed by another string.
  6102. @see StringArray
  6103. */
  6104. class JUCE_API StringPairArray
  6105. {
  6106. public:
  6107. /** Creates an empty array */
  6108. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  6109. /** Creates a copy of another array */
  6110. StringPairArray (const StringPairArray& other) throw();
  6111. /** Destructor. */
  6112. ~StringPairArray() throw();
  6113. /** Copies the contents of another string array into this one */
  6114. const StringPairArray& operator= (const StringPairArray& other) throw();
  6115. /** Compares two arrays.
  6116. Comparisons are case-sensitive.
  6117. @returns true only if the other array contains exactly the same strings with the same keys
  6118. */
  6119. bool operator== (const StringPairArray& other) const throw();
  6120. /** Compares two arrays.
  6121. Comparisons are case-sensitive.
  6122. @returns false if the other array contains exactly the same strings with the same keys
  6123. */
  6124. bool operator!= (const StringPairArray& other) const throw();
  6125. /** Finds the value corresponding to a key string.
  6126. If no such key is found, this will just return an empty string. To check whether
  6127. a given key actually exists (because it might actually be paired with an empty string), use
  6128. the getAllKeys() method to obtain a list.
  6129. Obviously the reference returned shouldn't be stored for later use, as the
  6130. string it refers to may disappear when the array changes.
  6131. @see getValue
  6132. */
  6133. const String& operator[] (const String& key) const throw();
  6134. /** Finds the value corresponding to a key string.
  6135. If no such key is found, this will just return the value provided as a default.
  6136. @see operator[]
  6137. */
  6138. const String getValue (const String& key, const String& defaultReturnValue) const;
  6139. /** Returns a list of all keys in the array. */
  6140. const StringArray& getAllKeys() const throw() { return keys; }
  6141. /** Returns a list of all values in the array. */
  6142. const StringArray& getAllValues() const throw() { return values; }
  6143. /** Returns the number of strings in the array */
  6144. inline int size() const throw() { return keys.size(); };
  6145. /** Adds or amends a key/value pair.
  6146. If a value already exists with this key, its value will be overwritten,
  6147. otherwise the key/value pair will be added to the array.
  6148. */
  6149. void set (const String& key,
  6150. const String& value) throw();
  6151. /** Adds the items from another array to this one.
  6152. This is equivalent to using set() to add each of the pairs from the other array.
  6153. */
  6154. void addArray (const StringPairArray& other);
  6155. /** Removes all elements from the array. */
  6156. void clear() throw();
  6157. /** Removes a string from the array based on its key.
  6158. If the key isn't found, nothing will happen.
  6159. */
  6160. void remove (const String& key) throw();
  6161. /** Removes a string from the array based on its index.
  6162. If the index is out-of-range, no action will be taken.
  6163. */
  6164. void remove (const int index) throw();
  6165. /** Reduces the amount of storage being used by the array.
  6166. Arrays typically allocate slightly more storage than they need, and after
  6167. removing elements, they may have quite a lot of unused space allocated.
  6168. This method will reduce the amount of allocated storage to a minimum.
  6169. */
  6170. void minimiseStorageOverheads() throw();
  6171. juce_UseDebuggingNewOperator
  6172. private:
  6173. StringArray keys, values;
  6174. bool ignoreCase;
  6175. };
  6176. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6177. /********* End of inlined file: juce_StringPairArray.h *********/
  6178. /********* Start of inlined file: juce_XmlElement.h *********/
  6179. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  6180. #define __JUCE_XMLELEMENT_JUCEHEADER__
  6181. /********* Start of inlined file: juce_OutputStream.h *********/
  6182. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6183. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6184. /********* Start of inlined file: juce_InputStream.h *********/
  6185. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6186. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6187. /** The base class for streams that read data.
  6188. Input and output streams are used throughout the library - subclasses can override
  6189. some or all of the virtual functions to implement their behaviour.
  6190. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6191. */
  6192. class JUCE_API InputStream
  6193. {
  6194. public:
  6195. /** Destructor. */
  6196. virtual ~InputStream() {}
  6197. /** Returns the total number of bytes available for reading in this stream.
  6198. Note that this is the number of bytes available from the start of the
  6199. stream, not from the current position.
  6200. If the size of the stream isn't actually known, this may return -1.
  6201. */
  6202. virtual int64 getTotalLength() = 0;
  6203. /** Returns true if the stream has no more data to read. */
  6204. virtual bool isExhausted() = 0;
  6205. /** Reads a set of bytes from the stream into a memory buffer.
  6206. This is the only read method that subclasses actually need to implement, as the
  6207. InputStream base class implements the other read methods in terms of this one (although
  6208. it's often more efficient for subclasses to implement them directly).
  6209. @param destBuffer the destination buffer for the data
  6210. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6211. memory block passed in is big enough to contain this
  6212. many bytes.
  6213. @returns the actual number of bytes that were read, which may be less than
  6214. maxBytesToRead if the stream is exhausted before it gets that far
  6215. */
  6216. virtual int read (void* destBuffer,
  6217. int maxBytesToRead) = 0;
  6218. /** Reads a byte from the stream.
  6219. If the stream is exhausted, this will return zero.
  6220. @see OutputStream::writeByte
  6221. */
  6222. virtual char readByte();
  6223. /** Reads a boolean from the stream.
  6224. The bool is encoded as a single byte - 1 for true, 0 for false.
  6225. If the stream is exhausted, this will return false.
  6226. @see OutputStream::writeBool
  6227. */
  6228. virtual bool readBool();
  6229. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6230. If the next two bytes read are byte1 and byte2, this returns
  6231. (byte1 | (byte2 << 8)).
  6232. If the stream is exhausted partway through reading the bytes, this will return zero.
  6233. @see OutputStream::writeShort, readShortBigEndian
  6234. */
  6235. virtual short readShort();
  6236. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6237. If the next two bytes read are byte1 and byte2, this returns
  6238. (byte2 | (byte1 << 8)).
  6239. If the stream is exhausted partway through reading the bytes, this will return zero.
  6240. @see OutputStream::writeShortBigEndian, readShort
  6241. */
  6242. virtual short readShortBigEndian();
  6243. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6244. If the next four bytes are byte1 to byte4, this returns
  6245. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6246. If the stream is exhausted partway through reading the bytes, this will return zero.
  6247. @see OutputStream::writeInt, readIntBigEndian
  6248. */
  6249. virtual int readInt();
  6250. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6251. If the next four bytes are byte1 to byte4, this returns
  6252. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6253. If the stream is exhausted partway through reading the bytes, this will return zero.
  6254. @see OutputStream::writeIntBigEndian, readInt
  6255. */
  6256. virtual int readIntBigEndian();
  6257. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6258. If the next eight bytes are byte1 to byte8, this returns
  6259. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6260. If the stream is exhausted partway through reading the bytes, this will return zero.
  6261. @see OutputStream::writeInt64, readInt64BigEndian
  6262. */
  6263. virtual int64 readInt64();
  6264. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6265. If the next eight bytes are byte1 to byte8, this returns
  6266. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6267. If the stream is exhausted partway through reading the bytes, this will return zero.
  6268. @see OutputStream::writeInt64BigEndian, readInt64
  6269. */
  6270. virtual int64 readInt64BigEndian();
  6271. /** Reads four bytes as a 32-bit floating point value.
  6272. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6273. If the stream is exhausted partway through reading the bytes, this will return zero.
  6274. @see OutputStream::writeFloat, readDouble
  6275. */
  6276. virtual float readFloat();
  6277. /** Reads four bytes as a 32-bit floating point value.
  6278. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6279. If the stream is exhausted partway through reading the bytes, this will return zero.
  6280. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6281. */
  6282. virtual float readFloatBigEndian();
  6283. /** Reads eight bytes as a 64-bit floating point value.
  6284. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6285. If the stream is exhausted partway through reading the bytes, this will return zero.
  6286. @see OutputStream::writeDouble, readFloat
  6287. */
  6288. virtual double readDouble();
  6289. /** Reads eight bytes as a 64-bit floating point value.
  6290. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6291. If the stream is exhausted partway through reading the bytes, this will return zero.
  6292. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6293. */
  6294. virtual double readDoubleBigEndian();
  6295. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6296. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6297. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6298. @see OutputStream::writeCompressedInt()
  6299. */
  6300. virtual int readCompressedInt();
  6301. /** Reads a string from the stream, up to the next linefeed or carriage return.
  6302. The stream is treated as 8-bit characters encoded with the system's default encoding,
  6303. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  6304. After this call, the stream's position will be left pointing to the character
  6305. following the line-feed, but the linefeeds aren't included in the string that
  6306. is returned.
  6307. */
  6308. virtual const String readNextLine();
  6309. /** Reads a zero-terminated string from the stream.
  6310. This will read characters from the stream until it hits a zero character or
  6311. end-of-stream.
  6312. @see OutputStream::writeString, readEntireStreamAsString
  6313. */
  6314. virtual const String readString();
  6315. /** Tries to read the whole stream and turn it into a string.
  6316. This will read from the stream's current position until the end-of-stream, and
  6317. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6318. */
  6319. virtual const String readEntireStreamAsString();
  6320. /** Reads from the stream and appends the data to a MemoryBlock.
  6321. @param destBlock the block to append the data onto
  6322. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6323. of bytes that will be read - if it's negative, data
  6324. will be read until the stream is exhausted.
  6325. @returns the number of bytes that were added to the memory block
  6326. */
  6327. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6328. int maxNumBytesToRead = -1);
  6329. /** Returns the offset of the next byte that will be read from the stream.
  6330. @see setPosition
  6331. */
  6332. virtual int64 getPosition() = 0;
  6333. /** Tries to move the current read position of the stream.
  6334. The position is an absolute number of bytes from the stream's start.
  6335. Some streams might not be able to do this, in which case they should do
  6336. nothing and return false. Others might be able to manage it by resetting
  6337. themselves and skipping to the correct position, although this is
  6338. obviously a bit slow.
  6339. @returns true if the stream manages to reposition itself correctly
  6340. @see getPosition
  6341. */
  6342. virtual bool setPosition (int64 newPosition) = 0;
  6343. /** Reads and discards a number of bytes from the stream.
  6344. Some input streams might implement this efficiently, but the base
  6345. class will just keep reading data until the requisite number of bytes
  6346. have been done.
  6347. */
  6348. virtual void skipNextBytes (int64 numBytesToSkip);
  6349. juce_UseDebuggingNewOperator
  6350. protected:
  6351. InputStream() throw() {}
  6352. };
  6353. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6354. /********* End of inlined file: juce_InputStream.h *********/
  6355. /**
  6356. The base class for streams that write data to some kind of destination.
  6357. Input and output streams are used throughout the library - subclasses can override
  6358. some or all of the virtual functions to implement their behaviour.
  6359. @see InputStream, MemoryOutputStream, FileOutputStream
  6360. */
  6361. class JUCE_API OutputStream
  6362. {
  6363. public:
  6364. /** Destructor.
  6365. Some subclasses might want to do things like call flush() during their
  6366. destructors.
  6367. */
  6368. virtual ~OutputStream();
  6369. /** If the stream is using a buffer, this will ensure it gets written
  6370. out to the destination. */
  6371. virtual void flush() = 0;
  6372. /** Tries to move the stream's output position.
  6373. Not all streams will be able to seek to a new position - this will return
  6374. false if it fails to work.
  6375. @see getPosition
  6376. */
  6377. virtual bool setPosition (int64 newPosition) = 0;
  6378. /** Returns the stream's current position.
  6379. @see setPosition
  6380. */
  6381. virtual int64 getPosition() = 0;
  6382. /** Writes a block of data to the stream.
  6383. When creating a subclass of OutputStream, this is the only write method
  6384. that needs to be overloaded - the base class has methods for writing other
  6385. types of data which use this to do the work.
  6386. @returns false if the write operation fails for some reason
  6387. */
  6388. virtual bool write (const void* dataToWrite,
  6389. int howManyBytes) = 0;
  6390. /** Writes a single byte to the stream.
  6391. @see InputStream::readByte
  6392. */
  6393. virtual void writeByte (char byte);
  6394. /** Writes a boolean to the stream.
  6395. This is encoded as a byte - either 1 or 0.
  6396. @see InputStream::readBool
  6397. */
  6398. virtual void writeBool (bool boolValue);
  6399. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6400. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6401. @see InputStream::readShort
  6402. */
  6403. virtual void writeShort (short value);
  6404. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6405. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6406. @see InputStream::readShortBigEndian
  6407. */
  6408. virtual void writeShortBigEndian (short value);
  6409. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6410. @see InputStream::readInt
  6411. */
  6412. virtual void writeInt (int value);
  6413. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6414. @see InputStream::readIntBigEndian
  6415. */
  6416. virtual void writeIntBigEndian (int value);
  6417. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6418. @see InputStream::readInt64
  6419. */
  6420. virtual void writeInt64 (int64 value);
  6421. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6422. @see InputStream::readInt64BigEndian
  6423. */
  6424. virtual void writeInt64BigEndian (int64 value);
  6425. /** Writes a 32-bit floating point value to the stream.
  6426. The binary 32-bit encoding of the float is written as a little-endian int.
  6427. @see InputStream::readFloat
  6428. */
  6429. virtual void writeFloat (float value);
  6430. /** Writes a 32-bit floating point value to the stream.
  6431. The binary 32-bit encoding of the float is written as a big-endian int.
  6432. @see InputStream::readFloatBigEndian
  6433. */
  6434. virtual void writeFloatBigEndian (float value);
  6435. /** Writes a 64-bit floating point value to the stream.
  6436. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6437. @see InputStream::readDouble
  6438. */
  6439. virtual void writeDouble (double value);
  6440. /** Writes a 64-bit floating point value to the stream.
  6441. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6442. @see InputStream::readDoubleBigEndian
  6443. */
  6444. virtual void writeDoubleBigEndian (double value);
  6445. /** Writes a condensed encoding of a 32-bit integer.
  6446. If you're storing a lot of integers which are unlikely to have very large values,
  6447. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6448. under 0xffff only 3 bytes, etc.
  6449. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6450. @see InputStream::readCompressedInt
  6451. */
  6452. virtual void writeCompressedInt (int value);
  6453. /** Stores a string in the stream.
  6454. This isn't the method to use if you're trying to append text to the end of a
  6455. text-file! It's intended for storing a string for later retrieval
  6456. by InputStream::readString.
  6457. For appending text to a file, instead use writeText, printf, or operator<<
  6458. @see InputStream::readString, writeText, printf, operator<<
  6459. */
  6460. virtual void writeString (const String& text);
  6461. /** Writes a string of text to the stream.
  6462. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6463. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6464. should only be done at the start of a file).
  6465. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6466. */
  6467. virtual void writeText (const String& text,
  6468. const bool asUnicode,
  6469. const bool writeUnicodeHeaderBytes);
  6470. /** Writes a string of text to the stream.
  6471. @see writeText
  6472. */
  6473. virtual void printf (const char* format, ...);
  6474. /** Reads data from an input stream and writes it to this stream.
  6475. @param source the stream to read from
  6476. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6477. less than zero, it will keep reading until the input
  6478. is exhausted)
  6479. */
  6480. virtual int writeFromInputStream (InputStream& source,
  6481. int maxNumBytesToWrite);
  6482. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6483. virtual OutputStream& operator<< (const int number);
  6484. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6485. virtual OutputStream& operator<< (const double number);
  6486. /** Writes a character to the stream. */
  6487. virtual OutputStream& operator<< (const char character);
  6488. /** Writes a null-terminated string to the stream. */
  6489. virtual OutputStream& operator<< (const char* const text);
  6490. /** Writes a null-terminated unicode text string to the stream, converting it
  6491. to 8-bit characters in the default system encoding. */
  6492. virtual OutputStream& operator<< (const juce_wchar* const text);
  6493. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  6494. virtual OutputStream& operator<< (const String& text);
  6495. juce_UseDebuggingNewOperator
  6496. protected:
  6497. OutputStream() throw();
  6498. };
  6499. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6500. /********* End of inlined file: juce_OutputStream.h *********/
  6501. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6502. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6503. will be the name of a pointer to each child element.
  6504. E.g. @code
  6505. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6506. forEachXmlChildElement (*myParentXml, child)
  6507. {
  6508. if (child->hasTagName ("FOO"))
  6509. doSomethingWithXmlElement (child);
  6510. }
  6511. @endcode
  6512. @see forEachXmlChildElementWithTagName
  6513. */
  6514. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6515. \
  6516. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6517. childElementVariableName != 0; \
  6518. childElementVariableName = childElementVariableName->getNextElement())
  6519. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6520. which have a specified tag.
  6521. This does the same job as the forEachXmlChildElement macro, but only for those
  6522. elements that have a particular tag name.
  6523. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6524. will be the name of a pointer to each child element. The requiredTagName is the
  6525. tag name to match.
  6526. E.g. @code
  6527. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6528. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6529. {
  6530. // the child object is now guaranteed to be a <MYTAG> element..
  6531. doSomethingWithMYTAGElement (child);
  6532. }
  6533. @endcode
  6534. @see forEachXmlChildElement
  6535. */
  6536. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6537. \
  6538. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6539. childElementVariableName != 0; \
  6540. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6541. /** Used to build a tree of elements representing an XML document.
  6542. An XML document can be parsed into a tree of XmlElements, each of which
  6543. represents an XML tag structure, and which may itself contain other
  6544. nested elements.
  6545. An XmlElement can also be converted back into a text document, and has
  6546. lots of useful methods for manipulating its attributes and sub-elements,
  6547. so XmlElements can actually be used as a handy general-purpose data
  6548. structure.
  6549. Here's an example of parsing some elements: @code
  6550. // check we're looking at the right kind of document..
  6551. if (myElement->hasTagName ("ANIMALS"))
  6552. {
  6553. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6554. forEachXmlChildElement (*myElement, e)
  6555. {
  6556. if (e->hasTagName ("GIRAFFE"))
  6557. {
  6558. // found a giraffe, so use some of its attributes..
  6559. String giraffeName = e->getStringAttribute ("name");
  6560. int giraffeAge = e->getIntAttribute ("age");
  6561. bool isFriendly = e->getBoolAttribute ("friendly");
  6562. }
  6563. }
  6564. }
  6565. @endcode
  6566. And here's an example of how to create an XML document from scratch: @code
  6567. // create an outer node called "ANIMALS"
  6568. XmlElement animalsList ("ANIMALS");
  6569. for (int i = 0; i < numAnimals; ++i)
  6570. {
  6571. // create an inner element..
  6572. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6573. giraffe->setAttribute ("name", "nigel");
  6574. giraffe->setAttribute ("age", 10);
  6575. giraffe->setAttribute ("friendly", true);
  6576. // ..and add our new element to the parent node
  6577. animalsList.addChildElement (giraffe);
  6578. }
  6579. // now we can turn the whole thing into a text document..
  6580. String myXmlDoc = animalsList.createDocument (String::empty);
  6581. @endcode
  6582. @see XmlDocument
  6583. */
  6584. class JUCE_API XmlElement
  6585. {
  6586. public:
  6587. /** Creates an XmlElement with this tag name. */
  6588. XmlElement (const String& tagName) throw();
  6589. /** Creates a (deep) copy of another element. */
  6590. XmlElement (const XmlElement& other) throw();
  6591. /** Creates a (deep) copy of another element. */
  6592. const XmlElement& operator= (const XmlElement& other) throw();
  6593. /** Deleting an XmlElement will also delete all its child elements. */
  6594. ~XmlElement() throw();
  6595. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6596. The elements are only considered equivalent if they contain the same attiributes
  6597. with the same values, and have the same sub-nodes.
  6598. @param other the other element to compare to
  6599. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6600. same attributes in a different order will be
  6601. considered the same; if false, the attributes must
  6602. be in the same order as well
  6603. */
  6604. bool isEquivalentTo (const XmlElement* const other,
  6605. const bool ignoreOrderOfAttributes) const throw();
  6606. /** Returns an XML text document that represents this element.
  6607. The string returned can be parsed to recreate the same XmlElement that
  6608. was used to create it.
  6609. @param dtdToUse the DTD to add to the document
  6610. @param allOnOneLine if true, this means that the document will not contain any
  6611. linefeeds, so it'll be smaller but not very easy to read.
  6612. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6613. document
  6614. @param encodingType the character encoding format string to put into the xml
  6615. header
  6616. @param lineWrapLength the line length that will be used before items get placed on
  6617. a new line. This isn't an absolute maximum length, it just
  6618. determines how lists of attributes get broken up
  6619. @see writeToFile
  6620. */
  6621. const String createDocument (const String& dtdToUse,
  6622. const bool allOnOneLine = false,
  6623. const bool includeXmlHeader = true,
  6624. const tchar* const encodingType = JUCE_T("UTF-8"),
  6625. const int lineWrapLength = 60) const throw();
  6626. /** Writes the element to a file as an XML document.
  6627. To improve safety in case something goes wrong while writing the file, this
  6628. will actually write the document to a new temporary file in the same
  6629. directory as the destination file, and if this succeeds, it will rename this
  6630. new file as the destination file (overwriting any existing file that was there).
  6631. @param destinationFile the file to write to. If this already exists, it will be
  6632. overwritten.
  6633. @param dtdToUse the DTD to add to the document
  6634. @param encodingType the character encoding format string to put into the xml
  6635. header
  6636. @param lineWrapLength the line length that will be used before items get placed on
  6637. a new line. This isn't an absolute maximum length, it just
  6638. determines how lists of attributes get broken up
  6639. @returns true if the file is written successfully; false if something goes wrong
  6640. in the process
  6641. @see createDocument
  6642. */
  6643. bool writeToFile (const File& destinationFile,
  6644. const String& dtdToUse,
  6645. const tchar* const encodingType = JUCE_T("UTF-8"),
  6646. const int lineWrapLength = 60) const throw();
  6647. /** Returns this element's tag type name.
  6648. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  6649. "MOOSE".
  6650. @see hasTagName
  6651. */
  6652. inline const String& getTagName() const throw() { return tagName; }
  6653. /** Tests whether this element has a particular tag name.
  6654. @param possibleTagName the tag name you're comparing it with
  6655. @see getTagName
  6656. */
  6657. bool hasTagName (const tchar* const possibleTagName) const throw();
  6658. /** Returns the number of XML attributes this element contains.
  6659. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  6660. return 2.
  6661. */
  6662. int getNumAttributes() const throw();
  6663. /** Returns the name of one of the elements attributes.
  6664. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6665. getAttributeName(1) would return "antlers".
  6666. @see getAttributeValue, getStringAttribute
  6667. */
  6668. const String& getAttributeName (const int attributeIndex) const throw();
  6669. /** Returns the value of one of the elements attributes.
  6670. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6671. getAttributeName(1) would return "2".
  6672. @see getAttributeName, getStringAttribute
  6673. */
  6674. const String& getAttributeValue (const int attributeIndex) const throw();
  6675. // Attribute-handling methods..
  6676. /** Checks whether the element contains an attribute with a certain name. */
  6677. bool hasAttribute (const tchar* const attributeName) const throw();
  6678. /** Returns the value of a named attribute.
  6679. @param attributeName the name of the attribute to look up
  6680. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6681. with this name
  6682. */
  6683. const String getStringAttribute (const tchar* const attributeName,
  6684. const tchar* const defaultReturnValue = 0) const throw();
  6685. /** Compares the value of a named attribute with a value passed-in.
  6686. @param attributeName the name of the attribute to look up
  6687. @param stringToCompareAgainst the value to compare it with
  6688. @param ignoreCase whether the comparison should be case-insensitive
  6689. @returns true if the value of the attribute is the same as the string passed-in;
  6690. false if it's different (or if no such attribute exists)
  6691. */
  6692. bool compareAttribute (const tchar* const attributeName,
  6693. const tchar* const stringToCompareAgainst,
  6694. const bool ignoreCase = false) const throw();
  6695. /** Returns the value of a named attribute as an integer.
  6696. This will try to find the attribute and convert it to an integer (using
  6697. the String::getIntValue() method).
  6698. @param attributeName the name of the attribute to look up
  6699. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6700. with this name
  6701. @see setAttribute (const tchar* const, int)
  6702. */
  6703. int getIntAttribute (const tchar* const attributeName,
  6704. const int defaultReturnValue = 0) const throw();
  6705. /** Returns the value of a named attribute as floating-point.
  6706. This will try to find the attribute and convert it to an integer (using
  6707. the String::getDoubleValue() method).
  6708. @param attributeName the name of the attribute to look up
  6709. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6710. with this name
  6711. @see setAttribute (const tchar* const, double)
  6712. */
  6713. double getDoubleAttribute (const tchar* const attributeName,
  6714. const double defaultReturnValue = 0.0) const throw();
  6715. /** Returns the value of a named attribute as a boolean.
  6716. This will try to find the attribute and interpret it as a boolean. To do this,
  6717. it'll return true if the value is "1", "true", "y", etc, or false for other
  6718. values.
  6719. @param attributeName the name of the attribute to look up
  6720. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6721. with this name
  6722. */
  6723. bool getBoolAttribute (const tchar* const attributeName,
  6724. const bool defaultReturnValue = false) const throw();
  6725. /** Adds a named attribute to the element.
  6726. If the element already contains an attribute with this name, it's value will
  6727. be updated to the new value. If there's no such attribute yet, a new one will
  6728. be added.
  6729. Note that there are other setAttribute() methods that take integers,
  6730. doubles, etc. to make it easy to store numbers.
  6731. @param attributeName the name of the attribute to set
  6732. @param newValue the value to set it to
  6733. @see removeAttribute
  6734. */
  6735. void setAttribute (const tchar* const attributeName,
  6736. const String& newValue) throw();
  6737. /** Adds a named attribute to the element.
  6738. If the element already contains an attribute with this name, it's value will
  6739. be updated to the new value. If there's no such attribute yet, a new one will
  6740. be added.
  6741. Note that there are other setAttribute() methods that take integers,
  6742. doubles, etc. to make it easy to store numbers.
  6743. @param attributeName the name of the attribute to set
  6744. @param newValue the value to set it to
  6745. */
  6746. void setAttribute (const tchar* const attributeName,
  6747. const tchar* const newValue) throw();
  6748. /** Adds a named attribute to the element, setting it to an integer value.
  6749. If the element already contains an attribute with this name, it's value will
  6750. be updated to the new value. If there's no such attribute yet, a new one will
  6751. be added.
  6752. Note that there are other setAttribute() methods that take integers,
  6753. doubles, etc. to make it easy to store numbers.
  6754. @param attributeName the name of the attribute to set
  6755. @param newValue the value to set it to
  6756. */
  6757. void setAttribute (const tchar* const attributeName,
  6758. const int newValue) throw();
  6759. /** Adds a named attribute to the element, setting it to a floating-point value.
  6760. If the element already contains an attribute with this name, it's value will
  6761. be updated to the new value. If there's no such attribute yet, a new one will
  6762. be added.
  6763. Note that there are other setAttribute() methods that take integers,
  6764. doubles, etc. to make it easy to store numbers.
  6765. @param attributeName the name of the attribute to set
  6766. @param newValue the value to set it to
  6767. */
  6768. void setAttribute (const tchar* const attributeName,
  6769. const double newValue) throw();
  6770. /** Removes a named attribute from the element.
  6771. @param attributeName the name of the attribute to remove
  6772. @see removeAllAttributes
  6773. */
  6774. void removeAttribute (const tchar* const attributeName) throw();
  6775. /** Removes all attributes from this element.
  6776. */
  6777. void removeAllAttributes() throw();
  6778. // Child element methods..
  6779. /** Returns the first of this element's sub-elements.
  6780. see getNextElement() for an example of how to iterate the sub-elements.
  6781. @see forEachXmlChildElement
  6782. */
  6783. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  6784. /** Returns the next of this element's siblings.
  6785. This can be used for iterating an element's sub-elements, e.g.
  6786. @code
  6787. XmlElement* child = myXmlDocument->getFirstChildElement();
  6788. while (child != 0)
  6789. {
  6790. ...do stuff with this child..
  6791. child = child->getNextElement();
  6792. }
  6793. @endcode
  6794. Note that when iterating the child elements, some of them might be
  6795. text elements as well as XML tags - use isTextElement() to work this
  6796. out.
  6797. Also, it's much easier and neater to use this method indirectly via the
  6798. forEachXmlChildElement macro.
  6799. @returns the sibling element that follows this one, or zero if this is the last
  6800. element in its parent
  6801. @see getNextElement, isTextElement, forEachXmlChildElement
  6802. */
  6803. inline XmlElement* getNextElement() const throw() { return nextElement; }
  6804. /** Returns the next of this element's siblings which has the specified tag
  6805. name.
  6806. This is like getNextElement(), but will scan through the list until it
  6807. finds an element with the given tag name.
  6808. @see getNextElement, forEachXmlChildElementWithTagName
  6809. */
  6810. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  6811. /** Returns the number of sub-elements in this element.
  6812. @see getChildElement
  6813. */
  6814. int getNumChildElements() const throw();
  6815. /** Returns the sub-element at a certain index.
  6816. It's not very efficient to iterate the sub-elements by index - see
  6817. getNextElement() for an example of how best to iterate.
  6818. @returns the n'th child of this element, or 0 if the index is out-of-range
  6819. @see getNextElement, isTextElement, getChildByName
  6820. */
  6821. XmlElement* getChildElement (const int index) const throw();
  6822. /** Returns the first sub-element with a given tag-name.
  6823. @param tagNameToLookFor the tag name of the element you want to find
  6824. @returns the first element with this tag name, or 0 if none is found
  6825. @see getNextElement, isTextElement, getChildElement
  6826. */
  6827. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  6828. /** Appends an element to this element's list of children.
  6829. Child elements are deleted automatically when their parent is deleted, so
  6830. make sure the object that you pass in will not be deleted by anything else,
  6831. and make sure it's not already the child of another element.
  6832. @see getFirstChildElement, getNextElement, getNumChildElements,
  6833. getChildElement, removeChildElement
  6834. */
  6835. void addChildElement (XmlElement* const newChildElement) throw();
  6836. /** Inserts an element into this element's list of children.
  6837. Child elements are deleted automatically when their parent is deleted, so
  6838. make sure the object that you pass in will not be deleted by anything else,
  6839. and make sure it's not already the child of another element.
  6840. @param newChildNode the element to add
  6841. @param indexToInsertAt the index at which to insert the new element - if this is
  6842. below zero, it will be added to the end of the list
  6843. @see addChildElement, insertChildElement
  6844. */
  6845. void insertChildElement (XmlElement* const newChildNode,
  6846. int indexToInsertAt) throw();
  6847. /** Replaces one of this element's children with another node.
  6848. If the current element passed-in isn't actually a child of this element,
  6849. this will return false and the new one won't be added. Otherwise, the
  6850. existing element will be deleted, replaced with the new one, and it
  6851. will return true.
  6852. */
  6853. bool replaceChildElement (XmlElement* const currentChildElement,
  6854. XmlElement* const newChildNode) throw();
  6855. /** Removes a child element.
  6856. @param childToRemove the child to look for and remove
  6857. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  6858. just remove it
  6859. */
  6860. void removeChildElement (XmlElement* const childToRemove,
  6861. const bool shouldDeleteTheChild) throw();
  6862. /** Deletes all the child elements in the element.
  6863. @see removeChildElement, deleteAllChildElementsWithTagName
  6864. */
  6865. void deleteAllChildElements() throw();
  6866. /** Deletes all the child elements with a given tag name.
  6867. @see removeChildElement
  6868. */
  6869. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  6870. /** Returns true if the given element is a child of this one. */
  6871. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  6872. /** Recursively searches all sub-elements to find one that contains the specified
  6873. child element.
  6874. */
  6875. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  6876. /** Sorts the child elements using a comparator.
  6877. This will use a comparator object to sort the elements into order. The object
  6878. passed must have a method of the form:
  6879. @code
  6880. int compareElements (const XmlElement* first, const XmlElement* second);
  6881. @endcode
  6882. ..and this method must return:
  6883. - a value of < 0 if the first comes before the second
  6884. - a value of 0 if the two objects are equivalent
  6885. - a value of > 0 if the second comes before the first
  6886. To improve performance, the compareElements() method can be declared as static or const.
  6887. @param comparator the comparator to use for comparing elements.
  6888. @param retainOrderOfEquivalentItems if this is true, then items
  6889. which the comparator says are equivalent will be
  6890. kept in the order in which they currently appear
  6891. in the array. This is slower to perform, but may
  6892. be important in some cases. If it's false, a faster
  6893. algorithm is used, but equivalent elements may be
  6894. rearranged.
  6895. */
  6896. template <class ElementComparator>
  6897. void sortChildElements (ElementComparator& comparator,
  6898. const bool retainOrderOfEquivalentItems = false) throw()
  6899. {
  6900. const int num = getNumChildElements();
  6901. if (num > 1)
  6902. {
  6903. XmlElement** const elems = getChildElementsAsArray (num);
  6904. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  6905. reorderChildElements (elems, num);
  6906. delete[] elems;
  6907. }
  6908. }
  6909. /** Returns true if this element is a section of text.
  6910. Elements can either be an XML tag element or a secton of text, so this
  6911. is used to find out what kind of element this one is.
  6912. @see getAllText, addTextElement, deleteAllTextElements
  6913. */
  6914. bool isTextElement() const throw();
  6915. /** Returns the text for a text element.
  6916. Note that if you have an element like this:
  6917. @code<xyz>hello</xyz>@endcode
  6918. then calling getText on the "xyz" element won't return "hello", because that is
  6919. actually stored in a special text sub-element inside the xyz element. To get the
  6920. "hello" string, you could either call getText on the (unnamed) sub-element, or
  6921. use getAllSubText() to do this automatically.
  6922. @see isTextElement, getAllSubText, getChildElementAllSubText
  6923. */
  6924. const String getText() const throw();
  6925. /** Sets the text in a text element.
  6926. Note that this is only a valid call if this element is a text element. If it's
  6927. not, then no action will be performed.
  6928. */
  6929. void setText (const String& newText) throw();
  6930. /** Returns all the text from this element's child nodes.
  6931. This iterates all the child elements and when it finds text elements,
  6932. it concatenates their text into a big string which it returns.
  6933. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  6934. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  6935. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  6936. */
  6937. const String getAllSubText() const throw();
  6938. /** Returns all the sub-text of a named child element.
  6939. If there is a child element with the given tag name, this will return
  6940. all of its sub-text (by calling getAllSubText() on it). If there is
  6941. no such child element, this will return the default string passed-in.
  6942. @see getAllSubText
  6943. */
  6944. const String getChildElementAllSubText (const tchar* const childTagName,
  6945. const String& defaultReturnValue) const throw();
  6946. /** Appends a section of text to this element.
  6947. @see isTextElement, getText, getAllSubText
  6948. */
  6949. void addTextElement (const String& text) throw();
  6950. /** Removes all the text elements from this element.
  6951. @see isTextElement, getText, getAllSubText, addTextElement
  6952. */
  6953. void deleteAllTextElements() throw();
  6954. /** Creates a text element that can be added to a parent element.
  6955. */
  6956. static XmlElement* createTextElement (const String& text) throw();
  6957. juce_UseDebuggingNewOperator
  6958. private:
  6959. friend class XmlDocument;
  6960. String tagName;
  6961. XmlElement* firstChildElement;
  6962. XmlElement* nextElement;
  6963. struct XmlAttributeNode
  6964. {
  6965. XmlAttributeNode (const XmlAttributeNode& other) throw();
  6966. XmlAttributeNode (const String& name, const String& value) throw();
  6967. String name, value;
  6968. XmlAttributeNode* next;
  6969. };
  6970. XmlAttributeNode* attributes;
  6971. XmlElement (int) throw(); // for internal use
  6972. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  6973. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  6974. void writeElementAsText (OutputStream& out,
  6975. const int indentationLevel,
  6976. const int lineWrapLength) const throw();
  6977. XmlElement** getChildElementsAsArray (const int) const throw();
  6978. void reorderChildElements (XmlElement** const, const int) throw();
  6979. };
  6980. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  6981. /********* End of inlined file: juce_XmlElement.h *********/
  6982. /**
  6983. A set of named property values, which can be strings, integers, floating point, etc.
  6984. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  6985. to load and save types other than strings.
  6986. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  6987. messages and saves/loads the list from a file.
  6988. */
  6989. class JUCE_API PropertySet
  6990. {
  6991. public:
  6992. /** Creates an empty PropertySet.
  6993. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  6994. case-insensitive way
  6995. */
  6996. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  6997. /** Creates a copy of another PropertySet.
  6998. */
  6999. PropertySet (const PropertySet& other) throw();
  7000. /** Copies another PropertySet over this one.
  7001. */
  7002. const PropertySet& operator= (const PropertySet& other) throw();
  7003. /** Destructor. */
  7004. virtual ~PropertySet();
  7005. /** Returns one of the properties as a string.
  7006. If the value isn't found in this set, then this will look for it in a fallback
  7007. property set (if you've specified one with the setFallbackPropertySet() method),
  7008. and if it can't find one there, it'll return the default value passed-in.
  7009. @param keyName the name of the property to retrieve
  7010. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7011. */
  7012. const String getValue (const String& keyName,
  7013. const String& defaultReturnValue = String::empty) const throw();
  7014. /** Returns one of the properties as an integer.
  7015. If the value isn't found in this set, then this will look for it in a fallback
  7016. property set (if you've specified one with the setFallbackPropertySet() method),
  7017. and if it can't find one there, it'll return the default value passed-in.
  7018. @param keyName the name of the property to retrieve
  7019. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7020. */
  7021. int getIntValue (const String& keyName,
  7022. const int defaultReturnValue = 0) const throw();
  7023. /** Returns one of the properties as an double.
  7024. If the value isn't found in this set, then this will look for it in a fallback
  7025. property set (if you've specified one with the setFallbackPropertySet() method),
  7026. and if it can't find one there, it'll return the default value passed-in.
  7027. @param keyName the name of the property to retrieve
  7028. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7029. */
  7030. double getDoubleValue (const String& keyName,
  7031. const double defaultReturnValue = 0.0) const throw();
  7032. /** Returns one of the properties as an boolean.
  7033. The result will be true if the string found for this key name can be parsed as a non-zero
  7034. integer.
  7035. If the value isn't found in this set, then this will look for it in a fallback
  7036. property set (if you've specified one with the setFallbackPropertySet() method),
  7037. and if it can't find one there, it'll return the default value passed-in.
  7038. @param keyName the name of the property to retrieve
  7039. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7040. */
  7041. bool getBoolValue (const String& keyName,
  7042. const bool defaultReturnValue = false) const throw();
  7043. /** Returns one of the properties as an XML element.
  7044. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7045. key isn't found, or if the entry contains an string that isn't valid XML.
  7046. If the value isn't found in this set, then this will look for it in a fallback
  7047. property set (if you've specified one with the setFallbackPropertySet() method),
  7048. and if it can't find one there, it'll return the default value passed-in.
  7049. @param keyName the name of the property to retrieve
  7050. */
  7051. XmlElement* getXmlValue (const String& keyName) const;
  7052. /** Sets a named property as a string.
  7053. @param keyName the name of the property to set. (This mustn't be an empty string)
  7054. @param value the new value to set it to
  7055. */
  7056. void setValue (const String& keyName, const String& value) throw();
  7057. /** Sets a named property as a string.
  7058. @param keyName the name of the property to set. (This mustn't be an empty string)
  7059. @param value the new value to set it to
  7060. */
  7061. void setValue (const String& keyName, const tchar* const value) throw();
  7062. /** Sets a named property to an integer.
  7063. @param keyName the name of the property to set. (This mustn't be an empty string)
  7064. @param value the new value to set it to
  7065. */
  7066. void setValue (const String& keyName, const int value) throw();
  7067. /** Sets a named property to a double.
  7068. @param keyName the name of the property to set. (This mustn't be an empty string)
  7069. @param value the new value to set it to
  7070. */
  7071. void setValue (const String& keyName, const double value) throw();
  7072. /** Sets a named property to a boolean.
  7073. @param keyName the name of the property to set. (This mustn't be an empty string)
  7074. @param value the new value to set it to
  7075. */
  7076. void setValue (const String& keyName, const bool value) throw();
  7077. /** Sets a named property to an XML element.
  7078. @param keyName the name of the property to set. (This mustn't be an empty string)
  7079. @param xml the new element to set it to. If this is zero, the value will be set to
  7080. an empty string
  7081. @see getXmlValue
  7082. */
  7083. void setValue (const String& keyName, const XmlElement* const xml);
  7084. /** Deletes a property.
  7085. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7086. */
  7087. void removeValue (const String& keyName) throw();
  7088. /** Returns true if the properies include the given key. */
  7089. bool containsKey (const String& keyName) const throw();
  7090. /** Removes all values. */
  7091. void clear();
  7092. /** Returns the keys/value pair array containing all the properties. */
  7093. StringPairArray& getAllProperties() throw() { return properties; }
  7094. /** Returns the lock used when reading or writing to this set */
  7095. const CriticalSection& getLock() const throw() { return lock; }
  7096. /** Returns an XML element which encapsulates all the items in this property set.
  7097. The string parameter is the tag name that should be used for the node.
  7098. @see restoreFromXml
  7099. */
  7100. XmlElement* createXml (const String& nodeName) const throw();
  7101. /** Reloads a set of properties that were previously stored as XML.
  7102. The node passed in must have been created by the createXml() method.
  7103. @see createXml
  7104. */
  7105. void restoreFromXml (const XmlElement& xml) throw();
  7106. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7107. set in this one.
  7108. If you set this up to be a pointer to a second property set, then whenever one
  7109. of the getValue() methods fails to find an entry in this set, it will look up that
  7110. value in the fallback set, and if it finds it, it will return that.
  7111. Make sure that you don't delete the fallback set while it's still being used by
  7112. another set! To remove the fallback set, just call this method with a null pointer.
  7113. @see getFallbackPropertySet
  7114. */
  7115. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7116. /** Returns the fallback property set.
  7117. @see setFallbackPropertySet
  7118. */
  7119. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7120. juce_UseDebuggingNewOperator
  7121. protected:
  7122. /** Subclasses can override this to be told when one of the properies has been changed.
  7123. */
  7124. virtual void propertyChanged();
  7125. private:
  7126. StringPairArray properties;
  7127. PropertySet* fallbackProperties;
  7128. CriticalSection lock;
  7129. bool ignoreCaseOfKeys;
  7130. };
  7131. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7132. /********* End of inlined file: juce_PropertySet.h *********/
  7133. #endif
  7134. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7135. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  7136. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7137. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7138. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  7139. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7140. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7141. /**
  7142. Adds reference-counting to an object.
  7143. To add reference-counting to a class, derive it from this class, and
  7144. use the ReferenceCountedObjectPtr class to point to it.
  7145. e.g. @code
  7146. class MyClass : public ReferenceCountedObject
  7147. {
  7148. void foo();
  7149. // This is a neat way of declaring a typedef for a pointer class,
  7150. // rather than typing out the full templated name each time..
  7151. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7152. };
  7153. MyClass::Ptr p = new MyClass();
  7154. MyClass::Ptr p2 = p;
  7155. p = 0;
  7156. p2->foo();
  7157. @endcode
  7158. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7159. careful not to delete the object manually.
  7160. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7161. */
  7162. class JUCE_API ReferenceCountedObject
  7163. {
  7164. public:
  7165. /** Increments the object's reference count.
  7166. This is done automatically by the smart pointer, but is public just
  7167. in case it's needed for nefarious purposes.
  7168. */
  7169. inline void incReferenceCount() throw()
  7170. {
  7171. atomicIncrement (refCounts);
  7172. jassert (refCounts > 0);
  7173. }
  7174. /** Decreases the object's reference count.
  7175. If the count gets to zero, the object will be deleted.
  7176. */
  7177. inline void decReferenceCount() throw()
  7178. {
  7179. jassert (refCounts > 0);
  7180. if (atomicDecrementAndReturn (refCounts) == 0)
  7181. delete this;
  7182. }
  7183. /** Returns the object's current reference count. */
  7184. inline int getReferenceCount() const throw()
  7185. {
  7186. return refCounts;
  7187. }
  7188. protected:
  7189. /** Creates the reference-counted object (with an initial ref count of zero). */
  7190. ReferenceCountedObject()
  7191. : refCounts (0)
  7192. {
  7193. }
  7194. /** Destructor. */
  7195. virtual ~ReferenceCountedObject()
  7196. {
  7197. // it's dangerous to delete an object that's still referenced by something else!
  7198. jassert (refCounts == 0);
  7199. }
  7200. private:
  7201. int refCounts;
  7202. };
  7203. /**
  7204. Used to point to an object of type ReferenceCountedObject.
  7205. It's wise to use a typedef instead of typing out the templated name
  7206. each time - e.g.
  7207. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7208. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7209. */
  7210. template <class ReferenceCountedObjectClass>
  7211. class ReferenceCountedObjectPtr
  7212. {
  7213. public:
  7214. /** Creates a pointer to a null object. */
  7215. inline ReferenceCountedObjectPtr() throw()
  7216. : referencedObject (0)
  7217. {
  7218. }
  7219. /** Creates a pointer to an object.
  7220. This will increment the object's reference-count if it is non-null.
  7221. */
  7222. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7223. : referencedObject (refCountedObject)
  7224. {
  7225. if (refCountedObject != 0)
  7226. refCountedObject->incReferenceCount();
  7227. }
  7228. /** Copies another pointer.
  7229. This will increment the object's reference-count (if it is non-null).
  7230. */
  7231. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7232. : referencedObject (other.referencedObject)
  7233. {
  7234. if (referencedObject != 0)
  7235. referencedObject->incReferenceCount();
  7236. }
  7237. /** Changes this pointer to point at a different object.
  7238. The reference count of the old object is decremented, and it might be
  7239. deleted if it hits zero. The new object's count is incremented.
  7240. */
  7241. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7242. {
  7243. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7244. if (newObject != referencedObject)
  7245. {
  7246. if (newObject != 0)
  7247. newObject->incReferenceCount();
  7248. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7249. referencedObject = newObject;
  7250. if (oldObject != 0)
  7251. oldObject->decReferenceCount();
  7252. }
  7253. return *this;
  7254. }
  7255. /** Changes this pointer to point at a different object.
  7256. The reference count of the old object is decremented, and it might be
  7257. deleted if it hits zero. The new object's count is incremented.
  7258. */
  7259. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7260. {
  7261. if (referencedObject != newObject)
  7262. {
  7263. if (newObject != 0)
  7264. newObject->incReferenceCount();
  7265. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7266. referencedObject = newObject;
  7267. if (oldObject != 0)
  7268. oldObject->decReferenceCount();
  7269. }
  7270. return *this;
  7271. }
  7272. /** Destructor.
  7273. This will decrement the object's reference-count, and may delete it if it
  7274. gets to zero.
  7275. */
  7276. inline ~ReferenceCountedObjectPtr()
  7277. {
  7278. if (referencedObject != 0)
  7279. referencedObject->decReferenceCount();
  7280. }
  7281. /** Returns the object that this pointer references.
  7282. The pointer returned may be zero, of course.
  7283. */
  7284. inline operator ReferenceCountedObjectClass*() const throw()
  7285. {
  7286. return referencedObject;
  7287. }
  7288. /** Returns true if this pointer refers to the given object. */
  7289. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7290. {
  7291. return referencedObject == object;
  7292. }
  7293. /** Returns true if this pointer doesn't refer to the given object. */
  7294. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7295. {
  7296. return referencedObject != object;
  7297. }
  7298. // the -> operator is called on the referenced object
  7299. inline ReferenceCountedObjectClass* operator->() const throw()
  7300. {
  7301. return referencedObject;
  7302. }
  7303. private:
  7304. ReferenceCountedObjectClass* referencedObject;
  7305. };
  7306. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7307. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7308. /**
  7309. Holds a list of objects derived from ReferenceCountedObject.
  7310. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7311. and takes care of incrementing and decrementing their ref counts when they
  7312. are added and removed from the array.
  7313. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7314. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7315. @see Array, OwnedArray, StringArray
  7316. */
  7317. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7318. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  7319. {
  7320. public:
  7321. /** Creates an empty array.
  7322. @param granularity this is the size of increment by which the internal storage
  7323. used by the array will grow. Only change it from the default if you know the
  7324. array is going to be very big and needs to be able to grow efficiently.
  7325. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  7326. */
  7327. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7328. : ArrayAllocationBase <ObjectClass*> (granularity),
  7329. numUsed (0)
  7330. {
  7331. }
  7332. /** Creates a copy of another array */
  7333. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7334. : ArrayAllocationBase <ObjectClass*> (other.granularity),
  7335. numUsed (other.numUsed)
  7336. {
  7337. other.lockArray();
  7338. this->setAllocatedSize (numUsed);
  7339. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7340. for (int i = numUsed; --i >= 0;)
  7341. if (this->elements[i] != 0)
  7342. this->elements[i]->incReferenceCount();
  7343. other.unlockArray();
  7344. }
  7345. /** Copies another array into this one.
  7346. Any existing objects in this array will first be released.
  7347. */
  7348. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7349. {
  7350. if (this != &other)
  7351. {
  7352. other.lockArray();
  7353. lock.enter();
  7354. clear();
  7355. this->granularity = other.granularity;
  7356. this->ensureAllocatedSize (other.numUsed);
  7357. numUsed = other.numUsed;
  7358. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7359. minimiseStorageOverheads();
  7360. for (int i = numUsed; --i >= 0;)
  7361. if (this->elements[i] != 0)
  7362. this->elements[i]->incReferenceCount();
  7363. lock.exit();
  7364. other.unlockArray();
  7365. }
  7366. return *this;
  7367. }
  7368. /** Destructor.
  7369. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7370. */
  7371. ~ReferenceCountedArray()
  7372. {
  7373. clear();
  7374. }
  7375. /** Removes all objects from the array.
  7376. Any objects in the array that are not referenced from elsewhere will be deleted.
  7377. */
  7378. void clear()
  7379. {
  7380. lock.enter();
  7381. while (numUsed > 0)
  7382. if (this->elements [--numUsed] != 0)
  7383. this->elements [numUsed]->decReferenceCount();
  7384. jassert (numUsed == 0);
  7385. this->setAllocatedSize (0);
  7386. lock.exit();
  7387. }
  7388. /** Returns the current number of objects in the array. */
  7389. inline int size() const throw()
  7390. {
  7391. return numUsed;
  7392. }
  7393. /** Returns a pointer to the object at this index in the array.
  7394. If the index is out-of-range, this will return a null pointer, (and
  7395. it could be null anyway, because it's ok for the array to hold null
  7396. pointers as well as objects).
  7397. @see getUnchecked
  7398. */
  7399. inline ObjectClass* operator[] (const int index) const throw()
  7400. {
  7401. lock.enter();
  7402. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  7403. ? this->elements [index]
  7404. : (ObjectClass*) 0;
  7405. lock.exit();
  7406. return result;
  7407. }
  7408. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7409. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7410. it can be used when you're sure the index if always going to be legal.
  7411. */
  7412. inline ObjectClass* getUnchecked (const int index) const throw()
  7413. {
  7414. lock.enter();
  7415. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7416. ObjectClass* const result = this->elements [index];
  7417. lock.exit();
  7418. return result;
  7419. }
  7420. /** Returns a pointer to the first object in the array.
  7421. This will return a null pointer if the array's empty.
  7422. @see getLast
  7423. */
  7424. inline ObjectClass* getFirst() const throw()
  7425. {
  7426. lock.enter();
  7427. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  7428. : (ObjectClass*) 0;
  7429. lock.exit();
  7430. return result;
  7431. }
  7432. /** Returns a pointer to the last object in the array.
  7433. This will return a null pointer if the array's empty.
  7434. @see getFirst
  7435. */
  7436. inline ObjectClass* getLast() const throw()
  7437. {
  7438. lock.enter();
  7439. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  7440. : (ObjectClass*) 0;
  7441. lock.exit();
  7442. return result;
  7443. }
  7444. /** Finds the index of the first occurrence of an object in the array.
  7445. @param objectToLookFor the object to look for
  7446. @returns the index at which the object was found, or -1 if it's not found
  7447. */
  7448. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7449. {
  7450. int result = -1;
  7451. lock.enter();
  7452. ObjectClass** e = this->elements;
  7453. for (int i = numUsed; --i >= 0;)
  7454. {
  7455. if (objectToLookFor == *e)
  7456. {
  7457. result = (int) (e - this->elements);
  7458. break;
  7459. }
  7460. ++e;
  7461. }
  7462. lock.exit();
  7463. return result;
  7464. }
  7465. /** Returns true if the array contains a specified object.
  7466. @param objectToLookFor the object to look for
  7467. @returns true if the object is in the array
  7468. */
  7469. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7470. {
  7471. lock.enter();
  7472. ObjectClass** e = this->elements;
  7473. for (int i = numUsed; --i >= 0;)
  7474. {
  7475. if (objectToLookFor == *e)
  7476. {
  7477. lock.exit();
  7478. return true;
  7479. }
  7480. ++e;
  7481. }
  7482. lock.exit();
  7483. return false;
  7484. }
  7485. /** Appends a new object to the end of the array.
  7486. This will increase the new object's reference count.
  7487. @param newObject the new object to add to the array
  7488. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7489. */
  7490. void add (ObjectClass* const newObject) throw()
  7491. {
  7492. lock.enter();
  7493. this->ensureAllocatedSize (numUsed + 1);
  7494. this->elements [numUsed++] = newObject;
  7495. if (newObject != 0)
  7496. newObject->incReferenceCount();
  7497. lock.exit();
  7498. }
  7499. /** Inserts a new object into the array at the given index.
  7500. If the index is less than 0 or greater than the size of the array, the
  7501. element will be added to the end of the array.
  7502. Otherwise, it will be inserted into the array, moving all the later elements
  7503. along to make room.
  7504. This will increase the new object's reference count.
  7505. @param indexToInsertAt the index at which the new element should be inserted
  7506. @param newObject the new object to add to the array
  7507. @see add, addSorted, addIfNotAlreadyThere, set
  7508. */
  7509. void insert (int indexToInsertAt,
  7510. ObjectClass* const newObject) throw()
  7511. {
  7512. if (indexToInsertAt >= 0)
  7513. {
  7514. lock.enter();
  7515. if (indexToInsertAt > numUsed)
  7516. indexToInsertAt = numUsed;
  7517. this->ensureAllocatedSize (numUsed + 1);
  7518. ObjectClass** const e = this->elements + indexToInsertAt;
  7519. const int numToMove = numUsed - indexToInsertAt;
  7520. if (numToMove > 0)
  7521. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7522. *e = newObject;
  7523. if (newObject != 0)
  7524. newObject->incReferenceCount();
  7525. ++numUsed;
  7526. lock.exit();
  7527. }
  7528. else
  7529. {
  7530. add (newObject);
  7531. }
  7532. }
  7533. /** Appends a new object at the end of the array as long as the array doesn't
  7534. already contain it.
  7535. If the array already contains a matching object, nothing will be done.
  7536. @param newObject the new object to add to the array
  7537. */
  7538. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7539. {
  7540. lock.enter();
  7541. if (! contains (newObject))
  7542. add (newObject);
  7543. lock.exit();
  7544. }
  7545. /** Replaces an object in the array with a different one.
  7546. If the index is less than zero, this method does nothing.
  7547. If the index is beyond the end of the array, the new object is added to the end of the array.
  7548. The object being added has its reference count increased, and if it's replacing
  7549. another object, then that one has its reference count decreased, and may be deleted.
  7550. @param indexToChange the index whose value you want to change
  7551. @param newObject the new value to set for this index.
  7552. @see add, insert, remove
  7553. */
  7554. void set (const int indexToChange,
  7555. ObjectClass* const newObject)
  7556. {
  7557. if (indexToChange >= 0)
  7558. {
  7559. lock.enter();
  7560. if (newObject != 0)
  7561. newObject->incReferenceCount();
  7562. if (indexToChange < numUsed)
  7563. {
  7564. if (this->elements [indexToChange] != 0)
  7565. this->elements [indexToChange]->decReferenceCount();
  7566. this->elements [indexToChange] = newObject;
  7567. }
  7568. else
  7569. {
  7570. this->ensureAllocatedSize (numUsed + 1);
  7571. this->elements [numUsed++] = newObject;
  7572. }
  7573. lock.exit();
  7574. }
  7575. }
  7576. /** Adds elements from another array to the end of this array.
  7577. @param arrayToAddFrom the array from which to copy the elements
  7578. @param startIndex the first element of the other array to start copying from
  7579. @param numElementsToAdd how many elements to add from the other array. If this
  7580. value is negative or greater than the number of available elements,
  7581. all available elements will be copied.
  7582. @see add
  7583. */
  7584. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7585. int startIndex = 0,
  7586. int numElementsToAdd = -1) throw()
  7587. {
  7588. arrayToAddFrom.lockArray();
  7589. lock.enter();
  7590. if (startIndex < 0)
  7591. {
  7592. jassertfalse
  7593. startIndex = 0;
  7594. }
  7595. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7596. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7597. if (numElementsToAdd > 0)
  7598. {
  7599. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  7600. while (--numElementsToAdd >= 0)
  7601. add (arrayToAddFrom.getUnchecked (startIndex++));
  7602. }
  7603. lock.exit();
  7604. arrayToAddFrom.unlockArray();
  7605. }
  7606. /** Inserts a new object into the array assuming that the array is sorted.
  7607. This will use a comparator to find the position at which the new object
  7608. should go. If the array isn't sorted, the behaviour of this
  7609. method will be unpredictable.
  7610. @param comparator the comparator object to use to compare the elements - see the
  7611. sort() method for details about this object's form
  7612. @param newObject the new object to insert to the array
  7613. @see add, sort
  7614. */
  7615. template <class ElementComparator>
  7616. void addSorted (ElementComparator& comparator,
  7617. ObjectClass* newObject) throw()
  7618. {
  7619. lock.enter();
  7620. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  7621. lock.exit();
  7622. }
  7623. /** Removes an object from the array.
  7624. This will remove the object at a given index and move back all the
  7625. subsequent objects to close the gap.
  7626. If the index passed in is out-of-range, nothing will happen.
  7627. The object that is removed will have its reference count decreased,
  7628. and may be deleted if not referenced from elsewhere.
  7629. @param indexToRemove the index of the element to remove
  7630. @see removeObject, removeRange
  7631. */
  7632. void remove (const int indexToRemove)
  7633. {
  7634. lock.enter();
  7635. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  7636. {
  7637. ObjectClass** const e = this->elements + indexToRemove;
  7638. if (*e != 0)
  7639. (*e)->decReferenceCount();
  7640. --numUsed;
  7641. const int numberToShift = numUsed - indexToRemove;
  7642. if (numberToShift > 0)
  7643. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  7644. if ((numUsed << 1) < this->numAllocated)
  7645. minimiseStorageOverheads();
  7646. }
  7647. lock.exit();
  7648. }
  7649. /** Removes the first occurrence of a specified object from the array.
  7650. If the item isn't found, no action is taken. If it is found, it is
  7651. removed and has its reference count decreased.
  7652. @param objectToRemove the object to try to remove
  7653. @see remove, removeRange
  7654. */
  7655. void removeObject (ObjectClass* const objectToRemove)
  7656. {
  7657. lock.enter();
  7658. remove (indexOf (objectToRemove));
  7659. lock.exit();
  7660. }
  7661. /** Removes a range of objects from the array.
  7662. This will remove a set of objects, starting from the given index,
  7663. and move any subsequent elements down to close the gap.
  7664. If the range extends beyond the bounds of the array, it will
  7665. be safely clipped to the size of the array.
  7666. The objects that are removed will have their reference counts decreased,
  7667. and may be deleted if not referenced from elsewhere.
  7668. @param startIndex the index of the first object to remove
  7669. @param numberToRemove how many objects should be removed
  7670. @see remove, removeObject
  7671. */
  7672. void removeRange (const int startIndex,
  7673. const int numberToRemove)
  7674. {
  7675. lock.enter();
  7676. const int start = jlimit (0, numUsed, startIndex);
  7677. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  7678. if (end > start)
  7679. {
  7680. int i;
  7681. for (i = start; i < end; ++i)
  7682. {
  7683. if (this->elements[i] != 0)
  7684. {
  7685. this->elements[i]->decReferenceCount();
  7686. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7687. }
  7688. }
  7689. const int rangeSize = end - start;
  7690. ObjectClass** e = this->elements + start;
  7691. i = numUsed - end;
  7692. numUsed -= rangeSize;
  7693. while (--i >= 0)
  7694. {
  7695. *e = e [rangeSize];
  7696. ++e;
  7697. }
  7698. if ((numUsed << 1) < this->numAllocated)
  7699. minimiseStorageOverheads();
  7700. }
  7701. lock.exit();
  7702. }
  7703. /** Removes the last n objects from the array.
  7704. The objects that are removed will have their reference counts decreased,
  7705. and may be deleted if not referenced from elsewhere.
  7706. @param howManyToRemove how many objects to remove from the end of the array
  7707. @see remove, removeObject, removeRange
  7708. */
  7709. void removeLast (int howManyToRemove = 1)
  7710. {
  7711. lock.enter();
  7712. if (howManyToRemove > numUsed)
  7713. howManyToRemove = numUsed;
  7714. while (--howManyToRemove >= 0)
  7715. remove (numUsed - 1);
  7716. lock.exit();
  7717. }
  7718. /** Swaps a pair of objects in the array.
  7719. If either of the indexes passed in is out-of-range, nothing will happen,
  7720. otherwise the two objects at these positions will be exchanged.
  7721. */
  7722. void swap (const int index1,
  7723. const int index2) throw()
  7724. {
  7725. lock.enter();
  7726. if (((unsigned int) index1) < (unsigned int) numUsed
  7727. && ((unsigned int) index2) < (unsigned int) numUsed)
  7728. {
  7729. swapVariables (this->elements [index1],
  7730. this->elements [index2]);
  7731. }
  7732. lock.exit();
  7733. }
  7734. /** Moves one of the objects to a different position.
  7735. This will move the object to a specified index, shuffling along
  7736. any intervening elements as required.
  7737. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7738. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7739. @param currentIndex the index of the object to be moved. If this isn't a
  7740. valid index, then nothing will be done
  7741. @param newIndex the index at which you'd like this object to end up. If this
  7742. is less than zero, it will be moved to the end of the array
  7743. */
  7744. void move (const int currentIndex,
  7745. int newIndex) throw()
  7746. {
  7747. if (currentIndex != newIndex)
  7748. {
  7749. lock.enter();
  7750. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  7751. {
  7752. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  7753. newIndex = numUsed - 1;
  7754. ObjectClass* const value = this->elements [currentIndex];
  7755. if (newIndex > currentIndex)
  7756. {
  7757. memmove (this->elements + currentIndex,
  7758. this->elements + currentIndex + 1,
  7759. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7760. }
  7761. else
  7762. {
  7763. memmove (this->elements + newIndex + 1,
  7764. this->elements + newIndex,
  7765. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7766. }
  7767. this->elements [newIndex] = value;
  7768. }
  7769. lock.exit();
  7770. }
  7771. }
  7772. /** Compares this array to another one.
  7773. @returns true only if the other array contains the same objects in the same order
  7774. */
  7775. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7776. {
  7777. other.lockArray();
  7778. lock.enter();
  7779. bool result = numUsed == other.numUsed;
  7780. if (result)
  7781. {
  7782. for (int i = numUsed; --i >= 0;)
  7783. {
  7784. if (this->elements [i] != other.elements [i])
  7785. {
  7786. result = false;
  7787. break;
  7788. }
  7789. }
  7790. }
  7791. lock.exit();
  7792. other.unlockArray();
  7793. return result;
  7794. }
  7795. /** Compares this array to another one.
  7796. @see operator==
  7797. */
  7798. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7799. {
  7800. return ! operator== (other);
  7801. }
  7802. /** Sorts the elements in the array.
  7803. This will use a comparator object to sort the elements into order. The object
  7804. passed must have a method of the form:
  7805. @code
  7806. int compareElements (ElementType first, ElementType second);
  7807. @endcode
  7808. ..and this method must return:
  7809. - a value of < 0 if the first comes before the second
  7810. - a value of 0 if the two objects are equivalent
  7811. - a value of > 0 if the second comes before the first
  7812. To improve performance, the compareElements() method can be declared as static or const.
  7813. @param comparator the comparator to use for comparing elements.
  7814. @param retainOrderOfEquivalentItems if this is true, then items
  7815. which the comparator says are equivalent will be
  7816. kept in the order in which they currently appear
  7817. in the array. This is slower to perform, but may
  7818. be important in some cases. If it's false, a faster
  7819. algorithm is used, but equivalent elements may be
  7820. rearranged.
  7821. @see sortArray
  7822. */
  7823. template <class ElementComparator>
  7824. void sort (ElementComparator& comparator,
  7825. const bool retainOrderOfEquivalentItems = false) const throw()
  7826. {
  7827. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7828. // avoids getting warning messages about the parameter being unused
  7829. lock.enter();
  7830. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  7831. lock.exit();
  7832. }
  7833. /** Reduces the amount of storage being used by the array.
  7834. Arrays typically allocate slightly more storage than they need, and after
  7835. removing elements, they may have quite a lot of unused space allocated.
  7836. This method will reduce the amount of allocated storage to a minimum.
  7837. */
  7838. void minimiseStorageOverheads() throw()
  7839. {
  7840. lock.enter();
  7841. if (numUsed == 0)
  7842. {
  7843. this->setAllocatedSize (0);
  7844. }
  7845. else
  7846. {
  7847. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  7848. if (newAllocation < this->numAllocated)
  7849. this->setAllocatedSize (newAllocation);
  7850. }
  7851. lock.exit();
  7852. }
  7853. /** Locks the array's CriticalSection.
  7854. Of course if the type of section used is a DummyCriticalSection, this won't
  7855. have any effect.
  7856. @see unlockArray
  7857. */
  7858. void lockArray() const throw()
  7859. {
  7860. lock.enter();
  7861. }
  7862. /** Unlocks the array's CriticalSection.
  7863. Of course if the type of section used is a DummyCriticalSection, this won't
  7864. have any effect.
  7865. @see lockArray
  7866. */
  7867. void unlockArray() const throw()
  7868. {
  7869. lock.exit();
  7870. }
  7871. juce_UseDebuggingNewOperator
  7872. private:
  7873. int numUsed;
  7874. TypeOfCriticalSectionToUse lock;
  7875. };
  7876. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7877. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  7878. #endif
  7879. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7880. #endif
  7881. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7882. /********* Start of inlined file: juce_SortedSet.h *********/
  7883. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7884. #define __JUCE_SORTEDSET_JUCEHEADER__
  7885. #if JUCE_MSVC
  7886. #pragma warning (push)
  7887. #pragma warning (disable: 4512)
  7888. #endif
  7889. /**
  7890. Holds a set of unique primitive objects, such as ints or doubles.
  7891. A set can only hold one item with a given value, so if for example it's a
  7892. set of integers, attempting to add the same integer twice will do nothing
  7893. the second time.
  7894. Internally, the list of items is kept sorted (which means that whatever
  7895. kind of primitive type is used must support the ==, <, >, <= and >= operators
  7896. to determine the order), and searching the set for known values is very fast
  7897. because it uses a binary-chop method.
  7898. Note that if you're using a class or struct as the element type, it must be
  7899. capable of being copied or moved with a straightforward memcpy, rather than
  7900. needing construction and destruction code.
  7901. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  7902. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7903. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  7904. */
  7905. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7906. class SortedSet : private ArrayAllocationBase <ElementType>
  7907. {
  7908. public:
  7909. /** Creates an empty set.
  7910. @param granularity this is the size of increment by which the internal storage
  7911. used by the array will grow. Only change it from the default if you know the
  7912. array is going to be very big and needs to be able to grow efficiently.
  7913. @see ArrayAllocationBase
  7914. */
  7915. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  7916. : ArrayAllocationBase <ElementType> (granularity),
  7917. numUsed (0)
  7918. {
  7919. }
  7920. /** Creates a copy of another set.
  7921. @param other the set to copy
  7922. */
  7923. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7924. : ArrayAllocationBase <ElementType> (other.granularity)
  7925. {
  7926. other.lockSet();
  7927. numUsed = other.numUsed;
  7928. setAllocatedSize (other.numUsed);
  7929. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7930. other.unlockSet();
  7931. }
  7932. /** Destructor. */
  7933. ~SortedSet() throw()
  7934. {
  7935. }
  7936. /** Copies another set over this one.
  7937. @param other the set to copy
  7938. */
  7939. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7940. {
  7941. if (this != &other)
  7942. {
  7943. other.lockSet();
  7944. lock.enter();
  7945. this->granularity = other.granularity;
  7946. ensureAllocatedSize (other.size());
  7947. numUsed = other.numUsed;
  7948. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  7949. minimiseStorageOverheads();
  7950. lock.exit();
  7951. other.unlockSet();
  7952. }
  7953. return *this;
  7954. }
  7955. /** Compares this set to another one.
  7956. Two sets are considered equal if they both contain the same set of
  7957. elements.
  7958. @param other the other set to compare with
  7959. */
  7960. bool operator== (const SortedSet<ElementType>& other) const throw()
  7961. {
  7962. lock.enter();
  7963. if (numUsed != other.numUsed)
  7964. {
  7965. lock.exit();
  7966. return false;
  7967. }
  7968. for (int i = numUsed; --i >= 0;)
  7969. {
  7970. if (this->elements [i] != other.elements [i])
  7971. {
  7972. lock.exit();
  7973. return false;
  7974. }
  7975. }
  7976. lock.exit();
  7977. return true;
  7978. }
  7979. /** Compares this set to another one.
  7980. Two sets are considered equal if they both contain the same set of
  7981. elements.
  7982. @param other the other set to compare with
  7983. */
  7984. bool operator!= (const SortedSet<ElementType>& other) const throw()
  7985. {
  7986. return ! operator== (other);
  7987. }
  7988. /** Removes all elements from the set.
  7989. This will remove all the elements, and free any storage that the set is
  7990. using. To clear it without freeing the storage, use the clearQuick()
  7991. method instead.
  7992. @see clearQuick
  7993. */
  7994. void clear() throw()
  7995. {
  7996. lock.enter();
  7997. this->setAllocatedSize (0);
  7998. numUsed = 0;
  7999. lock.exit();
  8000. }
  8001. /** Removes all elements from the set without freeing the array's allocated storage.
  8002. @see clear
  8003. */
  8004. void clearQuick() throw()
  8005. {
  8006. lock.enter();
  8007. numUsed = 0;
  8008. lock.exit();
  8009. }
  8010. /** Returns the current number of elements in the set.
  8011. */
  8012. inline int size() const throw()
  8013. {
  8014. return numUsed;
  8015. }
  8016. /** Returns one of the elements in the set.
  8017. If the index passed in is beyond the range of valid elements, this
  8018. will return zero.
  8019. If you're certain that the index will always be a valid element, you
  8020. can call getUnchecked() instead, which is faster.
  8021. @param index the index of the element being requested (0 is the first element in the set)
  8022. @see getUnchecked, getFirst, getLast
  8023. */
  8024. inline ElementType operator[] (const int index) const throw()
  8025. {
  8026. lock.enter();
  8027. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  8028. ? this->elements [index]
  8029. : (ElementType) 0;
  8030. lock.exit();
  8031. return result;
  8032. }
  8033. /** Returns one of the elements in the set, without checking the index passed in.
  8034. Unlike the operator[] method, this will try to return an element without
  8035. checking that the index is within the bounds of the set, so should only
  8036. be used when you're confident that it will always be a valid index.
  8037. @param index the index of the element being requested (0 is the first element in the set)
  8038. @see operator[], getFirst, getLast
  8039. */
  8040. inline ElementType getUnchecked (const int index) const throw()
  8041. {
  8042. lock.enter();
  8043. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8044. const ElementType result = this->elements [index];
  8045. lock.exit();
  8046. return result;
  8047. }
  8048. /** Returns the first element in the set, or 0 if the set is empty.
  8049. @see operator[], getUnchecked, getLast
  8050. */
  8051. inline ElementType getFirst() const throw()
  8052. {
  8053. lock.enter();
  8054. const ElementType result = (numUsed > 0) ? this->elements [0]
  8055. : (ElementType) 0;
  8056. lock.exit();
  8057. return result;
  8058. }
  8059. /** Returns the last element in the set, or 0 if the set is empty.
  8060. @see operator[], getUnchecked, getFirst
  8061. */
  8062. inline ElementType getLast() const throw()
  8063. {
  8064. lock.enter();
  8065. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  8066. : (ElementType) 0;
  8067. lock.exit();
  8068. return result;
  8069. }
  8070. /** Finds the index of the first element which matches the value passed in.
  8071. This will search the set for the given object, and return the index
  8072. of its first occurrence. If the object isn't found, the method will return -1.
  8073. @param elementToLookFor the value or object to look for
  8074. @returns the index of the object, or -1 if it's not found
  8075. */
  8076. int indexOf (const ElementType elementToLookFor) const throw()
  8077. {
  8078. lock.enter();
  8079. int start = 0;
  8080. int end = numUsed;
  8081. for (;;)
  8082. {
  8083. if (start >= end)
  8084. {
  8085. lock.exit();
  8086. return -1;
  8087. }
  8088. else if (elementToLookFor == this->elements [start])
  8089. {
  8090. lock.exit();
  8091. return start;
  8092. }
  8093. else
  8094. {
  8095. const int halfway = (start + end) >> 1;
  8096. if (halfway == start)
  8097. {
  8098. lock.exit();
  8099. return -1;
  8100. }
  8101. else if (elementToLookFor >= this->elements [halfway])
  8102. start = halfway;
  8103. else
  8104. end = halfway;
  8105. }
  8106. }
  8107. }
  8108. /** Returns true if the set contains at least one occurrence of an object.
  8109. @param elementToLookFor the value or object to look for
  8110. @returns true if the item is found
  8111. */
  8112. bool contains (const ElementType elementToLookFor) const throw()
  8113. {
  8114. lock.enter();
  8115. int start = 0;
  8116. int end = numUsed;
  8117. for (;;)
  8118. {
  8119. if (start >= end)
  8120. {
  8121. lock.exit();
  8122. return false;
  8123. }
  8124. else if (elementToLookFor == this->elements [start])
  8125. {
  8126. lock.exit();
  8127. return true;
  8128. }
  8129. else
  8130. {
  8131. const int halfway = (start + end) >> 1;
  8132. if (halfway == start)
  8133. {
  8134. lock.exit();
  8135. return false;
  8136. }
  8137. else if (elementToLookFor >= this->elements [halfway])
  8138. start = halfway;
  8139. else
  8140. end = halfway;
  8141. }
  8142. }
  8143. }
  8144. /** Adds a new element to the set, (as long as it's not already in there).
  8145. @param newElement the new object to add to the set
  8146. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8147. */
  8148. void add (const ElementType newElement) throw()
  8149. {
  8150. lock.enter();
  8151. int start = 0;
  8152. int end = numUsed;
  8153. for (;;)
  8154. {
  8155. if (start >= end)
  8156. {
  8157. jassert (start <= end);
  8158. insertInternal (start, newElement);
  8159. break;
  8160. }
  8161. else if (newElement == this->elements [start])
  8162. {
  8163. break;
  8164. }
  8165. else
  8166. {
  8167. const int halfway = (start + end) >> 1;
  8168. if (halfway == start)
  8169. {
  8170. if (newElement >= this->elements [halfway])
  8171. insertInternal (start + 1, newElement);
  8172. else
  8173. insertInternal (start, newElement);
  8174. break;
  8175. }
  8176. else if (newElement >= this->elements [halfway])
  8177. start = halfway;
  8178. else
  8179. end = halfway;
  8180. }
  8181. }
  8182. lock.exit();
  8183. }
  8184. /** Adds elements from an array to this set.
  8185. @param elementsToAdd the array of elements to add
  8186. @param numElementsToAdd how many elements are in this other array
  8187. @see add
  8188. */
  8189. void addArray (const ElementType* elementsToAdd,
  8190. int numElementsToAdd) throw()
  8191. {
  8192. lock.enter();
  8193. while (--numElementsToAdd >= 0)
  8194. add (*elementsToAdd++);
  8195. lock.exit();
  8196. }
  8197. /** Adds elements from another set to this one.
  8198. @param setToAddFrom the set from which to copy the elements
  8199. @param startIndex the first element of the other set to start copying from
  8200. @param numElementsToAdd how many elements to add from the other set. If this
  8201. value is negative or greater than the number of available elements,
  8202. all available elements will be copied.
  8203. @see add
  8204. */
  8205. template <class OtherSetType>
  8206. void addSet (const OtherSetType& setToAddFrom,
  8207. int startIndex = 0,
  8208. int numElementsToAdd = -1) throw()
  8209. {
  8210. setToAddFrom.lockSet();
  8211. lock.enter();
  8212. jassert (this != &setToAddFrom);
  8213. if (this != &setToAddFrom)
  8214. {
  8215. if (startIndex < 0)
  8216. {
  8217. jassertfalse
  8218. startIndex = 0;
  8219. }
  8220. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8221. numElementsToAdd = setToAddFrom.size() - startIndex;
  8222. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8223. }
  8224. lock.exit();
  8225. setToAddFrom.unlockSet();
  8226. }
  8227. /** Removes an element from the set.
  8228. This will remove the element at a given index.
  8229. If the index passed in is out-of-range, nothing will happen.
  8230. @param indexToRemove the index of the element to remove
  8231. @returns the element that has been removed
  8232. @see removeValue, removeRange
  8233. */
  8234. ElementType remove (const int indexToRemove) throw()
  8235. {
  8236. lock.enter();
  8237. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8238. {
  8239. --numUsed;
  8240. ElementType* const e = this->elements + indexToRemove;
  8241. ElementType const removed = *e;
  8242. const int numberToShift = numUsed - indexToRemove;
  8243. if (numberToShift > 0)
  8244. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8245. if ((numUsed << 1) < this->numAllocated)
  8246. minimiseStorageOverheads();
  8247. lock.exit();
  8248. return removed;
  8249. }
  8250. else
  8251. {
  8252. lock.exit();
  8253. return 0;
  8254. }
  8255. }
  8256. /** Removes an item from the set.
  8257. This will remove the given element from the set, if it's there.
  8258. @param valueToRemove the object to try to remove
  8259. @see remove, removeRange
  8260. */
  8261. void removeValue (const ElementType valueToRemove) throw()
  8262. {
  8263. lock.enter();
  8264. remove (indexOf (valueToRemove));
  8265. lock.exit();
  8266. }
  8267. /** Removes any elements which are also in another set.
  8268. @param otherSet the other set in which to look for elements to remove
  8269. @see removeValuesNotIn, remove, removeValue, removeRange
  8270. */
  8271. template <class OtherSetType>
  8272. void removeValuesIn (const OtherSetType& otherSet) throw()
  8273. {
  8274. otherSet.lockSet();
  8275. lock.enter();
  8276. if (this == &otherSet)
  8277. {
  8278. clear();
  8279. }
  8280. else
  8281. {
  8282. if (otherSet.size() > 0)
  8283. {
  8284. for (int i = numUsed; --i >= 0;)
  8285. if (otherSet.contains (this->elements [i]))
  8286. remove (i);
  8287. }
  8288. }
  8289. lock.exit();
  8290. otherSet.unlockSet();
  8291. }
  8292. /** Removes any elements which are not found in another set.
  8293. Only elements which occur in this other set will be retained.
  8294. @param otherSet the set in which to look for elements NOT to remove
  8295. @see removeValuesIn, remove, removeValue, removeRange
  8296. */
  8297. template <class OtherSetType>
  8298. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8299. {
  8300. otherSet.lockSet();
  8301. lock.enter();
  8302. if (this != &otherSet)
  8303. {
  8304. if (otherSet.size() <= 0)
  8305. {
  8306. clear();
  8307. }
  8308. else
  8309. {
  8310. for (int i = numUsed; --i >= 0;)
  8311. if (! otherSet.contains (this->elements [i]))
  8312. remove (i);
  8313. }
  8314. }
  8315. lock.exit();
  8316. otherSet.lockSet();
  8317. }
  8318. /** Reduces the amount of storage being used by the set.
  8319. Sets typically allocate slightly more storage than they need, and after
  8320. removing elements, they may have quite a lot of unused space allocated.
  8321. This method will reduce the amount of allocated storage to a minimum.
  8322. */
  8323. void minimiseStorageOverheads() throw()
  8324. {
  8325. lock.enter();
  8326. if (numUsed == 0)
  8327. {
  8328. this->setAllocatedSize (0);
  8329. }
  8330. else
  8331. {
  8332. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8333. if (newAllocation < this->numAllocated)
  8334. this->setAllocatedSize (newAllocation);
  8335. }
  8336. lock.exit();
  8337. }
  8338. /** Locks the set's CriticalSection.
  8339. Of course if the type of section used is a DummyCriticalSection, this won't
  8340. have any effect.
  8341. @see unlockSet
  8342. */
  8343. void lockSet() const throw()
  8344. {
  8345. lock.enter();
  8346. }
  8347. /** Unlocks the set's CriticalSection.
  8348. Of course if the type of section used is a DummyCriticalSection, this won't
  8349. have any effect.
  8350. @see lockSet
  8351. */
  8352. void unlockSet() const throw()
  8353. {
  8354. lock.exit();
  8355. }
  8356. juce_UseDebuggingNewOperator
  8357. private:
  8358. int numUsed;
  8359. TypeOfCriticalSectionToUse lock;
  8360. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8361. {
  8362. this->ensureAllocatedSize (numUsed + 1);
  8363. ElementType* const insertPos = this->elements + indexToInsertAt;
  8364. const int numberToMove = numUsed - indexToInsertAt;
  8365. if (numberToMove > 0)
  8366. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8367. *insertPos = newElement;
  8368. ++numUsed;
  8369. }
  8370. };
  8371. #if JUCE_MSVC
  8372. #pragma warning (pop)
  8373. #endif
  8374. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8375. /********* End of inlined file: juce_SortedSet.h *********/
  8376. #endif
  8377. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8378. /********* Start of inlined file: juce_SparseSet.h *********/
  8379. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8380. #define __JUCE_SPARSESET_JUCEHEADER__
  8381. /**
  8382. Holds a set of primitive values, storing them as a set of ranges.
  8383. This container acts like a simple BitArray, but can efficiently hold large
  8384. continguous ranges of values. It's quite a specialised class, mostly useful
  8385. for things like keeping the set of selected rows in a listbox.
  8386. The type used as a template paramter must be an integer type, such as int, short,
  8387. int64, etc.
  8388. */
  8389. template <class Type>
  8390. class SparseSet
  8391. {
  8392. public:
  8393. /** Creates a new empty set. */
  8394. SparseSet() throw()
  8395. {
  8396. }
  8397. /** Creates a copy of another SparseSet. */
  8398. SparseSet (const SparseSet<Type>& other) throw()
  8399. : values (other.values)
  8400. {
  8401. }
  8402. /** Destructor. */
  8403. ~SparseSet() throw()
  8404. {
  8405. }
  8406. /** Clears the set. */
  8407. void clear() throw()
  8408. {
  8409. values.clear();
  8410. }
  8411. /** Checks whether the set is empty.
  8412. This is much quicker than using (size() == 0).
  8413. */
  8414. bool isEmpty() const throw()
  8415. {
  8416. return values.size() == 0;
  8417. }
  8418. /** Returns the number of values in the set.
  8419. Because of the way the data is stored, this method can take longer if there
  8420. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8421. are any items.
  8422. */
  8423. Type size() const throw()
  8424. {
  8425. Type num = 0;
  8426. for (int i = 0; i < values.size(); i += 2)
  8427. num += values[i + 1] - values[i];
  8428. return num;
  8429. }
  8430. /** Returns one of the values in the set.
  8431. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8432. @returns the value at this index, or 0 if it's out-of-range
  8433. */
  8434. Type operator[] (int index) const throw()
  8435. {
  8436. for (int i = 0; i < values.size(); i += 2)
  8437. {
  8438. const Type s = values.getUnchecked(i);
  8439. const Type e = values.getUnchecked(i + 1);
  8440. if (index < e - s)
  8441. return s + index;
  8442. index -= e - s;
  8443. }
  8444. return (Type) 0;
  8445. }
  8446. /** Checks whether a particular value is in the set. */
  8447. bool contains (const Type valueToLookFor) const throw()
  8448. {
  8449. bool on = false;
  8450. for (int i = 0; i < values.size(); ++i)
  8451. {
  8452. if (values.getUnchecked(i) > valueToLookFor)
  8453. return on;
  8454. on = ! on;
  8455. }
  8456. return false;
  8457. }
  8458. /** Returns the number of contiguous blocks of values.
  8459. @see getRange
  8460. */
  8461. int getNumRanges() const throw()
  8462. {
  8463. return values.size() >> 1;
  8464. }
  8465. /** Returns one of the contiguous ranges of values stored.
  8466. @param rangeIndex the index of the range to look up, between 0
  8467. and (getNumRanges() - 1)
  8468. @param startValue on return, the value at the start of the range
  8469. @param numValues on return, the number of values in the range
  8470. @see getTotalRange
  8471. */
  8472. bool getRange (const int rangeIndex,
  8473. Type& startValue,
  8474. Type& numValues) const throw()
  8475. {
  8476. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8477. {
  8478. startValue = values [rangeIndex << 1];
  8479. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8480. return true;
  8481. }
  8482. return false;
  8483. }
  8484. /** Returns the lowest and highest values in the set.
  8485. @see getRange
  8486. */
  8487. bool getTotalRange (Type& lowestValue,
  8488. Type& highestValue) const throw()
  8489. {
  8490. if (values.size() > 0)
  8491. {
  8492. lowestValue = values.getUnchecked (0);
  8493. highestValue = values.getUnchecked (values.size() - 1);
  8494. return true;
  8495. }
  8496. return false;
  8497. }
  8498. /** Adds a range of contiguous values to the set.
  8499. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8500. @param firstValue the start of the range of values to add
  8501. @param numValuesToAdd how many values to add
  8502. */
  8503. void addRange (const Type firstValue,
  8504. const Type numValuesToAdd) throw()
  8505. {
  8506. jassert (numValuesToAdd >= 0);
  8507. if (numValuesToAdd > 0)
  8508. {
  8509. removeRange (firstValue, numValuesToAdd);
  8510. IntegerElementComparator<Type> sorter;
  8511. values.addSorted (sorter, firstValue);
  8512. values.addSorted (sorter, firstValue + numValuesToAdd);
  8513. simplify();
  8514. }
  8515. }
  8516. /** Removes a range of values from the set.
  8517. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8518. @param firstValue the start of the range of values to remove
  8519. @param numValuesToRemove how many values to remove
  8520. */
  8521. void removeRange (const Type firstValue,
  8522. const Type numValuesToRemove) throw()
  8523. {
  8524. jassert (numValuesToRemove >= 0);
  8525. if (numValuesToRemove > 0
  8526. && firstValue < values.getLast())
  8527. {
  8528. const bool onAtStart = contains (firstValue - 1);
  8529. Type lastValue = firstValue + numValuesToRemove;
  8530. if (lastValue < firstValue) // possible if the signed arithmetic wraps around
  8531. lastValue = values.getLast();
  8532. const bool onAtEnd = contains (lastValue);
  8533. for (int i = values.size(); --i >= 0;)
  8534. {
  8535. if (values.getUnchecked(i) >= firstValue
  8536. && values.getUnchecked(i) <= lastValue)
  8537. {
  8538. values.remove (i);
  8539. }
  8540. }
  8541. IntegerElementComparator<Type> sorter;
  8542. if (onAtStart)
  8543. values.addSorted (sorter, firstValue);
  8544. if (onAtEnd)
  8545. values.addSorted (sorter, lastValue);
  8546. simplify();
  8547. }
  8548. }
  8549. /** Does an XOR of the values in a given range. */
  8550. void invertRange (const Type firstValue,
  8551. const Type numValues)
  8552. {
  8553. SparseSet newItems;
  8554. newItems.addRange (firstValue, numValues);
  8555. int i;
  8556. for (i = getNumRanges(); --i >= 0;)
  8557. {
  8558. const int start = values [i << 1];
  8559. const int end = values [(i << 1) + 1];
  8560. newItems.removeRange (start, end);
  8561. }
  8562. removeRange (firstValue, numValues);
  8563. for (i = newItems.getNumRanges(); --i >= 0;)
  8564. {
  8565. const int start = newItems.values [i << 1];
  8566. const int end = newItems.values [(i << 1) + 1];
  8567. addRange (start, end);
  8568. }
  8569. }
  8570. /** Checks whether any part of a given range overlaps any part of this one. */
  8571. bool overlapsRange (const Type firstValue,
  8572. const Type numValues) throw()
  8573. {
  8574. jassert (numValues >= 0);
  8575. if (numValues > 0)
  8576. {
  8577. for (int i = getNumRanges(); --i >= 0;)
  8578. {
  8579. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8580. return false;
  8581. if (firstValue + numValues > values.getUnchecked (i << 1))
  8582. return true;
  8583. }
  8584. }
  8585. return false;
  8586. }
  8587. /** Checks whether the whole of a given range is contained within this one. */
  8588. bool containsRange (const Type firstValue,
  8589. const Type numValues) throw()
  8590. {
  8591. jassert (numValues >= 0);
  8592. if (numValues > 0)
  8593. {
  8594. for (int i = getNumRanges(); --i >= 0;)
  8595. {
  8596. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8597. return false;
  8598. if (firstValue >= values.getUnchecked (i << 1)
  8599. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  8600. return true;
  8601. }
  8602. }
  8603. return false;
  8604. }
  8605. bool operator== (const SparseSet<Type>& other) throw()
  8606. {
  8607. return values == other.values;
  8608. }
  8609. bool operator!= (const SparseSet<Type>& other) throw()
  8610. {
  8611. return values != other.values;
  8612. }
  8613. juce_UseDebuggingNewOperator
  8614. private:
  8615. // alternating start/end values of ranges of values that are present.
  8616. Array<Type> values;
  8617. void simplify() throw()
  8618. {
  8619. jassert ((values.size() & 1) == 0);
  8620. for (int i = values.size(); --i > 0;)
  8621. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8622. values.removeRange (i - 1, 2);
  8623. }
  8624. };
  8625. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8626. /********* End of inlined file: juce_SparseSet.h *********/
  8627. #endif
  8628. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  8629. #endif
  8630. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  8631. #endif
  8632. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  8633. #endif
  8634. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8635. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  8636. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8637. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8638. /**
  8639. Searches through a the files in a directory, returning each file that is found.
  8640. A DirectoryIterator will search through a directory and its subdirectories using
  8641. a wildcard filepattern match.
  8642. If you may be finding a large number of files, this is better than
  8643. using File::findChildFiles() because it doesn't block while it finds them
  8644. all, and this is more memory-efficient.
  8645. It can also guess how far it's got using a wildly inaccurate algorithm.
  8646. */
  8647. class JUCE_API DirectoryIterator
  8648. {
  8649. public:
  8650. /** Creates a DirectoryIterator for a given directory.
  8651. After creating one of these, call its next() method to get the
  8652. first file - e.g. @code
  8653. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  8654. while (iter.next())
  8655. {
  8656. File theFileItFound (iter.getFile());
  8657. ... etc
  8658. }
  8659. @endcode
  8660. @param directory the directory to search in
  8661. @param isRecursive whether all the subdirectories should also be searched
  8662. @param wildCard the file pattern to match
  8663. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  8664. whether to look for files, directories, or both.
  8665. */
  8666. DirectoryIterator (const File& directory,
  8667. bool isRecursive,
  8668. const String& wildCard = JUCE_T("*"),
  8669. const int whatToLookFor = File::findFiles) throw();
  8670. /** Destructor. */
  8671. ~DirectoryIterator() throw();
  8672. /** Call this to move the iterator along to the next file.
  8673. @returns true if a file was found (you can then use getFile() to see what it was) - or
  8674. false if there are no more matching files.
  8675. */
  8676. bool next() throw();
  8677. /** Returns the file that the iterator is currently pointing at.
  8678. The result of this call is only valid after a call to next() has returned true.
  8679. */
  8680. const File getFile() const throw();
  8681. /** Returns a guess of how far through the search the iterator has got.
  8682. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  8683. very accurate.
  8684. */
  8685. float getEstimatedProgress() const throw();
  8686. juce_UseDebuggingNewOperator
  8687. private:
  8688. OwnedArray <File> filesFound;
  8689. OwnedArray <File> dirsFound;
  8690. String wildCard;
  8691. int index;
  8692. const int whatToLookFor;
  8693. DirectoryIterator* subIterator;
  8694. DirectoryIterator (const DirectoryIterator&);
  8695. const DirectoryIterator& operator= (const DirectoryIterator&);
  8696. };
  8697. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  8698. /********* End of inlined file: juce_DirectoryIterator.h *********/
  8699. #endif
  8700. #ifndef __JUCE_FILE_JUCEHEADER__
  8701. #endif
  8702. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8703. /********* Start of inlined file: juce_FileInputStream.h *********/
  8704. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8705. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8706. /**
  8707. An input stream that reads from a local file.
  8708. @see InputStream, FileOutputStream, File::createInputStream
  8709. */
  8710. class JUCE_API FileInputStream : public InputStream
  8711. {
  8712. public:
  8713. /** Creates a FileInputStream.
  8714. @param fileToRead the file to read from - if the file can't be accessed for some
  8715. reason, then the stream will just contain no data
  8716. */
  8717. FileInputStream (const File& fileToRead);
  8718. /** Destructor. */
  8719. ~FileInputStream();
  8720. const File& getFile() const throw() { return file; }
  8721. int64 getTotalLength();
  8722. int read (void* destBuffer, int maxBytesToRead);
  8723. bool isExhausted();
  8724. int64 getPosition();
  8725. bool setPosition (int64 pos);
  8726. juce_UseDebuggingNewOperator
  8727. private:
  8728. File file;
  8729. void* fileHandle;
  8730. int64 currentPosition, totalSize;
  8731. bool needToSeek;
  8732. };
  8733. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  8734. /********* End of inlined file: juce_FileInputStream.h *********/
  8735. #endif
  8736. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8737. /********* Start of inlined file: juce_FileOutputStream.h *********/
  8738. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8739. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8740. /**
  8741. An output stream that writes into a local file.
  8742. @see OutputStream, FileInputStream, File::createOutputStream
  8743. */
  8744. class JUCE_API FileOutputStream : public OutputStream
  8745. {
  8746. public:
  8747. /** Creates a FileOutputStream.
  8748. If the file doesn't exist, it will first be created. If the file can't be
  8749. created or opened, the failedToOpen() method will return
  8750. true.
  8751. If the file already exists when opened, the stream's write-postion will
  8752. be set to the end of the file. To overwrite an existing file,
  8753. use File::deleteFile() before opening the stream, or use setPosition(0)
  8754. after it's opened (although this won't truncate the file).
  8755. It's better to use File::createOutputStream() to create one of these, rather
  8756. than using the class directly.
  8757. */
  8758. FileOutputStream (const File& fileToWriteTo,
  8759. const int bufferSizeToUse = 16384);
  8760. /** Destructor. */
  8761. ~FileOutputStream();
  8762. /** Returns the file that this stream is writing to.
  8763. */
  8764. const File& getFile() const throw() { return file; }
  8765. /** Returns true if the stream couldn't be opened for some reason.
  8766. */
  8767. bool failedToOpen() const throw() { return fileHandle == 0; }
  8768. void flush();
  8769. int64 getPosition();
  8770. bool setPosition (int64 pos);
  8771. bool write (const void* data, int numBytes);
  8772. juce_UseDebuggingNewOperator
  8773. private:
  8774. File file;
  8775. void* fileHandle;
  8776. int64 currentPosition;
  8777. int bufferSize, bytesInBuffer;
  8778. char* buffer;
  8779. };
  8780. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  8781. /********* End of inlined file: juce_FileOutputStream.h *********/
  8782. #endif
  8783. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8784. /********* Start of inlined file: juce_FileSearchPath.h *********/
  8785. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  8786. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  8787. /**
  8788. Encapsulates a set of folders that make up a search path.
  8789. @see File
  8790. */
  8791. class JUCE_API FileSearchPath
  8792. {
  8793. public:
  8794. /** Creates an empty search path. */
  8795. FileSearchPath();
  8796. /** Creates a search path from a string of pathnames.
  8797. The path can be semicolon- or comma-separated, e.g.
  8798. "/foo/bar;/foo/moose;/fish/moose"
  8799. The separate folders are tokenised and added to the search path.
  8800. */
  8801. FileSearchPath (const String& path);
  8802. /** Creates a copy of another search path. */
  8803. FileSearchPath (const FileSearchPath& other);
  8804. /** Destructor. */
  8805. ~FileSearchPath();
  8806. /** Uses a string containing a list of pathnames to re-initialise this list.
  8807. This search path is cleared and the semicolon- or comma-separated folders
  8808. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  8809. */
  8810. const FileSearchPath& operator= (const String& path);
  8811. /** Returns the number of folders in this search path.
  8812. @see operator[]
  8813. */
  8814. int getNumPaths() const;
  8815. /** Returns one of the folders in this search path.
  8816. The file returned isn't guaranteed to actually be a valid directory.
  8817. @see getNumPaths
  8818. */
  8819. const File operator[] (const int index) const;
  8820. /** Returns the search path as a semicolon-separated list of directories. */
  8821. const String toString() const;
  8822. /** Adds a new directory to the search path.
  8823. The new directory is added to the end of the list if the insertIndex parameter is
  8824. less than zero, otherwise it is inserted at the given index.
  8825. */
  8826. void add (const File& directoryToAdd,
  8827. const int insertIndex = -1);
  8828. /** Adds a new directory to the search path if it's not already in there. */
  8829. void addIfNotAlreadyThere (const File& directoryToAdd);
  8830. /** Removes a directory from the search path. */
  8831. void remove (const int indexToRemove);
  8832. /** Merges another search path into this one.
  8833. This will remove any duplicate directories.
  8834. */
  8835. void addPath (const FileSearchPath& other);
  8836. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  8837. If the search is intended to be recursive, there's no point having nested folders in the search
  8838. path, because they'll just get searched twice and you'll get duplicate results.
  8839. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  8840. */
  8841. void removeRedundantPaths();
  8842. /** Removes any directories that don't actually exist. */
  8843. void removeNonExistentPaths();
  8844. /** Searches the path for a wildcard.
  8845. This will search all the directories in the search path in order, adding any
  8846. matching files to the results array.
  8847. @param results an array to append the results to
  8848. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  8849. return files, directories, or both.
  8850. @param searchRecursively whether to recursively search the subdirectories too
  8851. @param wildCardPattern a pattern to match against the filenames
  8852. @returns the number of files added to the array
  8853. @see File::findChildFiles
  8854. */
  8855. int findChildFiles (OwnedArray<File>& results,
  8856. const int whatToLookFor,
  8857. const bool searchRecursively,
  8858. const String& wildCardPattern = JUCE_T("*")) const;
  8859. /** Finds out whether a file is inside one of the path's directories.
  8860. This will return true if the specified file is a child of one of the
  8861. directories specified by this path. Note that this doesn't actually do any
  8862. searching or check that the files exist - it just looks at the pathnames
  8863. to work out whether the file would be inside a directory.
  8864. @param fileToCheck the file to look for
  8865. @param checkRecursively if true, then this will return true if the file is inside a
  8866. subfolder of one of the path's directories (at any depth). If false
  8867. it will only return true if the file is actually a direct child
  8868. of one of the directories.
  8869. @see File::isAChildOf
  8870. */
  8871. bool isFileInPath (const File& fileToCheck,
  8872. const bool checkRecursively) const;
  8873. juce_UseDebuggingNewOperator
  8874. private:
  8875. StringArray directories;
  8876. void init (const String& path);
  8877. };
  8878. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  8879. /********* End of inlined file: juce_FileSearchPath.h *********/
  8880. #endif
  8881. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8882. /********* Start of inlined file: juce_NamedPipe.h *********/
  8883. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  8884. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  8885. /**
  8886. A cross-process pipe that can have data written to and read from it.
  8887. Two or more processes can use these for inter-process communication.
  8888. @see InterprocessConnection
  8889. */
  8890. class JUCE_API NamedPipe
  8891. {
  8892. public:
  8893. /** Creates a NamedPipe. */
  8894. NamedPipe();
  8895. /** Destructor. */
  8896. ~NamedPipe();
  8897. /** Tries to open a pipe that already exists.
  8898. Returns true if it succeeds.
  8899. */
  8900. bool openExisting (const String& pipeName);
  8901. /** Tries to create a new pipe.
  8902. Returns true if it succeeds.
  8903. */
  8904. bool createNewPipe (const String& pipeName);
  8905. /** Closes the pipe, if it's open. */
  8906. void close();
  8907. /** True if the pipe is currently open. */
  8908. bool isOpen() const throw();
  8909. /** Returns the last name that was used to try to open this pipe. */
  8910. const String getName() const throw();
  8911. /** Reads data from the pipe.
  8912. This will block until another thread has written enough data into the pipe to fill
  8913. the number of bytes specified, or until another thread calls the cancelPendingReads()
  8914. method.
  8915. If the operation fails, it returns -1, otherwise, it will return the number of
  8916. bytes read.
  8917. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  8918. this is a maximum timeout for reading from the pipe.
  8919. */
  8920. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  8921. /** Writes some data to the pipe.
  8922. If the operation fails, it returns -1, otherwise, it will return the number of
  8923. bytes written.
  8924. */
  8925. int write (const void* sourceBuffer, int numBytesToWrite,
  8926. int timeOutMilliseconds = 2000);
  8927. /** If any threads are currently blocked on a read operation, this tells them to abort.
  8928. */
  8929. void cancelPendingReads();
  8930. juce_UseDebuggingNewOperator
  8931. private:
  8932. void* internal;
  8933. String currentPipeName;
  8934. NamedPipe (const NamedPipe&);
  8935. const NamedPipe& operator= (const NamedPipe&);
  8936. bool openInternal (const String& pipeName, const bool createPipe);
  8937. };
  8938. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  8939. /********* End of inlined file: juce_NamedPipe.h *********/
  8940. #endif
  8941. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8942. /********* Start of inlined file: juce_BlowFish.h *********/
  8943. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  8944. #define __JUCE_BLOWFISH_JUCEHEADER__
  8945. /**
  8946. BlowFish encryption class.
  8947. */
  8948. class JUCE_API BlowFish
  8949. {
  8950. public:
  8951. /** Creates an object that can encode/decode based on the specified key.
  8952. The key data can be up to 72 bytes long.
  8953. */
  8954. BlowFish (const uint8* keyData, int keyBytes);
  8955. /** Creates a copy of another blowfish object. */
  8956. BlowFish (const BlowFish& other);
  8957. /** Copies another blowfish object. */
  8958. const BlowFish& operator= (const BlowFish& other);
  8959. /** Destructor. */
  8960. ~BlowFish();
  8961. /** Encrypts a pair of 32-bit integers. */
  8962. void encrypt (uint32& data1, uint32& data2) const;
  8963. /** Decrypts a pair of 32-bit integers. */
  8964. void decrypt (uint32& data1, uint32& data2) const;
  8965. juce_UseDebuggingNewOperator
  8966. private:
  8967. uint32 p[18];
  8968. uint32* s[4];
  8969. uint32 F (uint32 x) const;
  8970. };
  8971. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  8972. /********* End of inlined file: juce_BlowFish.h *********/
  8973. #endif
  8974. #ifndef __JUCE_MD5_JUCEHEADER__
  8975. /********* Start of inlined file: juce_MD5.h *********/
  8976. #ifndef __JUCE_MD5_JUCEHEADER__
  8977. #define __JUCE_MD5_JUCEHEADER__
  8978. /**
  8979. MD5 checksum class.
  8980. Create one of these with a block of source data or a string, and it calculates the
  8981. MD5 checksum of that data.
  8982. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  8983. */
  8984. class JUCE_API MD5
  8985. {
  8986. public:
  8987. /** Creates a null MD5 object. */
  8988. MD5();
  8989. /** Creates a copy of another MD5. */
  8990. MD5 (const MD5& other);
  8991. /** Copies another MD5. */
  8992. const MD5& operator= (const MD5& other);
  8993. /** Creates a checksum for a block of binary data. */
  8994. MD5 (const MemoryBlock& data);
  8995. /** Creates a checksum for a block of binary data. */
  8996. MD5 (const char* data, const int numBytes);
  8997. /** Creates a checksum for a string.
  8998. Note that this operates on the string as a block of unicode characters, so the
  8999. result you get will differ from the value you'd get if the string was treated
  9000. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  9001. of this method with a checksum created by a different framework, which may have
  9002. used a different encoding.
  9003. */
  9004. MD5 (const String& text);
  9005. /** Creates a checksum for the input from a stream.
  9006. This will read up to the given number of bytes from the stream, and produce the
  9007. checksum of that. If the number of bytes to read is negative, it'll read
  9008. until the stream is exhausted.
  9009. */
  9010. MD5 (InputStream& input, int numBytesToRead = -1);
  9011. /** Creates a checksum for a file. */
  9012. MD5 (const File& file);
  9013. /** Destructor. */
  9014. ~MD5();
  9015. /** Returns the checksum as a 16-byte block of data. */
  9016. const MemoryBlock getRawChecksumData() const;
  9017. /** Returns the checksum as a 32-digit hex string. */
  9018. const String toHexString() const;
  9019. /** Compares this to another MD5. */
  9020. bool operator== (const MD5& other) const;
  9021. /** Compares this to another MD5. */
  9022. bool operator!= (const MD5& other) const;
  9023. juce_UseDebuggingNewOperator
  9024. private:
  9025. uint8 result [16];
  9026. struct ProcessContext
  9027. {
  9028. uint8 buffer [64];
  9029. uint32 state [4];
  9030. uint32 count [2];
  9031. ProcessContext();
  9032. void processBlock (const uint8* const data, int dataSize);
  9033. void transform (const uint8* const buffer);
  9034. void finish (uint8* const result);
  9035. };
  9036. void processStream (InputStream& input, int numBytesToRead);
  9037. };
  9038. #endif // __JUCE_MD5_JUCEHEADER__
  9039. /********* End of inlined file: juce_MD5.h *********/
  9040. #endif
  9041. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9042. /********* Start of inlined file: juce_Primes.h *********/
  9043. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9044. #define __JUCE_PRIMES_JUCEHEADER__
  9045. /**
  9046. Prime number creation class.
  9047. This class contains static methods for generating and testing prime numbers.
  9048. @see BitArray
  9049. */
  9050. class JUCE_API Primes
  9051. {
  9052. public:
  9053. /** Creates a random prime number with a given bit-length.
  9054. The certainty parameter specifies how many iterations to use when testing
  9055. for primality. A safe value might be anything over about 20-30.
  9056. The randomSeeds parameter lets you optionally pass it a set of values with
  9057. which to seed the random number generation, improving the security of the
  9058. keys generated.
  9059. */
  9060. static const BitArray createProbablePrime (int bitLength,
  9061. int certainty,
  9062. const int* randomSeeds = 0,
  9063. int numRandomSeeds = 0) throw();
  9064. /** Tests a number to see if it's prime.
  9065. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  9066. whether the number is prime.
  9067. The certainty parameter specifies how many iterations to use when testing - a
  9068. safe value might be anything over about 20-30.
  9069. */
  9070. static bool isProbablyPrime (const BitArray& number,
  9071. int certainty) throw();
  9072. };
  9073. #endif // __JUCE_PRIMES_JUCEHEADER__
  9074. /********* End of inlined file: juce_Primes.h *********/
  9075. #endif
  9076. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9077. /********* Start of inlined file: juce_RSAKey.h *********/
  9078. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9079. #define __JUCE_RSAKEY_JUCEHEADER__
  9080. /**
  9081. RSA public/private key-pair encryption class.
  9082. An object of this type makes up one half of a public/private RSA key pair. Use the
  9083. createKeyPair() method to create a matching pair for encoding/decoding.
  9084. */
  9085. class JUCE_API RSAKey
  9086. {
  9087. public:
  9088. /** Creates a null key object.
  9089. Initialise a pair of objects for use with the createKeyPair() method.
  9090. */
  9091. RSAKey() throw();
  9092. /** Loads a key from an encoded string representation.
  9093. This reloads a key from a string created by the toString() method.
  9094. */
  9095. RSAKey (const String& stringRepresentation) throw();
  9096. /** Destructor. */
  9097. ~RSAKey() throw();
  9098. /** Turns the key into a string representation.
  9099. This can be reloaded using the constructor that takes a string.
  9100. */
  9101. const String toString() const throw();
  9102. /** Encodes or decodes a value.
  9103. Call this on the public key object to encode some data, then use the matching
  9104. private key object to decode it.
  9105. Returns false if the operation failed, e.g. if this object isn't a valid key.
  9106. */
  9107. bool applyToValue (BitArray& value) const throw();
  9108. /** Creates a public/private key-pair.
  9109. Each key will perform one-way encryption that can only be reversed by
  9110. using the other key.
  9111. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  9112. sizes are more secure, but this method will take longer to execute.
  9113. The randomSeeds parameter lets you optionally pass it a set of values with
  9114. which to seed the random number generation, improving the security of the
  9115. keys generated.
  9116. */
  9117. static void createKeyPair (RSAKey& publicKey,
  9118. RSAKey& privateKey,
  9119. const int numBits,
  9120. const int* randomSeeds = 0,
  9121. const int numRandomSeeds = 0) throw();
  9122. juce_UseDebuggingNewOperator
  9123. protected:
  9124. BitArray part1, part2;
  9125. };
  9126. #endif // __JUCE_RSAKEY_JUCEHEADER__
  9127. /********* End of inlined file: juce_RSAKey.h *********/
  9128. #endif
  9129. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9130. /********* Start of inlined file: juce_Socket.h *********/
  9131. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9132. #define __JUCE_SOCKET_JUCEHEADER__
  9133. /**
  9134. A wrapper for a streaming (TCP) socket.
  9135. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9136. sockets, you could also try the InterprocessConnection class.
  9137. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  9138. */
  9139. class JUCE_API StreamingSocket
  9140. {
  9141. public:
  9142. /** Creates an uninitialised socket.
  9143. To connect it, use the connect() method, after which you can read() or write()
  9144. to it.
  9145. To wait for other sockets to connect to this one, the createListener() method
  9146. enters "listener" mode, and can be used to spawn new sockets for each connection
  9147. that comes along.
  9148. */
  9149. StreamingSocket();
  9150. /** Destructor. */
  9151. ~StreamingSocket();
  9152. /** Binds the socket to the specified local port.
  9153. @returns true on success; false may indicate that another socket is already bound
  9154. on the same port
  9155. */
  9156. bool bindToPort (const int localPortNumber);
  9157. /** Tries to connect the socket to hostname:port.
  9158. If timeOutMillisecs is 0, then this method will block until the operating system
  9159. rejects the connection (which could take a long time).
  9160. @returns true if it succeeds.
  9161. @see isConnected
  9162. */
  9163. bool connect (const String& remoteHostname,
  9164. const int remotePortNumber,
  9165. const int timeOutMillisecs = 3000);
  9166. /** True if the socket is currently connected. */
  9167. bool isConnected() const throw() { return connected; }
  9168. /** Closes the connection. */
  9169. void close();
  9170. /** Returns the name of the currently connected host. */
  9171. const String& getHostName() const throw() { return hostName; }
  9172. /** Returns the port number that's currently open. */
  9173. int getPort() const throw() { return portNumber; }
  9174. /** True if the socket is connected to this machine rather than over the network. */
  9175. bool isLocal() const throw();
  9176. /** Waits until the socket is ready for reading or writing.
  9177. If readyForReading is true, it will wait until the socket is ready for
  9178. reading; if false, it will wait until it's ready for writing.
  9179. If the timeout is < 0, it will wait forever, or else will give up after
  9180. the specified time.
  9181. If the socket is ready on return, this returns 1. If it times-out before
  9182. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9183. */
  9184. int waitUntilReady (const bool readyForReading,
  9185. const int timeoutMsecs) const;
  9186. /** Reads bytes from the socket (blocking).
  9187. Note that this method will block unless you have checked the socket is ready
  9188. for reading before calling it (see the waitUntilReady() method).
  9189. @returns the number of bytes read, or -1 if there was an error.
  9190. */
  9191. int read (void* destBuffer, const int maxBytesToRead);
  9192. /** Writes bytes to the socket from a buffer.
  9193. Note that this method will block unless you have checked the socket is ready
  9194. for writing before calling it (see the waitUntilReady() method).
  9195. @returns the number of bytes written, or -1 if there was an error.
  9196. */
  9197. int write (const void* sourceBuffer, const int numBytesToWrite);
  9198. /** Puts this socket into "listener" mode.
  9199. When in this mode, your thread can call waitForNextConnection() repeatedly,
  9200. which will spawn new sockets for each new connection, so that these can
  9201. be handled in parallel by other threads.
  9202. This returns true if it manages to open the socket successfully.
  9203. @see waitForNextConnection
  9204. */
  9205. bool createListener (const int portNumber);
  9206. /** When in "listener" mode, this waits for a connection and spawns it as a new
  9207. socket.
  9208. The object that gets returned will be owned by the caller.
  9209. This method can only be called after using createListener().
  9210. @see createListener
  9211. */
  9212. StreamingSocket* waitForNextConnection() const;
  9213. juce_UseDebuggingNewOperator
  9214. private:
  9215. String hostName;
  9216. int volatile portNumber, handle;
  9217. bool connected, isListener;
  9218. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  9219. StreamingSocket (const StreamingSocket&);
  9220. const StreamingSocket& operator= (const StreamingSocket&);
  9221. };
  9222. /**
  9223. A wrapper for a datagram (UDP) socket.
  9224. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9225. sockets, you could also try the InterprocessConnection class.
  9226. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  9227. */
  9228. class JUCE_API DatagramSocket
  9229. {
  9230. public:
  9231. /**
  9232. Creates an (uninitialised) datagram socket.
  9233. The localPortNumber is the port on which to bind this socket. If this value is 0,
  9234. the port number is assigned by the operating system.
  9235. To use the socket for sending, call the connect() method. This will not immediately
  9236. make a connection, but will save the destination you've provided. After this, you can
  9237. call read() or write().
  9238. To wait for other sockets to connect to this one, call waitForNextConnection().
  9239. */
  9240. DatagramSocket (const int localPortNumber);
  9241. /** Destructor. */
  9242. ~DatagramSocket();
  9243. /** Binds the socket to the specified local port.
  9244. @returns true on success; false may indicate that another socket is already bound
  9245. on the same port
  9246. */
  9247. bool bindToPort (const int localPortNumber);
  9248. /** Tries to connect the socket to hostname:port.
  9249. If timeOutMillisecs is 0, then this method will block until the operating system
  9250. rejects the connection (which could take a long time).
  9251. @returns true if it succeeds.
  9252. @see isConnected
  9253. */
  9254. bool connect (const String& remoteHostname,
  9255. const int remotePortNumber,
  9256. const int timeOutMillisecs = 3000);
  9257. /** True if the socket is currently connected. */
  9258. bool isConnected() const throw() { return connected; }
  9259. /** Closes the connection. */
  9260. void close();
  9261. /** Returns the name of the currently connected host. */
  9262. const String& getHostName() const throw() { return hostName; }
  9263. /** Returns the port number that's currently open. */
  9264. int getPort() const throw() { return portNumber; }
  9265. /** True if the socket is connected to this machine rather than over the network. */
  9266. bool isLocal() const throw();
  9267. /** Waits until the socket is ready for reading or writing.
  9268. If readyForReading is true, it will wait until the socket is ready for
  9269. reading; if false, it will wait until it's ready for writing.
  9270. If the timeout is < 0, it will wait forever, or else will give up after
  9271. the specified time.
  9272. If the socket is ready on return, this returns 1. If it times-out before
  9273. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9274. */
  9275. int waitUntilReady (const bool readyForReading,
  9276. const int timeoutMsecs) const;
  9277. /** Reads bytes from the socket (blocking).
  9278. Note that this method will block unless you have checked the socket is ready
  9279. for reading before calling it (see the waitUntilReady() method).
  9280. @returns the number of bytes read, or -1 if there was an error.
  9281. */
  9282. int read (void* destBuffer, const int maxBytesToRead);
  9283. /** Writes bytes to the socket from a buffer.
  9284. Note that this method will block unless you have checked the socket is ready
  9285. for writing before calling it (see the waitUntilReady() method).
  9286. @returns the number of bytes written, or -1 if there was an error.
  9287. */
  9288. int write (const void* sourceBuffer, const int numBytesToWrite);
  9289. /** This waits for incoming data to be sent, and returns a socket that can be used
  9290. to read it.
  9291. The object that gets returned is owned by the caller, and can't be used for
  9292. sending, but can be used to read the data.
  9293. */
  9294. DatagramSocket* waitForNextConnection() const;
  9295. juce_UseDebuggingNewOperator
  9296. private:
  9297. String hostName;
  9298. int volatile portNumber, handle;
  9299. bool connected;
  9300. void* serverAddress;
  9301. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  9302. DatagramSocket (const DatagramSocket&);
  9303. const DatagramSocket& operator= (const DatagramSocket&);
  9304. };
  9305. #endif // __JUCE_SOCKET_JUCEHEADER__
  9306. /********* End of inlined file: juce_Socket.h *********/
  9307. #endif
  9308. #ifndef __JUCE_URL_JUCEHEADER__
  9309. /********* Start of inlined file: juce_URL.h *********/
  9310. #ifndef __JUCE_URL_JUCEHEADER__
  9311. #define __JUCE_URL_JUCEHEADER__
  9312. /**
  9313. Represents a URL and has a bunch of useful functions to manipulate it.
  9314. This class can be used to launch URLs in browsers, and also to create
  9315. InputStreams that can read from remote http or ftp sources.
  9316. */
  9317. class JUCE_API URL
  9318. {
  9319. public:
  9320. /** Creates an empty URL. */
  9321. URL() throw();
  9322. /** Creates a URL from a string. */
  9323. URL (const String& url);
  9324. /** Creates a copy of another URL. */
  9325. URL (const URL& other);
  9326. /** Destructor. */
  9327. ~URL() throw();
  9328. /** Copies this URL from another one. */
  9329. const URL& operator= (const URL& other);
  9330. /** Returns a string version of the URL.
  9331. If includeGetParameters is true and any parameters have been set with the
  9332. withParameter() method, then the string will have these appended on the
  9333. end and url-encoded.
  9334. */
  9335. const String toString (const bool includeGetParameters) const;
  9336. /** True if it seems to be valid. */
  9337. bool isWellFormed() const;
  9338. /** Returns a copy of this URL, with a GET parameter added to the end.
  9339. Any control characters in the value will be encoded.
  9340. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  9341. would produce a new url whose toString(true) method would return
  9342. "www.fish.com?amount=some+fish".
  9343. */
  9344. const URL withParameter (const String& parameterName,
  9345. const String& parameterValue) const;
  9346. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  9347. When performing a POST where one of your parameters is a binary file, this
  9348. lets you specify the file.
  9349. Note that the filename is stored, but the file itself won't actually be read
  9350. until this URL is later used to create a network input stream.
  9351. */
  9352. const URL withFileToUpload (const String& parameterName,
  9353. const File& fileToUpload,
  9354. const String& mimeType) const;
  9355. /** Returns a set of all the parameters encoded into the url.
  9356. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  9357. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  9358. The values returned will have been cleaned up to remove any escape characters.
  9359. @see getNamedParameter, withParameter
  9360. */
  9361. const StringPairArray& getParameters() const throw();
  9362. /** Returns the set of files that should be uploaded as part of a POST operation.
  9363. This is the set of files that were added to the URL with the withFileToUpload()
  9364. method.
  9365. */
  9366. const StringPairArray& getFilesToUpload() const throw();
  9367. /** Returns the set of mime types associated with each of the upload files.
  9368. */
  9369. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  9370. /** Returns a copy of this URL, with a block of data to send as the POST data.
  9371. If you're setting the POST data, be careful not to have any parameters set
  9372. as well, otherwise it'll all get thrown in together, and might not have the
  9373. desired effect.
  9374. If the URL already contains some POST data, this will replace it, rather
  9375. than being appended to it.
  9376. This data will only be used if you specify a post operation when you call
  9377. createInputStream().
  9378. */
  9379. const URL withPOSTData (const String& postData) const;
  9380. /** Returns the data that was set using withPOSTData().
  9381. */
  9382. const String getPostData() const throw() { return postData; }
  9383. /** Tries to launch the system's default browser to open the URL.
  9384. Returns true if this seems to have worked.
  9385. */
  9386. bool launchInDefaultBrowser() const;
  9387. /** Takes a guess as to whether a string might be a valid website address.
  9388. This isn't foolproof!
  9389. */
  9390. static bool isProbablyAWebsiteURL (const String& possibleURL);
  9391. /** Takes a guess as to whether a string might be a valid email address.
  9392. This isn't foolproof!
  9393. */
  9394. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  9395. /** This callback function can be used by the createInputStream() method.
  9396. It allows your app to receive progress updates during a lengthy POST operation. If you
  9397. want to continue the operation, this should return true, or false to abort.
  9398. */
  9399. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  9400. /** Attempts to open a stream that can read from this URL.
  9401. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  9402. the paramters, otherwise it'll encode them into the
  9403. URL and do a 'GET'.
  9404. @param progressCallback if this is non-zero, it lets you supply a callback function
  9405. to keep track of the operation's progress. This can be useful
  9406. for lengthy POST operations, so that you can provide user feedback.
  9407. @param progressCallbackContext if a callback is specified, this value will be passed to
  9408. the function
  9409. @param extraHeaders if not empty, this string is appended onto the headers that
  9410. are used for the request. It must therefore be a valid set of HTML
  9411. header directives, separated by newlines.
  9412. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  9413. a negative number, it will be infinite. Otherwise it specifies a
  9414. time in milliseconds.
  9415. */
  9416. InputStream* createInputStream (const bool usePostCommand,
  9417. OpenStreamProgressCallback* const progressCallback = 0,
  9418. void* const progressCallbackContext = 0,
  9419. const String& extraHeaders = String::empty,
  9420. const int connectionTimeOutMs = 0) const;
  9421. /** Tries to download the entire contents of this URL into a binary data block.
  9422. If it succeeds, this will return true and append the data it read onto the end
  9423. of the memory block.
  9424. @param destData the memory block to append the new data to
  9425. @param usePostCommand whether to use a POST command to get the data (uses
  9426. a GET command if this is false)
  9427. @see readEntireTextStream, readEntireXmlStream
  9428. */
  9429. bool readEntireBinaryStream (MemoryBlock& destData,
  9430. const bool usePostCommand = false) const;
  9431. /** Tries to download the entire contents of this URL as a string.
  9432. If it fails, this will return an empty string, otherwise it will return the
  9433. contents of the downloaded file. If you need to distinguish between a read
  9434. operation that fails and one that returns an empty string, you'll need to use
  9435. a different method, such as readEntireBinaryStream().
  9436. @param usePostCommand whether to use a POST command to get the data (uses
  9437. a GET command if this is false)
  9438. @see readEntireBinaryStream, readEntireXmlStream
  9439. */
  9440. const String readEntireTextStream (const bool usePostCommand = false) const;
  9441. /** Tries to download the entire contents of this URL and parse it as XML.
  9442. If it fails, or if the text that it reads can't be parsed as XML, this will
  9443. return 0.
  9444. When it returns a valid XmlElement object, the caller is responsibile for deleting
  9445. this object when no longer needed.
  9446. @param usePostCommand whether to use a POST command to get the data (uses
  9447. a GET command if this is false)
  9448. @see readEntireBinaryStream, readEntireTextStream
  9449. */
  9450. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  9451. /** Adds escape sequences to a string to encode any characters that aren't
  9452. legal in a URL.
  9453. E.g. any spaces will be replaced with "%20".
  9454. This is the opposite of removeEscapeChars().
  9455. If isParameter is true, it means that the string is going to be used
  9456. as a parameter, so it also encodes '$' and ',' (which would otherwise
  9457. be legal in a URL.
  9458. @see removeEscapeChars
  9459. */
  9460. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  9461. const bool isParameter);
  9462. /** Replaces any escape character sequences in a string with their original
  9463. character codes.
  9464. E.g. any instances of "%20" will be replaced by a space.
  9465. This is the opposite of addEscapeChars().
  9466. @see addEscapeChars
  9467. */
  9468. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  9469. juce_UseDebuggingNewOperator
  9470. private:
  9471. String url, postData;
  9472. StringPairArray parameters, filesToUpload, mimeTypes;
  9473. };
  9474. #endif // __JUCE_URL_JUCEHEADER__
  9475. /********* End of inlined file: juce_URL.h *********/
  9476. #endif
  9477. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9478. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  9479. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9480. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9481. /** Wraps another input stream, and reads from it using an intermediate buffer
  9482. If you're using an input stream such as a file input stream, and making lots of
  9483. small read accesses to it, it's probably sensible to wrap it in one of these,
  9484. so that the source stream gets accessed in larger chunk sizes, meaning less
  9485. work for the underlying stream.
  9486. */
  9487. class JUCE_API BufferedInputStream : public InputStream
  9488. {
  9489. public:
  9490. /** Creates a BufferedInputStream from an input source.
  9491. @param sourceStream the source stream to read from
  9492. @param bufferSize the size of reservoir to use to buffer the source
  9493. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9494. deleted by this object when it is itself deleted.
  9495. */
  9496. BufferedInputStream (InputStream* const sourceStream,
  9497. const int bufferSize,
  9498. const bool deleteSourceWhenDestroyed) throw();
  9499. /** Destructor.
  9500. This may also delete the source stream, if that option was chosen when the
  9501. buffered stream was created.
  9502. */
  9503. ~BufferedInputStream() throw();
  9504. int64 getTotalLength();
  9505. int64 getPosition();
  9506. bool setPosition (int64 newPosition);
  9507. int read (void* destBuffer, int maxBytesToRead);
  9508. const String readString();
  9509. bool isExhausted();
  9510. juce_UseDebuggingNewOperator
  9511. private:
  9512. InputStream* const source;
  9513. const bool deleteSourceWhenDestroyed;
  9514. int bufferSize;
  9515. int64 position, lastReadPos, bufferStart, bufferOverlap;
  9516. char* buffer;
  9517. void ensureBuffered();
  9518. BufferedInputStream (const BufferedInputStream&);
  9519. const BufferedInputStream& operator= (const BufferedInputStream&);
  9520. };
  9521. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  9522. /********* End of inlined file: juce_BufferedInputStream.h *********/
  9523. #endif
  9524. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9525. /********* Start of inlined file: juce_FileInputSource.h *********/
  9526. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9527. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9528. /********* Start of inlined file: juce_InputSource.h *********/
  9529. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9530. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9531. /**
  9532. A lightweight object that can create a stream to read some kind of resource.
  9533. This may be used to refer to a file, or some other kind of source, allowing a
  9534. caller to create an input stream that can read from it when required.
  9535. @see FileInputSource
  9536. */
  9537. class JUCE_API InputSource
  9538. {
  9539. public:
  9540. InputSource() throw() {}
  9541. /** Destructor. */
  9542. virtual ~InputSource() {}
  9543. /** Returns a new InputStream to read this item.
  9544. @returns an inputstream that the caller will delete, or 0 if
  9545. the filename isn't found.
  9546. */
  9547. virtual InputStream* createInputStream() = 0;
  9548. /** Returns a new InputStream to read an item, relative.
  9549. @param relatedItemPath the relative pathname of the resource that is required
  9550. @returns an inputstream that the caller will delete, or 0 if
  9551. the item isn't found.
  9552. */
  9553. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9554. /** Returns a hash code that uniquely represents this item.
  9555. */
  9556. virtual int64 hashCode() const = 0;
  9557. juce_UseDebuggingNewOperator
  9558. };
  9559. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9560. /********* End of inlined file: juce_InputSource.h *********/
  9561. /**
  9562. A type of InputSource that represents a normal file.
  9563. @see InputSource
  9564. */
  9565. class JUCE_API FileInputSource : public InputSource
  9566. {
  9567. public:
  9568. FileInputSource (const File& file) throw();
  9569. ~FileInputSource();
  9570. InputStream* createInputStream();
  9571. InputStream* createInputStreamFor (const String& relatedItemPath);
  9572. int64 hashCode() const;
  9573. juce_UseDebuggingNewOperator
  9574. private:
  9575. const File file;
  9576. FileInputSource (const FileInputSource&);
  9577. const FileInputSource& operator= (const FileInputSource&);
  9578. };
  9579. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  9580. /********* End of inlined file: juce_FileInputSource.h *********/
  9581. #endif
  9582. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9583. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9584. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9585. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9586. /**
  9587. A stream which uses zlib to compress the data written into it.
  9588. @see GZIPDecompressorInputStream
  9589. */
  9590. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  9591. {
  9592. public:
  9593. /** Creates a compression stream.
  9594. @param destStream the stream into which the compressed data should
  9595. be written
  9596. @param compressionLevel how much to compress the data, between 1 and 9, where
  9597. 1 is the fastest/lowest compression, and 9 is the
  9598. slowest/highest compression. Any value outside this range
  9599. indicates that a default compression level should be used.
  9600. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  9601. this stream is destroyed
  9602. @param noWrap this is used internally by the ZipFile class
  9603. and should be ignored by user applications
  9604. */
  9605. GZIPCompressorOutputStream (OutputStream* const destStream,
  9606. int compressionLevel = 0,
  9607. const bool deleteDestStreamWhenDestroyed = false,
  9608. const bool noWrap = false);
  9609. /** Destructor. */
  9610. ~GZIPCompressorOutputStream();
  9611. void flush();
  9612. int64 getPosition();
  9613. bool setPosition (int64 newPosition);
  9614. bool write (const void* destBuffer, int howMany);
  9615. juce_UseDebuggingNewOperator
  9616. private:
  9617. OutputStream* const destStream;
  9618. const bool deleteDestStream;
  9619. uint8* buffer;
  9620. void* helper;
  9621. bool doNextBlock();
  9622. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  9623. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  9624. };
  9625. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  9626. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  9627. #endif
  9628. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9629. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9630. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9631. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9632. /**
  9633. This stream will decompress a source-stream using zlib.
  9634. Tip: if you're reading lots of small items from one of these streams, you
  9635. can increase the performance enormously by passing it through a
  9636. BufferedInputStream, so that it has to read larger blocks less often.
  9637. @see GZIPCompressorOutputStream
  9638. */
  9639. class JUCE_API GZIPDecompressorInputStream : public InputStream
  9640. {
  9641. public:
  9642. /** Creates a decompressor stream.
  9643. @param sourceStream the stream to read from
  9644. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  9645. when this object is destroyed
  9646. @param noWrap this is used internally by the ZipFile class
  9647. and should be ignored by user applications
  9648. @param uncompressedStreamLength if the creator knows the length that the
  9649. uncompressed stream will be, then it can supply this
  9650. value, which will be returned by getTotalLength()
  9651. */
  9652. GZIPDecompressorInputStream (InputStream* const sourceStream,
  9653. const bool deleteSourceWhenDestroyed,
  9654. const bool noWrap = false,
  9655. const int64 uncompressedStreamLength = -1);
  9656. /** Destructor. */
  9657. ~GZIPDecompressorInputStream();
  9658. int64 getPosition();
  9659. bool setPosition (int64 pos);
  9660. int64 getTotalLength();
  9661. bool isExhausted();
  9662. int read (void* destBuffer, int maxBytesToRead);
  9663. juce_UseDebuggingNewOperator
  9664. private:
  9665. InputStream* const sourceStream;
  9666. const int64 uncompressedStreamLength;
  9667. const bool deleteSourceWhenDestroyed, noWrap;
  9668. bool isEof;
  9669. int activeBufferSize;
  9670. int64 originalSourcePos, currentPos;
  9671. uint8* buffer;
  9672. void* helper;
  9673. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  9674. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  9675. };
  9676. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  9677. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  9678. #endif
  9679. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9680. #endif
  9681. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9682. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  9683. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9684. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9685. /**
  9686. Allows a block of data and to be accessed as a stream.
  9687. This can either be used to refer to a shared block of memory, or can make its
  9688. own internal copy of the data when the MemoryInputStream is created.
  9689. */
  9690. class JUCE_API MemoryInputStream : public InputStream
  9691. {
  9692. public:
  9693. /** Creates a MemoryInputStream.
  9694. @param sourceData the block of data to use as the stream's source
  9695. @param sourceDataSize the number of bytes in the source data block
  9696. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  9697. the source data, so this data shouldn't be changed
  9698. for the lifetime of the stream; if this parameter is
  9699. true, the stream will make its own copy of the
  9700. data and use that.
  9701. */
  9702. MemoryInputStream (const void* const sourceData,
  9703. const int sourceDataSize,
  9704. const bool keepInternalCopyOfData) throw();
  9705. /** Destructor. */
  9706. ~MemoryInputStream() throw();
  9707. int64 getPosition();
  9708. bool setPosition (int64 pos);
  9709. int64 getTotalLength();
  9710. bool isExhausted();
  9711. int read (void* destBuffer, int maxBytesToRead);
  9712. juce_UseDebuggingNewOperator
  9713. private:
  9714. const char* data;
  9715. int dataSize, position;
  9716. MemoryBlock internalCopy;
  9717. };
  9718. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  9719. /********* End of inlined file: juce_MemoryInputStream.h *********/
  9720. #endif
  9721. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9722. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  9723. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9724. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9725. /** Writes data to an internal memory buffer, which grows as required.
  9726. The data that was written into the stream can then be accessed later as
  9727. a contiguous block of memory.
  9728. */
  9729. class JUCE_API MemoryOutputStream : public OutputStream
  9730. {
  9731. public:
  9732. /** Creates a memory stream ready for writing into.
  9733. @param initialSize the intial amount of space to allocate for writing into
  9734. @param granularity the increments by which the internal storage will be increased
  9735. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  9736. place that the data gets stored. If it's zero, the stream
  9737. will allocate its own storage internally, which you can
  9738. access using getData() and getDataSize()
  9739. */
  9740. MemoryOutputStream (const int initialSize = 256,
  9741. const int granularity = 256,
  9742. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  9743. /** Destructor.
  9744. This will free any data that was written to it.
  9745. */
  9746. ~MemoryOutputStream() throw();
  9747. /** Returns a pointer to the data that has been written to the stream.
  9748. @see getDataSize
  9749. */
  9750. const char* getData() throw();
  9751. /** Returns the number of bytes of data that have been written to the stream.
  9752. @see getData
  9753. */
  9754. int getDataSize() const throw();
  9755. /** Resets the stream, clearing any data that has been written to it so far. */
  9756. void reset() throw();
  9757. void flush();
  9758. bool write (const void* buffer, int howMany);
  9759. int64 getPosition();
  9760. bool setPosition (int64 newPosition);
  9761. juce_UseDebuggingNewOperator
  9762. private:
  9763. MemoryBlock* data;
  9764. int position, size, blockSize;
  9765. bool ownsMemoryBlock;
  9766. };
  9767. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  9768. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  9769. #endif
  9770. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9771. /********* Start of inlined file: juce_SubregionStream.h *********/
  9772. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9773. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9774. /** Wraps another input stream, and reads from a specific part of it.
  9775. This lets you take a subsection of a stream and present it as an entire
  9776. stream in its own right.
  9777. */
  9778. class JUCE_API SubregionStream : public InputStream
  9779. {
  9780. public:
  9781. /** Creates a SubregionStream from an input source.
  9782. @param sourceStream the source stream to read from
  9783. @param startPositionInSourceStream this is the position in the source stream that
  9784. corresponds to position 0 in this stream
  9785. @param lengthOfSourceStream this specifies the maximum number of bytes
  9786. from the source stream that will be passed through
  9787. by this stream. When the position of this stream
  9788. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  9789. If the length passed in here is greater than the length
  9790. of the source stream (as returned by getTotalLength()),
  9791. then the smaller value will be used.
  9792. Passing a negative value for this parameter means it
  9793. will keep reading until the source's end-of-stream.
  9794. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  9795. deleted by this object when it is itself deleted.
  9796. */
  9797. SubregionStream (InputStream* const sourceStream,
  9798. const int64 startPositionInSourceStream,
  9799. const int64 lengthOfSourceStream,
  9800. const bool deleteSourceWhenDestroyed) throw();
  9801. /** Destructor.
  9802. This may also delete the source stream, if that option was chosen when the
  9803. buffered stream was created.
  9804. */
  9805. ~SubregionStream() throw();
  9806. int64 getTotalLength();
  9807. int64 getPosition();
  9808. bool setPosition (int64 newPosition);
  9809. int read (void* destBuffer, int maxBytesToRead);
  9810. bool isExhausted();
  9811. juce_UseDebuggingNewOperator
  9812. private:
  9813. InputStream* const source;
  9814. const bool deleteSourceWhenDestroyed;
  9815. const int64 startPositionInSourceStream, lengthOfSourceStream;
  9816. SubregionStream (const SubregionStream&);
  9817. const SubregionStream& operator= (const SubregionStream&);
  9818. };
  9819. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  9820. /********* End of inlined file: juce_SubregionStream.h *********/
  9821. #endif
  9822. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9823. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  9824. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9825. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9826. /** A timer for measuring performance of code and dumping the results to a file.
  9827. e.g. @code
  9828. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  9829. for (;;)
  9830. {
  9831. pc.start();
  9832. doSomethingFishy();
  9833. pc.stop();
  9834. }
  9835. @endcode
  9836. In this example, the time of each period between calling start/stop will be
  9837. measured and averaged over 50 runs, and the results printed to a file
  9838. every 50 times round the loop.
  9839. */
  9840. class JUCE_API PerformanceCounter
  9841. {
  9842. public:
  9843. /** Creates a PerformanceCounter object.
  9844. @param counterName the name used when printing out the statistics
  9845. @param runsPerPrintout the number of start/stop iterations before calling
  9846. printStatistics()
  9847. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  9848. the results are just written to the debugger output
  9849. */
  9850. PerformanceCounter (const String& counterName,
  9851. int runsPerPrintout = 100,
  9852. const File& loggingFile = File::nonexistent);
  9853. /** Destructor. */
  9854. ~PerformanceCounter();
  9855. /** Starts timing.
  9856. @see stop
  9857. */
  9858. void start();
  9859. /** Stops timing and prints out the results.
  9860. The number of iterations before doing a printout of the
  9861. results is set in the constructor.
  9862. @see start
  9863. */
  9864. void stop();
  9865. /** Dumps the current metrics to the debugger output and to a file.
  9866. As well as using Logger::outputDebugString to print the results,
  9867. this will write then to the file specified in the constructor (if
  9868. this was valid).
  9869. */
  9870. void printStatistics();
  9871. juce_UseDebuggingNewOperator
  9872. private:
  9873. String name;
  9874. int numRuns, runsPerPrint;
  9875. double totalTime;
  9876. int64 started;
  9877. File outputFile;
  9878. };
  9879. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9880. /********* End of inlined file: juce_PerformanceCounter.h *********/
  9881. #endif
  9882. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9883. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  9884. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9885. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9886. /**
  9887. A collection of miscellaneous platform-specific utilities.
  9888. */
  9889. class JUCE_API PlatformUtilities
  9890. {
  9891. public:
  9892. /** Plays the operating system's default alert 'beep' sound. */
  9893. static void beep();
  9894. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  9895. const String& emailSubject,
  9896. const String& bodyText,
  9897. const StringArray& filesToAttach);
  9898. #if JUCE_MAC || DOXYGEN
  9899. /** MAC ONLY - Turns a Core CF String into a juce one. */
  9900. static const String cfStringToJuceString (CFStringRef cfString);
  9901. /** MAC ONLY - Turns a juce string into a Core CF one. */
  9902. static CFStringRef juceStringToCFString (const String& s);
  9903. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  9904. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  9905. /** MAC ONLY - Turns an FSRef into a juce string path. */
  9906. static const String makePathFromFSRef (FSRef* file);
  9907. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  9908. their precomposed equivalents.
  9909. */
  9910. static const String convertToPrecomposedUnicode (const String& s);
  9911. /** MAC ONLY - Gets the type of a file from the file's resources. */
  9912. static OSType getTypeOfFile (const String& filename);
  9913. /** MAC ONLY - Returns true if this file is actually a bundle. */
  9914. static bool isBundle (const String& filename);
  9915. #endif
  9916. #if JUCE_WIN32 || DOXYGEN
  9917. // Some registry helper functions:
  9918. /** WIN32 ONLY - Returns a string from the registry.
  9919. The path is a string for the entire path of a value in the registry,
  9920. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  9921. */
  9922. static const String getRegistryValue (const String& regValuePath,
  9923. const String& defaultValue = String::empty);
  9924. /** WIN32 ONLY - Sets a registry value as a string.
  9925. This will take care of creating any groups needed to get to the given
  9926. registry value.
  9927. */
  9928. static void setRegistryValue (const String& regValuePath,
  9929. const String& value);
  9930. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  9931. static bool registryValueExists (const String& regValuePath);
  9932. /** WIN32 ONLY - Deletes a registry value. */
  9933. static void deleteRegistryValue (const String& regValuePath);
  9934. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  9935. static void deleteRegistryKey (const String& regKeyPath);
  9936. /** WIN32 ONLY - Creates a file association in the registry.
  9937. This lets you set the exe that should be launched by a given file extension.
  9938. @param fileExtension the file extension to associate, including the
  9939. initial dot, e.g. ".txt"
  9940. @param symbolicDescription a space-free short token to identify the file type
  9941. @param fullDescription a human-readable description of the file type
  9942. @param targetExecutable the executable that should be launched
  9943. @param iconResourceNumber the icon that gets displayed for the file type will be
  9944. found by looking up this resource number in the
  9945. executable. Pass 0 here to not use an icon
  9946. */
  9947. static void registerFileAssociation (const String& fileExtension,
  9948. const String& symbolicDescription,
  9949. const String& fullDescription,
  9950. const File& targetExecutable,
  9951. int iconResourceNumber);
  9952. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  9953. In a normal Juce application this will be set to the module handle
  9954. of the application executable.
  9955. If you're writing a DLL using Juce and plan to use any Juce messaging or
  9956. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  9957. to set the correct module handle in your DllMain() function, because
  9958. the win32 system relies on the correct instance handle when opening windows.
  9959. */
  9960. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  9961. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  9962. @see getCurrentModuleInstanceHandle()
  9963. */
  9964. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  9965. /** WIN32 ONLY - Gets the command-line params as a string.
  9966. This is needed to avoid unicode problems with the argc type params.
  9967. */
  9968. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  9969. #endif
  9970. /** Clears the floating point unit's flags.
  9971. Only has an effect under win32, currently.
  9972. */
  9973. static void fpuReset();
  9974. #if JUCE_LINUX || JUCE_WIN32
  9975. /** Loads a dynamically-linked library into the process's address space.
  9976. @param pathOrFilename the platform-dependent name and search path
  9977. @returns a handle which can be used by getProcedureEntryPoint(), or
  9978. zero if it fails.
  9979. @see freeDynamicLibrary, getProcedureEntryPoint
  9980. */
  9981. static void* loadDynamicLibrary (const String& pathOrFilename);
  9982. /** Frees a dynamically-linked library.
  9983. @param libraryHandle a handle created by loadDynamicLibrary
  9984. @see loadDynamicLibrary, getProcedureEntryPoint
  9985. */
  9986. static void freeDynamicLibrary (void* libraryHandle);
  9987. /** Finds a procedure call in a dynamically-linked library.
  9988. @param libraryHandle a library handle returned by loadDynamicLibrary
  9989. @param procedureName the name of the procedure call to try to load
  9990. @returns a pointer to the function if found, or 0 if it fails
  9991. @see loadDynamicLibrary
  9992. */
  9993. static void* getProcedureEntryPoint (void* libraryHandle,
  9994. const String& procedureName);
  9995. #endif
  9996. #if JUCE_LINUX || DOXYGEN
  9997. #endif
  9998. };
  9999. #if JUCE_MAC
  10000. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10001. using RAII.
  10002. */
  10003. class ScopedAutoReleasePool
  10004. {
  10005. public:
  10006. ScopedAutoReleasePool();
  10007. ~ScopedAutoReleasePool();
  10008. private:
  10009. void* pool;
  10010. };
  10011. /**
  10012. A wrapper class for picking up events from an Apple IR remote control device.
  10013. To use it, just create a subclass of this class, implementing the buttonPressed()
  10014. callback, then call start() and stop() to start or stop receiving events.
  10015. */
  10016. class JUCE_API AppleRemoteDevice
  10017. {
  10018. public:
  10019. AppleRemoteDevice();
  10020. virtual ~AppleRemoteDevice();
  10021. /** The set of buttons that may be pressed.
  10022. @see buttonPressed
  10023. */
  10024. enum ButtonType
  10025. {
  10026. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10027. playButton, /**< The play button. */
  10028. plusButton, /**< The plus or volume-up button. */
  10029. minusButton, /**< The minus or volume-down button. */
  10030. rightButton, /**< The right button (if it's held for a short time). */
  10031. leftButton, /**< The left button (if it's held for a short time). */
  10032. rightButton_Long, /**< The right button (if it's held for a long time). */
  10033. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10034. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10035. playButtonSleepMode,
  10036. switched
  10037. };
  10038. /** Override this method to receive the callback about a button press.
  10039. The callback will happen on the application's message thread.
  10040. Some buttons trigger matching up and down events, in which the isDown parameter
  10041. will be true and then false. Others only send a single event when the
  10042. button is pressed.
  10043. */
  10044. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10045. /** Starts the device running and responding to events.
  10046. Returns true if it managed to open the device.
  10047. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10048. and will not be available to any other part of the system. If
  10049. false, it will be shared with other apps.
  10050. @see stop
  10051. */
  10052. bool start (const bool inExclusiveMode) throw();
  10053. /** Stops the device running.
  10054. @see start
  10055. */
  10056. void stop() throw();
  10057. /** Returns true if the device has been started successfully.
  10058. */
  10059. bool isActive() const throw();
  10060. /** Returns the ID number of the remote, if it has sent one.
  10061. */
  10062. int getRemoteId() const throw() { return remoteId; }
  10063. juce_UseDebuggingNewOperator
  10064. /** @internal */
  10065. void handleCallbackInternal();
  10066. private:
  10067. void* device;
  10068. void* queue;
  10069. int remoteId;
  10070. bool open (const bool openInExclusiveMode) throw();
  10071. };
  10072. #endif
  10073. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10074. /********* End of inlined file: juce_PlatformUtilities.h *********/
  10075. #endif
  10076. #ifndef __JUCE_UUID_JUCEHEADER__
  10077. /********* Start of inlined file: juce_Uuid.h *********/
  10078. #ifndef __JUCE_UUID_JUCEHEADER__
  10079. #define __JUCE_UUID_JUCEHEADER__
  10080. /**
  10081. A universally unique 128-bit identifier.
  10082. This class generates very random unique numbers based on the system time
  10083. and MAC addresses if any are available. It's extremely unlikely that two identical
  10084. UUIDs would ever be created by chance.
  10085. The class includes methods for saving the ID as a string or as raw binary data.
  10086. */
  10087. class JUCE_API Uuid
  10088. {
  10089. public:
  10090. /** Creates a new unique ID. */
  10091. Uuid();
  10092. /** Destructor. */
  10093. ~Uuid() throw();
  10094. /** Creates a copy of another UUID. */
  10095. Uuid (const Uuid& other);
  10096. /** Copies another UUID. */
  10097. Uuid& operator= (const Uuid& other);
  10098. /** Returns true if the ID is zero. */
  10099. bool isNull() const throw();
  10100. /** Compares two UUIDs. */
  10101. bool operator== (const Uuid& other) const;
  10102. /** Compares two UUIDs. */
  10103. bool operator!= (const Uuid& other) const;
  10104. /** Returns a stringified version of this UUID.
  10105. A Uuid object can later be reconstructed from this string using operator= or
  10106. the constructor that takes a string parameter.
  10107. @returns a 32 character hex string.
  10108. */
  10109. const String toString() const;
  10110. /** Creates an ID from an encoded string version.
  10111. @see toString
  10112. */
  10113. Uuid (const String& uuidString);
  10114. /** Copies from a stringified UUID.
  10115. The string passed in should be one that was created with the toString() method.
  10116. */
  10117. Uuid& operator= (const String& uuidString);
  10118. /** Returns a pointer to the internal binary representation of the ID.
  10119. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  10120. the constructor or operator= method that takes an array of uint8s.
  10121. */
  10122. const uint8* getRawData() const throw() { return value.asBytes; }
  10123. /** Creates a UUID from a 16-byte array.
  10124. @see getRawData
  10125. */
  10126. Uuid (const uint8* const rawData);
  10127. /** Sets this UUID from 16-bytes of raw data. */
  10128. Uuid& operator= (const uint8* const rawData);
  10129. juce_UseDebuggingNewOperator
  10130. private:
  10131. union
  10132. {
  10133. uint8 asBytes [16];
  10134. int asInt[4];
  10135. int64 asInt64[2];
  10136. } value;
  10137. };
  10138. #endif // __JUCE_UUID_JUCEHEADER__
  10139. /********* End of inlined file: juce_Uuid.h *********/
  10140. #endif
  10141. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10142. /********* Start of inlined file: juce_ZipFile.h *********/
  10143. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10144. #define __JUCE_ZIPFILE_JUCEHEADER__
  10145. /**
  10146. Decodes a ZIP file from a stream.
  10147. This can enumerate the items in a ZIP file and can create suitable stream objects
  10148. to read each one.
  10149. */
  10150. class JUCE_API ZipFile
  10151. {
  10152. public:
  10153. /** Creates a ZipFile for a given stream.
  10154. @param inputStream the stream to read from
  10155. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  10156. will be deleted when this ZipFile object is deleted
  10157. */
  10158. ZipFile (InputStream* const inputStream,
  10159. const bool deleteStreamWhenDestroyed) throw();
  10160. /** Creates a ZipFile based for a file. */
  10161. ZipFile (const File& file);
  10162. /** Creates a ZipFile for an input source.
  10163. The inputSource object will be owned by the zip file, which will delete
  10164. it later when not needed.
  10165. */
  10166. ZipFile (InputSource* const inputSource);
  10167. /** Destructor. */
  10168. ~ZipFile() throw();
  10169. /**
  10170. Contains information about one of the entries in a ZipFile.
  10171. @see ZipFile::getEntry
  10172. */
  10173. struct ZipEntry
  10174. {
  10175. /** The name of the file, which may also include a partial pathname. */
  10176. String filename;
  10177. /** The file's original size. */
  10178. unsigned int uncompressedSize;
  10179. /** The last time the file was modified. */
  10180. Time fileTime;
  10181. };
  10182. /** Returns the number of items in the zip file. */
  10183. int getNumEntries() const throw();
  10184. /** Returns a structure that describes one of the entries in the zip file.
  10185. This may return zero if the index is out of range.
  10186. @see ZipFile::ZipEntry
  10187. */
  10188. const ZipEntry* getEntry (const int index) const throw();
  10189. /** Returns the index of the first entry with a given filename.
  10190. This uses a case-sensitive comparison to look for a filename in the
  10191. list of entries. It might return -1 if no match is found.
  10192. @see ZipFile::ZipEntry
  10193. */
  10194. int getIndexOfFileName (const String& fileName) const throw();
  10195. /** Returns a structure that describes one of the entries in the zip file.
  10196. This uses a case-sensitive comparison to look for a filename in the
  10197. list of entries. It might return 0 if no match is found.
  10198. @see ZipFile::ZipEntry
  10199. */
  10200. const ZipEntry* getEntry (const String& fileName) const throw();
  10201. /** Sorts the list of entries, based on the filename.
  10202. */
  10203. void sortEntriesByFilename();
  10204. /** Creates a stream that can read from one of the zip file's entries.
  10205. The stream that is returned must be deleted by the caller (and
  10206. zero might be returned if a stream can't be opened for some reason).
  10207. The stream must not be used after the ZipFile object that created
  10208. has been deleted.
  10209. */
  10210. InputStream* createStreamForEntry (const int index);
  10211. /** Uncompresses all of the files in the zip file.
  10212. This will expand all the entires into a target directory. The relative
  10213. paths of the entries are used.
  10214. @param targetDirectory the root folder to uncompress to
  10215. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  10216. */
  10217. void uncompressTo (const File& targetDirectory,
  10218. const bool shouldOverwriteFiles = true);
  10219. juce_UseDebuggingNewOperator
  10220. private:
  10221. VoidArray entries;
  10222. friend class ZipInputStream;
  10223. CriticalSection lock;
  10224. InputStream* inputStream;
  10225. InputSource* inputSource;
  10226. bool deleteStreamWhenDestroyed;
  10227. int numEntries, centralRecStart;
  10228. #ifdef JUCE_DEBUG
  10229. int numOpenStreams;
  10230. #endif
  10231. void init();
  10232. int findEndOfZipEntryTable (InputStream* in);
  10233. ZipFile (const ZipFile&);
  10234. const ZipFile& operator= (const ZipFile&);
  10235. };
  10236. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  10237. /********* End of inlined file: juce_ZipFile.h *********/
  10238. #endif
  10239. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10240. #endif
  10241. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10242. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10243. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10244. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10245. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10246. string into a localised version using the LocalisedStrings class.
  10247. @see LocalisedStrings
  10248. */
  10249. #define TRANS(stringLiteral) \
  10250. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10251. /**
  10252. Used to convert strings to localised foreign-language versions.
  10253. This is basically a look-up table of strings and their translated equivalents.
  10254. It can be loaded from a text file, so that you can supply a set of localised
  10255. versions of strings that you use in your app.
  10256. To use it in your code, simply call the translate() method on each string that
  10257. might have foreign versions, and if none is found, the method will just return
  10258. the original string.
  10259. The translation file should start with some lines specifying a description of
  10260. the language it contains, and also a list of ISO country codes where it might
  10261. be appropriate to use the file. After that, each line of the file should contain
  10262. a pair of quoted strings with an '=' sign.
  10263. E.g. for a french translation, the file might be:
  10264. @code
  10265. language: French
  10266. countries: fr be mc ch lu
  10267. "hello" = "bonjour"
  10268. "goodbye" = "au revoir"
  10269. @endcode
  10270. If the strings need to contain a quote character, they can use '\"' instead, and
  10271. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10272. (you can use this to add comments).
  10273. Note that this is a singleton class, so don't create or destroy the object directly.
  10274. There's also a TRANS(text) macro defined to make it easy to use the this.
  10275. E.g. @code
  10276. printSomething (TRANS("hello"));
  10277. @endcode
  10278. This macro is used in the Juce classes themselves, so your application has a chance to
  10279. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10280. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10281. code).
  10282. */
  10283. class JUCE_API LocalisedStrings
  10284. {
  10285. public:
  10286. /** Creates a set of translations from the text of a translation file.
  10287. When you create one of these, you can call setCurrentMappings() to make it
  10288. the set of mappings that the system's using.
  10289. */
  10290. LocalisedStrings (const String& fileContents) throw();
  10291. /** Creates a set of translations from a file.
  10292. When you create one of these, you can call setCurrentMappings() to make it
  10293. the set of mappings that the system's using.
  10294. */
  10295. LocalisedStrings (const File& fileToLoad) throw();
  10296. /** Destructor. */
  10297. ~LocalisedStrings() throw();
  10298. /** Selects the current set of mappings to be used by the system.
  10299. The object you pass in will be automatically deleted when no longer needed, so
  10300. don't keep a pointer to it. You can also pass in zero to remove the current
  10301. mappings.
  10302. See also the TRANS() macro, which uses the current set to do its translation.
  10303. @see translateWithCurrentMappings
  10304. */
  10305. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10306. /** Returns the currently selected set of mappings.
  10307. This is the object that was last passed to setCurrentMappings(). It may
  10308. be 0 if none has been created.
  10309. */
  10310. static LocalisedStrings* getCurrentMappings() throw();
  10311. /** Tries to translate a string using the currently selected set of mappings.
  10312. If no mapping has been set, or if the mapping doesn't contain a translation
  10313. for the string, this will just return the original string.
  10314. See also the TRANS() macro, which uses this method to do its translation.
  10315. @see setCurrentMappings, getCurrentMappings
  10316. */
  10317. static const String translateWithCurrentMappings (const String& text) throw();
  10318. /** Tries to translate a string using the currently selected set of mappings.
  10319. If no mapping has been set, or if the mapping doesn't contain a translation
  10320. for the string, this will just return the original string.
  10321. See also the TRANS() macro, which uses this method to do its translation.
  10322. @see setCurrentMappings, getCurrentMappings
  10323. */
  10324. static const String translateWithCurrentMappings (const char* text) throw();
  10325. /** Attempts to look up a string and return its localised version.
  10326. If the string isn't found in the list, the original string will be returned.
  10327. */
  10328. const String translate (const String& text) const throw();
  10329. /** Returns the name of the language specified in the translation file.
  10330. This is specified in the file using a line starting with "language:", e.g.
  10331. @code
  10332. language: german
  10333. @endcode
  10334. */
  10335. const String getLanguageName() const throw() { return languageName; }
  10336. /** Returns the list of suitable country codes listed in the translation file.
  10337. These is specified in the file using a line starting with "countries:", e.g.
  10338. @code
  10339. countries: fr be mc ch lu
  10340. @endcode
  10341. The country codes are supposed to be 2-character ISO complient codes.
  10342. */
  10343. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10344. juce_UseDebuggingNewOperator
  10345. private:
  10346. String languageName;
  10347. StringArray countryCodes;
  10348. StringPairArray translations;
  10349. void loadFromText (const String& fileContents) throw();
  10350. };
  10351. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10352. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10353. #endif
  10354. #ifndef __JUCE_STRING_JUCEHEADER__
  10355. #endif
  10356. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10357. #endif
  10358. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10359. #endif
  10360. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10361. /********* Start of inlined file: juce_XmlDocument.h *********/
  10362. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10363. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10364. /**
  10365. Parses a text-based XML document and creates an XmlElement object from it.
  10366. The parser will parse DTDs to load external entities but won't
  10367. check the document for validity against the DTD.
  10368. e.g.
  10369. @code
  10370. XmlDocument myDocument (File ("myfile.xml"));
  10371. XmlElement* mainElement = myDocument.getDocumentElement();
  10372. if (mainElement == 0)
  10373. {
  10374. String error = myDocument.getLastParseError();
  10375. }
  10376. else
  10377. {
  10378. ..use the element
  10379. }
  10380. @endcode
  10381. @see XmlElement
  10382. */
  10383. class JUCE_API XmlDocument
  10384. {
  10385. public:
  10386. /** Creates an XmlDocument from the xml text.
  10387. The text doesn't actually get parsed until the getDocumentElement() method is
  10388. called.
  10389. */
  10390. XmlDocument (const String& documentText) throw();
  10391. /** Creates an XmlDocument from a file.
  10392. The text doesn't actually get parsed until the getDocumentElement() method is
  10393. called.
  10394. */
  10395. XmlDocument (const File& file);
  10396. /** Destructor. */
  10397. ~XmlDocument() throw();
  10398. /** Creates an XmlElement object to represent the main document node.
  10399. This method will do the actual parsing of the text, and if there's a
  10400. parse error, it may returns 0 (and you can find out the error using
  10401. the getLastParseError() method).
  10402. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10403. first section of the file, and will only
  10404. return the outer document element - this
  10405. allows quick checking of large files to
  10406. see if they contain the correct type of
  10407. tag, without having to parse the entire file
  10408. @returns a new XmlElement which the caller will need to delete, or null if
  10409. there was an error.
  10410. @see getLastParseError
  10411. */
  10412. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10413. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10414. @returns the error, or an empty string if there was no error.
  10415. */
  10416. const String& getLastParseError() const throw();
  10417. /** Sets an input source object to use for parsing documents that reference external entities.
  10418. If the document has been created from a file, this probably won't be needed, but
  10419. if you're parsing some text and there might be a DTD that references external
  10420. files, you may need to create a custom input source that can retrieve the
  10421. other files it needs.
  10422. The object that is passed-in will be deleted automatically when no longer needed.
  10423. @see InputSource
  10424. */
  10425. void setInputSource (InputSource* const newSource) throw();
  10426. /** Sets a flag to change the treatment of empty text elements.
  10427. If this is true (the default state), then any text elements that contain only
  10428. whitespace characters will be ingored during parsing. If you need to catch
  10429. whitespace-only text, then you should set this to false before calling the
  10430. getDocumentElement() method.
  10431. */
  10432. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  10433. juce_UseDebuggingNewOperator
  10434. private:
  10435. String originalText;
  10436. const tchar* input;
  10437. bool outOfData, errorOccurred;
  10438. bool identifierLookupTable [128];
  10439. String lastError, dtdText;
  10440. StringArray tokenisedDTD;
  10441. bool needToLoadDTD, ignoreEmptyTextElements;
  10442. InputSource* inputSource;
  10443. void setLastError (const String& desc, const bool carryOn) throw();
  10444. void skipHeader() throw();
  10445. void skipNextWhiteSpace() throw();
  10446. tchar readNextChar() throw();
  10447. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10448. void readChildElements (XmlElement* parent) throw();
  10449. int findNextTokenLength() throw();
  10450. void readQuotedString (String& result) throw();
  10451. void readEntity (String& result) throw();
  10452. const String getFileContents (const String& filename) const;
  10453. const String expandEntity (const String& entity);
  10454. const String expandExternalEntity (const String& entity);
  10455. const String getParameterEntity (const String& entity);
  10456. };
  10457. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10458. /********* End of inlined file: juce_XmlDocument.h *********/
  10459. #endif
  10460. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10461. #endif
  10462. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10463. #endif
  10464. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10465. /********* Start of inlined file: juce_InterProcessLock.h *********/
  10466. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10467. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10468. /**
  10469. Acts as a critical section which processes can use to block each other.
  10470. @see CriticalSection
  10471. */
  10472. class JUCE_API InterProcessLock
  10473. {
  10474. public:
  10475. /** Creates a lock object.
  10476. @param name a name that processes will use to identify this lock object
  10477. */
  10478. InterProcessLock (const String& name) throw();
  10479. /** Destructor.
  10480. This will also release the lock if it's currently held by this process.
  10481. */
  10482. ~InterProcessLock() throw();
  10483. /** Attempts to lock the critical section.
  10484. @param timeOutMillisecs how many milliseconds to wait if the lock
  10485. is already held by another process - a value of
  10486. 0 will return immediately, negative values will wait
  10487. forever
  10488. @returns true if the lock could be gained within the timeout period, or
  10489. false if the timeout expired.
  10490. */
  10491. bool enter (int timeOutMillisecs = -1) throw();
  10492. /** Releases the lock if it's currently held by this process.
  10493. */
  10494. void exit() throw();
  10495. juce_UseDebuggingNewOperator
  10496. private:
  10497. void* internal;
  10498. String name;
  10499. int reentrancyLevel;
  10500. InterProcessLock (const InterProcessLock&);
  10501. const InterProcessLock& operator= (const InterProcessLock&);
  10502. };
  10503. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10504. /********* End of inlined file: juce_InterProcessLock.h *********/
  10505. #endif
  10506. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10507. /********* Start of inlined file: juce_Process.h *********/
  10508. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10509. #define __JUCE_PROCESS_JUCEHEADER__
  10510. /** Represents the current executable's process.
  10511. This contains methods for controlling the current application at the
  10512. process-level.
  10513. @see Thread, JUCEApplication
  10514. */
  10515. class JUCE_API Process
  10516. {
  10517. public:
  10518. enum ProcessPriority
  10519. {
  10520. LowPriority = 0,
  10521. NormalPriority = 1,
  10522. HighPriority = 2,
  10523. RealtimePriority = 3
  10524. };
  10525. /** Changes the current process's priority.
  10526. @param priority the process priority, where
  10527. 0=low, 1=normal, 2=high, 3=realtime
  10528. */
  10529. static void setPriority (const ProcessPriority priority);
  10530. /** Kills the current process immediately.
  10531. This is an emergency process terminator that kills the application
  10532. immediately - it's intended only for use only when something goes
  10533. horribly wrong.
  10534. @see JUCEApplication::quit
  10535. */
  10536. static void terminate();
  10537. /** Returns true if this application process is the one that the user is
  10538. currently using.
  10539. */
  10540. static bool isForegroundProcess() throw();
  10541. /** Raises the current process's privilege level.
  10542. Does nothing if this isn't supported by the current OS, or if process
  10543. privilege level is fixed.
  10544. */
  10545. static void raisePrivilege();
  10546. /** Lowers the current process's privilege level.
  10547. Does nothing if this isn't supported by the current OS, or if process
  10548. privilege level is fixed.
  10549. */
  10550. static void lowerPrivilege();
  10551. /** Returns true if this process is being hosted by a debugger.
  10552. */
  10553. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  10554. };
  10555. #endif // __JUCE_PROCESS_JUCEHEADER__
  10556. /********* End of inlined file: juce_Process.h *********/
  10557. #endif
  10558. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10559. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  10560. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10561. #define __JUCE_READWRITELOCK_JUCEHEADER__
  10562. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10563. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10564. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10565. /**
  10566. Allows threads to wait for events triggered by other threads.
  10567. A thread can call wait() on a WaitableObject, and this will suspend the
  10568. calling thread until another thread wakes it up by calling the signal()
  10569. method.
  10570. */
  10571. class JUCE_API WaitableEvent
  10572. {
  10573. public:
  10574. /** Creates a WaitableEvent object. */
  10575. WaitableEvent() throw();
  10576. /** Destructor.
  10577. If other threads are waiting on this object when it gets deleted, this
  10578. can cause nasty errors, so be careful!
  10579. */
  10580. ~WaitableEvent() throw();
  10581. /** Suspends the calling thread until the event has been signalled.
  10582. This will wait until the object's signal() method is called by another thread,
  10583. or until the timeout expires.
  10584. After the event has been signalled, this method will return true and reset
  10585. the event.
  10586. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10587. value will cause it to wait forever.
  10588. @returns true if the object has been signalled, false if the timeout expires first.
  10589. @see signal, reset
  10590. */
  10591. bool wait (const int timeOutMilliseconds = -1) const throw();
  10592. /** Wakes up any threads that are currently waiting on this object.
  10593. If signal() is called when nothing is waiting, the next thread to call wait()
  10594. will return immediately and reset the signal.
  10595. @see wait, reset
  10596. */
  10597. void signal() const throw();
  10598. /** Resets the event to an unsignalled state.
  10599. If it's not already signalled, this does nothing.
  10600. */
  10601. void reset() const throw();
  10602. juce_UseDebuggingNewOperator
  10603. private:
  10604. void* internal;
  10605. WaitableEvent (const WaitableEvent&);
  10606. const WaitableEvent& operator= (const WaitableEvent&);
  10607. };
  10608. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10609. /********* End of inlined file: juce_WaitableEvent.h *********/
  10610. /********* Start of inlined file: juce_Thread.h *********/
  10611. #ifndef __JUCE_THREAD_JUCEHEADER__
  10612. #define __JUCE_THREAD_JUCEHEADER__
  10613. /**
  10614. Encapsulates a thread.
  10615. Subclasses derive from Thread and implement the run() method, in which they
  10616. do their business. The thread can then be started with the startThread() method
  10617. and controlled with various other methods.
  10618. This class also contains some thread-related static methods, such
  10619. as sleep(), yield(), getCurrentThreadId() etc.
  10620. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10621. MessageManagerLock
  10622. */
  10623. class JUCE_API Thread
  10624. {
  10625. public:
  10626. /**
  10627. Creates a thread.
  10628. When first created, the thread is not running. Use the startThread()
  10629. method to start it.
  10630. */
  10631. Thread (const String& threadName);
  10632. /** Destructor.
  10633. Deleting a Thread object that is running will only give the thread a
  10634. brief opportunity to stop itself cleanly, so it's recommended that you
  10635. should always call stopThread() with a decent timeout before deleting,
  10636. to avoid the thread being forcibly killed (which is a Bad Thing).
  10637. */
  10638. virtual ~Thread();
  10639. /** Must be implemented to perform the thread's actual code.
  10640. Remember that the thread must regularly check the threadShouldExit()
  10641. method whilst running, and if this returns true it should return from
  10642. the run() method as soon as possible to avoid being forcibly killed.
  10643. @see threadShouldExit, startThread
  10644. */
  10645. virtual void run() = 0;
  10646. // Thread control functions..
  10647. /** Starts the thread running.
  10648. This will start the thread's run() method.
  10649. (if it's already started, startThread() won't do anything).
  10650. @see stopThread
  10651. */
  10652. void startThread() throw();
  10653. /** Starts the thread with a given priority.
  10654. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10655. If the thread is already running, its priority will be changed.
  10656. @see startThread, setPriority
  10657. */
  10658. void startThread (const int priority) throw();
  10659. /** Attempts to stop the thread running.
  10660. This method will cause the threadShouldExit() method to return true
  10661. and call notify() in case the thread is currently waiting.
  10662. Hopefully the thread will then respond to this by exiting cleanly, and
  10663. the stopThread method will wait for a given time-period for this to
  10664. happen.
  10665. If the thread is stuck and fails to respond after the time-out, it gets
  10666. forcibly killed, which is a very bad thing to happen, as it could still
  10667. be holding locks, etc. which are needed by other parts of your program.
  10668. @param timeOutMilliseconds The number of milliseconds to wait for the
  10669. thread to finish before killing it by force. A negative
  10670. value in here will wait forever.
  10671. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  10672. */
  10673. void stopThread (const int timeOutMilliseconds) throw();
  10674. /** Returns true if the thread is currently active */
  10675. bool isThreadRunning() const throw();
  10676. /** Sets a flag to tell the thread it should stop.
  10677. Calling this means that the threadShouldExit() method will then return true.
  10678. The thread should be regularly checking this to see whether it should exit.
  10679. @see threadShouldExit
  10680. @see waitForThreadToExit
  10681. */
  10682. void signalThreadShouldExit() throw();
  10683. /** Checks whether the thread has been told to stop running.
  10684. Threads need to check this regularly, and if it returns true, they should
  10685. return from their run() method at the first possible opportunity.
  10686. @see signalThreadShouldExit
  10687. */
  10688. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  10689. /** Waits for the thread to stop.
  10690. This will waits until isThreadRunning() is false or until a timeout expires.
  10691. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  10692. is less than zero, it will wait forever.
  10693. @returns true if the thread exits, or false if the timeout expires first.
  10694. */
  10695. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  10696. /** Changes the thread's priority.
  10697. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  10698. of 5 is normal.
  10699. */
  10700. void setPriority (const int priority) throw();
  10701. /** Changes the priority of the caller thread.
  10702. Similar to setPriority(), but this static method acts on the caller thread.
  10703. @see setPriority
  10704. */
  10705. static void setCurrentThreadPriority (const int priority) throw();
  10706. /** Sets the affinity mask for the thread.
  10707. This will only have an effect next time the thread is started - i.e. if the
  10708. thread is already running when called, it'll have no effect.
  10709. @see setCurrentThreadAffinityMask
  10710. */
  10711. void setAffinityMask (const uint32 affinityMask) throw();
  10712. /** Changes the affinity mask for the caller thread.
  10713. This will change the affinity mask for the thread that calls this static method.
  10714. @see setAffinityMask
  10715. */
  10716. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  10717. // this can be called from any thread that needs to pause..
  10718. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  10719. /** Yields the calling thread's current time-slot. */
  10720. static void JUCE_CALLTYPE yield() throw();
  10721. /** Makes the thread wait for a notification.
  10722. This puts the thread to sleep until either the timeout period expires, or
  10723. another thread calls the notify() method to wake it up.
  10724. @returns true if the event has been signalled, false if the timeout expires.
  10725. */
  10726. bool wait (const int timeOutMilliseconds) const throw();
  10727. /** Wakes up the thread.
  10728. If the thread has called the wait() method, this will wake it up.
  10729. @see wait
  10730. */
  10731. void notify() const throw();
  10732. /** A value type used for thread IDs.
  10733. @see getCurrentThreadId(), getThreadId()
  10734. */
  10735. typedef void* ThreadID;
  10736. /** Returns an id that identifies the caller thread.
  10737. To find the ID of a particular thread object, use getThreadId().
  10738. @returns a unique identifier that identifies the calling thread.
  10739. @see getThreadId
  10740. */
  10741. static ThreadID getCurrentThreadId() throw();
  10742. /** Finds the thread object that is currently running.
  10743. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  10744. object associated with them, so this will return 0.
  10745. */
  10746. static Thread* getCurrentThread() throw();
  10747. /** Returns the ID of this thread.
  10748. That means the ID of this thread object - not of the thread that's calling the method.
  10749. This can change when the thread is started and stopped, and will be invalid if the
  10750. thread's not actually running.
  10751. @see getCurrentThreadId
  10752. */
  10753. ThreadID getThreadId() const throw();
  10754. /** Returns the name of the thread.
  10755. This is the name that gets set in the constructor.
  10756. */
  10757. const String getThreadName() const throw() { return threadName_; }
  10758. /** Returns the number of currently-running threads.
  10759. @returns the number of Thread objects known to be currently running.
  10760. @see stopAllThreads
  10761. */
  10762. static int getNumRunningThreads() throw();
  10763. /** Tries to stop all currently-running threads.
  10764. This will attempt to stop all the threads known to be running at the moment.
  10765. */
  10766. static void stopAllThreads (const int timeoutInMillisecs) throw();
  10767. juce_UseDebuggingNewOperator
  10768. private:
  10769. const String threadName_;
  10770. void* volatile threadHandle_;
  10771. CriticalSection startStopLock;
  10772. WaitableEvent startSuspensionEvent_, defaultEvent_;
  10773. int threadPriority_;
  10774. ThreadID threadId_;
  10775. uint32 affinityMask_;
  10776. bool volatile threadShouldExit_;
  10777. friend void JUCE_API juce_threadEntryPoint (void*);
  10778. static void threadEntryPoint (Thread* thread) throw();
  10779. Thread (const Thread&);
  10780. const Thread& operator= (const Thread&);
  10781. };
  10782. #endif // __JUCE_THREAD_JUCEHEADER__
  10783. /********* End of inlined file: juce_Thread.h *********/
  10784. /**
  10785. A critical section that allows multiple simultaneous readers.
  10786. Features of this type of lock are:
  10787. - Multiple readers can hold the lock at the same time, but only one writer
  10788. can hold it at once.
  10789. - Writers trying to gain the lock will be blocked until all readers and writers
  10790. have released it
  10791. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  10792. blocked until the writer has obtained and released it
  10793. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  10794. there are no other readers
  10795. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  10796. - Recursive locking is supported.
  10797. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  10798. */
  10799. class JUCE_API ReadWriteLock
  10800. {
  10801. public:
  10802. /**
  10803. Creates a ReadWriteLock object.
  10804. */
  10805. ReadWriteLock() throw();
  10806. /** Destructor.
  10807. If the object is deleted whilst locked, any subsequent behaviour
  10808. is unpredictable.
  10809. */
  10810. ~ReadWriteLock() throw();
  10811. /** Locks this object for reading.
  10812. Multiple threads can simulaneously lock the object for reading, but if another
  10813. thread has it locked for writing, then this will block until it releases the
  10814. lock.
  10815. @see exitRead, ScopedReadLock
  10816. */
  10817. void enterRead() const throw();
  10818. /** Releases the read-lock.
  10819. If the caller thread hasn't got the lock, this can have unpredictable results.
  10820. If the enterRead() method has been called multiple times by the thread, each
  10821. call must be matched by a call to exitRead() before other threads will be allowed
  10822. to take over the lock.
  10823. @see enterRead, ScopedReadLock
  10824. */
  10825. void exitRead() const throw();
  10826. /** Locks this object for writing.
  10827. This will block until any other threads that have it locked for reading or
  10828. writing have released their lock.
  10829. @see exitWrite, ScopedWriteLock
  10830. */
  10831. void enterWrite() const throw();
  10832. /** Tries to lock this object for writing.
  10833. This is like enterWrite(), but doesn't block - it returns true if it manages
  10834. to obtain the lock.
  10835. @see enterWrite
  10836. */
  10837. bool tryEnterWrite() const throw();
  10838. /** Releases the write-lock.
  10839. If the caller thread hasn't got the lock, this can have unpredictable results.
  10840. If the enterWrite() method has been called multiple times by the thread, each
  10841. call must be matched by a call to exit() before other threads will be allowed
  10842. to take over the lock.
  10843. @see enterWrite, ScopedWriteLock
  10844. */
  10845. void exitWrite() const throw();
  10846. juce_UseDebuggingNewOperator
  10847. private:
  10848. CriticalSection accessLock;
  10849. WaitableEvent waitEvent;
  10850. mutable int numWaitingWriters, numWriters;
  10851. mutable Thread::ThreadID writerThreadId;
  10852. mutable Array <Thread::ThreadID> readerThreads;
  10853. ReadWriteLock (const ReadWriteLock&);
  10854. const ReadWriteLock& operator= (const ReadWriteLock&);
  10855. };
  10856. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  10857. /********* End of inlined file: juce_ReadWriteLock.h *********/
  10858. #endif
  10859. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  10860. #endif
  10861. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10862. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  10863. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10864. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10865. /**
  10866. Automatically locks and unlocks a ReadWriteLock object.
  10867. Use one of these as a local variable to control access to a ReadWriteLock.
  10868. e.g. @code
  10869. ReadWriteLock myLock;
  10870. for (;;)
  10871. {
  10872. const ScopedReadLock myScopedLock (myLock);
  10873. // myLock is now locked
  10874. ...do some stuff...
  10875. // myLock gets unlocked here.
  10876. }
  10877. @endcode
  10878. @see ReadWriteLock, ScopedWriteLock
  10879. */
  10880. class JUCE_API ScopedReadLock
  10881. {
  10882. public:
  10883. /** Creates a ScopedReadLock.
  10884. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  10885. when the ScopedReadLock object is deleted, the ReadWriteLock will
  10886. be unlocked.
  10887. Make sure this object is created and deleted by the same thread,
  10888. otherwise there are no guarantees what will happen! Best just to use it
  10889. as a local stack object, rather than creating one with the new() operator.
  10890. */
  10891. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  10892. /** Destructor.
  10893. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  10894. Make sure this object is created and deleted by the same thread,
  10895. otherwise there are no guarantees what will happen!
  10896. */
  10897. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  10898. private:
  10899. const ReadWriteLock& lock_;
  10900. ScopedReadLock (const ScopedReadLock&);
  10901. const ScopedReadLock& operator= (const ScopedReadLock&);
  10902. };
  10903. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  10904. /********* End of inlined file: juce_ScopedReadLock.h *********/
  10905. #endif
  10906. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10907. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  10908. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10909. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10910. /**
  10911. Automatically tries to lock and unlock a CriticalSection object.
  10912. Use one of these as a local variable to control access to a CriticalSection.
  10913. e.g. @code
  10914. CriticalSection myCriticalSection;
  10915. for (;;)
  10916. {
  10917. const ScopedTryLock myScopedTryLock (myCriticalSection);
  10918. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  10919. // should test this with the isLocked() method before doing your thread-unsafe
  10920. // action..
  10921. if (myScopedTryLock.isLocked())
  10922. {
  10923. ...do some stuff...
  10924. }
  10925. else
  10926. {
  10927. ..our attempt at locking failed because another thread had already locked it..
  10928. }
  10929. // myCriticalSection gets unlocked here (if it was locked)
  10930. }
  10931. @endcode
  10932. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  10933. */
  10934. class JUCE_API ScopedTryLock
  10935. {
  10936. public:
  10937. /** Creates a ScopedTryLock.
  10938. As soon as it is created, this will try to lock the CriticalSection, and
  10939. when the ScopedTryLock object is deleted, the CriticalSection will
  10940. be unlocked if the lock was successful.
  10941. Make sure this object is created and deleted by the same thread,
  10942. otherwise there are no guarantees what will happen! Best just to use it
  10943. as a local stack object, rather than creating one with the new() operator.
  10944. */
  10945. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  10946. /** Destructor.
  10947. The CriticalSection will be unlocked (if locked) when the destructor is called.
  10948. Make sure this object is created and deleted by the same thread,
  10949. otherwise there are no guarantees what will happen!
  10950. */
  10951. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  10952. /** Lock state
  10953. @return True if the CriticalSection is locked.
  10954. */
  10955. bool isLocked() const throw() { return lockWasSuccessful; }
  10956. private:
  10957. const CriticalSection& lock_;
  10958. const bool lockWasSuccessful;
  10959. ScopedTryLock (const ScopedTryLock&);
  10960. const ScopedTryLock& operator= (const ScopedTryLock&);
  10961. };
  10962. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  10963. /********* End of inlined file: juce_ScopedTryLock.h *********/
  10964. #endif
  10965. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10966. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  10967. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10968. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  10969. /**
  10970. Automatically locks and unlocks a ReadWriteLock object.
  10971. Use one of these as a local variable to control access to a ReadWriteLock.
  10972. e.g. @code
  10973. ReadWriteLock myLock;
  10974. for (;;)
  10975. {
  10976. const ScopedWriteLock myScopedLock (myLock);
  10977. // myLock is now locked
  10978. ...do some stuff...
  10979. // myLock gets unlocked here.
  10980. }
  10981. @endcode
  10982. @see ReadWriteLock, ScopedReadLock
  10983. */
  10984. class JUCE_API ScopedWriteLock
  10985. {
  10986. public:
  10987. /** Creates a ScopedWriteLock.
  10988. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  10989. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  10990. be unlocked.
  10991. Make sure this object is created and deleted by the same thread,
  10992. otherwise there are no guarantees what will happen! Best just to use it
  10993. as a local stack object, rather than creating one with the new() operator.
  10994. */
  10995. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  10996. /** Destructor.
  10997. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  10998. Make sure this object is created and deleted by the same thread,
  10999. otherwise there are no guarantees what will happen!
  11000. */
  11001. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  11002. private:
  11003. const ReadWriteLock& lock_;
  11004. ScopedWriteLock (const ScopedWriteLock&);
  11005. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  11006. };
  11007. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11008. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  11009. #endif
  11010. #ifndef __JUCE_THREAD_JUCEHEADER__
  11011. #endif
  11012. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  11013. /********* Start of inlined file: juce_ThreadPool.h *********/
  11014. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  11015. #define __JUCE_THREADPOOL_JUCEHEADER__
  11016. class ThreadPool;
  11017. class ThreadPoolThread;
  11018. /**
  11019. A task that is executed by a ThreadPool object.
  11020. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  11021. its threads.
  11022. The runJob() method needs to be implemented to do the task, and if the code that
  11023. does the work takes a significant time to run, it must keep checking the shouldExit()
  11024. method to see if something is trying to interrupt the job. If shouldExit() returns
  11025. true, the runJob() method must return immediately.
  11026. @see ThreadPool, Thread
  11027. */
  11028. class JUCE_API ThreadPoolJob
  11029. {
  11030. public:
  11031. /** Creates a thread pool job object.
  11032. After creating your job, add it to a thread pool with ThreadPool::addJob().
  11033. */
  11034. ThreadPoolJob (const String& name);
  11035. /** Destructor. */
  11036. virtual ~ThreadPoolJob();
  11037. /** Returns the name of this job.
  11038. @see setJobName
  11039. */
  11040. const String getJobName() const;
  11041. /** Changes the job's name.
  11042. @see getJobName
  11043. */
  11044. void setJobName (const String& newName);
  11045. /** These are the values that can be returned by the runJob() method.
  11046. */
  11047. enum JobStatus
  11048. {
  11049. jobHasFinished = 0, /**< indicates that the job has finished and can be
  11050. removed from the pool. */
  11051. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  11052. should be automatically deleted by the pool. */
  11053. jobNeedsRunningAgain /**< indicates that the job would like to be called
  11054. again when a thread is free. */
  11055. };
  11056. /** Peforms the actual work that this job needs to do.
  11057. Your subclass must implement this method, in which is does its work.
  11058. If the code in this method takes a significant time to run, it must repeatedly check
  11059. the shouldExit() method to see if something is trying to interrupt the job.
  11060. If shouldExit() ever returns true, the runJob() method must return immediately.
  11061. If this method returns jobHasFinished, then the job will be removed from the pool
  11062. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  11063. pool and will get a chance to run again as soon as a thread is free.
  11064. @see shouldExit()
  11065. */
  11066. virtual JobStatus runJob() = 0;
  11067. /** Returns true if this job is currently running its runJob() method. */
  11068. bool isRunning() const throw() { return isActive; }
  11069. /** Returns true if something is trying to interrupt this job and make it stop.
  11070. Your runJob() method must call this whenever it gets a chance, and if it ever
  11071. returns true, the runJob() method must return immediately.
  11072. @see signalJobShouldExit()
  11073. */
  11074. bool shouldExit() const throw() { return shouldStop; }
  11075. /** Calling this will cause the shouldExit() method to return true, and the job
  11076. should (if it's been implemented correctly) stop as soon as possible.
  11077. @see shouldExit()
  11078. */
  11079. void signalJobShouldExit();
  11080. juce_UseDebuggingNewOperator
  11081. private:
  11082. friend class ThreadPool;
  11083. friend class ThreadPoolThread;
  11084. String jobName;
  11085. ThreadPool* pool;
  11086. bool shouldStop, isActive, shouldBeDeleted;
  11087. };
  11088. /**
  11089. A set of threads that will run a list of jobs.
  11090. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  11091. will be called by the next pooled thread that becomes free.
  11092. @see ThreadPoolJob, Thread
  11093. */
  11094. class JUCE_API ThreadPool
  11095. {
  11096. public:
  11097. /** Creates a thread pool.
  11098. Once you've created a pool, you can give it some things to do with the addJob()
  11099. method.
  11100. @param numberOfThreads the maximum number of actual threads to run.
  11101. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  11102. until there are some jobs to run. If false, then
  11103. all the threads will be fired-up immediately so that
  11104. they're ready for action
  11105. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  11106. inactive for this length of time, they will automatically
  11107. be stopped until more jobs come along and they're needed
  11108. */
  11109. ThreadPool (const int numberOfThreads,
  11110. const bool startThreadsOnlyWhenNeeded = true,
  11111. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  11112. /** Destructor.
  11113. This will attempt to remove all the jobs before deleting, but if you want to
  11114. specify a timeout, you should call removeAllJobs() explicitly before deleting
  11115. the pool.
  11116. */
  11117. ~ThreadPool();
  11118. /** Adds a job to the queue.
  11119. Once a job has been added, then the next time a thread is free, it will run
  11120. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  11121. runJob() method, the pool will either remove the job from the pool or add it to
  11122. the back of the queue to be run again.
  11123. */
  11124. void addJob (ThreadPoolJob* const job);
  11125. /** Tries to remove a job from the pool.
  11126. If the job isn't yet running, this will simply remove it. If it is running, it
  11127. will wait for it to finish.
  11128. If the timeout period expires before the job finishes running, then the job will be
  11129. left in the pool and this will return false. It returns true if the job is sucessfully
  11130. stopped and removed.
  11131. @param job the job to remove
  11132. @param interruptIfRunning if true, then if the job is currently busy, its
  11133. ThreadPoolJob::signalJobShouldExit() method will be called to try
  11134. to interrupt it. If false, then if the job will be allowed to run
  11135. until it stops normally (or the timeout expires)
  11136. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  11137. before giving up and returning false
  11138. */
  11139. bool removeJob (ThreadPoolJob* const job,
  11140. const bool interruptIfRunning,
  11141. const int timeOutMilliseconds);
  11142. /** Tries clear all jobs from the pool.
  11143. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  11144. methods called to try to interrupt them
  11145. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  11146. before giving up and returning false
  11147. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  11148. expires while waiting for them to stop
  11149. */
  11150. bool removeAllJobs (const bool interruptRunningJobs,
  11151. const int timeOutMilliseconds);
  11152. /** Returns the number of jobs currently running or queued.
  11153. */
  11154. int getNumJobs() const throw();
  11155. /** Returns one of the jobs in the queue.
  11156. Note that this can be a very volatile list as jobs might be continuously getting shifted
  11157. around in the list, and this method may return 0 if the index is currently out-of-range.
  11158. */
  11159. ThreadPoolJob* getJob (const int index) const;
  11160. /** Returns true if the given job is currently queued or running.
  11161. @see isJobRunning()
  11162. */
  11163. bool contains (const ThreadPoolJob* const job) const throw();
  11164. /** Returns true if the given job is currently being run by a thread.
  11165. */
  11166. bool isJobRunning (const ThreadPoolJob* const job) const;
  11167. /** Waits until a job has finished running and has been removed from the pool.
  11168. This will wait until the job is no longer in the pool - i.e. until its
  11169. runJob() method returns ThreadPoolJob::jobHasFinished.
  11170. If the timeout period expires before the job finishes, this will return false;
  11171. it returns true if the job has finished successfully.
  11172. */
  11173. bool waitForJobToFinish (const ThreadPoolJob* const job,
  11174. const int timeOutMilliseconds) const;
  11175. /** Returns a list of the names of all the jobs currently running or queued.
  11176. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  11177. */
  11178. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  11179. /** Changes the priority of all the threads.
  11180. This will call Thread::setPriority() for each thread in the pool.
  11181. */
  11182. void setThreadPriorities (const int newPriority);
  11183. juce_UseDebuggingNewOperator
  11184. private:
  11185. const int numThreads, threadStopTimeout;
  11186. int priority;
  11187. Thread** threads;
  11188. VoidArray jobs;
  11189. CriticalSection lock;
  11190. uint32 lastJobEndTime;
  11191. friend class ThreadPoolThread;
  11192. bool runNextJob();
  11193. ThreadPool (const ThreadPool&);
  11194. const ThreadPool& operator= (const ThreadPool&);
  11195. };
  11196. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  11197. /********* End of inlined file: juce_ThreadPool.h *********/
  11198. #endif
  11199. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11200. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  11201. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11202. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11203. /**
  11204. Used by the TimeSliceThread class.
  11205. To register your class with a TimeSliceThread, derive from this class and
  11206. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  11207. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  11208. deleting your client!
  11209. @see TimeSliceThread
  11210. */
  11211. class JUCE_API TimeSliceClient
  11212. {
  11213. public:
  11214. /** Destructor. */
  11215. virtual ~TimeSliceClient() {}
  11216. /** Called back by a TimeSliceThread.
  11217. When you register this class with it, a TimeSliceThread will repeatedly call
  11218. this method.
  11219. The implementation of this method should use its time-slice to do something that's
  11220. quick - never block for longer than absolutely necessary.
  11221. @returns Your method should return true if it needs more time, or false if it's
  11222. not too busy and doesn't need calling back urgently. If all the thread's
  11223. clients indicate that they're not busy, then it'll save CPU by sleeping for
  11224. up to half a second in between callbacks. You can force the TimeSliceThread
  11225. to wake up and poll again immediately by calling its notify() method.
  11226. */
  11227. virtual bool useTimeSlice() = 0;
  11228. };
  11229. /**
  11230. A thread that keeps a list of clients, and calls each one in turn, giving them
  11231. all a chance to run some sort of short task.
  11232. @see TimeSliceClient, Thread
  11233. */
  11234. class JUCE_API TimeSliceThread : public Thread
  11235. {
  11236. public:
  11237. /**
  11238. Creates a TimeSliceThread.
  11239. When first created, the thread is not running. Use the startThread()
  11240. method to start it.
  11241. */
  11242. TimeSliceThread (const String& threadName);
  11243. /** Destructor.
  11244. Deleting a Thread object that is running will only give the thread a
  11245. brief opportunity to stop itself cleanly, so it's recommended that you
  11246. should always call stopThread() with a decent timeout before deleting,
  11247. to avoid the thread being forcibly killed (which is a Bad Thing).
  11248. */
  11249. ~TimeSliceThread();
  11250. /** Adds a client to the list.
  11251. The client's callbacks will start immediately (possibly before the method
  11252. has returned).
  11253. */
  11254. void addTimeSliceClient (TimeSliceClient* const client);
  11255. /** Removes a client from the list.
  11256. This method will make sure that all callbacks to the client have completely
  11257. finished before the method returns.
  11258. */
  11259. void removeTimeSliceClient (TimeSliceClient* const client);
  11260. /** Returns the number of registered clients. */
  11261. int getNumClients() const throw();
  11262. /** Returns one of the registered clients. */
  11263. TimeSliceClient* getClient (const int index) const throw();
  11264. /** @internal */
  11265. void run();
  11266. juce_UseDebuggingNewOperator
  11267. private:
  11268. CriticalSection callbackLock, listLock;
  11269. Array <TimeSliceClient*> clients;
  11270. int index;
  11271. TimeSliceClient* clientBeingCalled;
  11272. bool clientsChanged;
  11273. TimeSliceThread (const TimeSliceThread&);
  11274. const TimeSliceThread& operator= (const TimeSliceThread&);
  11275. };
  11276. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11277. /********* End of inlined file: juce_TimeSliceThread.h *********/
  11278. #endif
  11279. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11280. #endif
  11281. #endif
  11282. /********* End of inlined file: juce_core_includes.h *********/
  11283. // if you're compiling a command-line app, you might want to just include the core headers,
  11284. // so you can set this macro before including juce.h
  11285. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11286. /********* Start of inlined file: juce_app_includes.h *********/
  11287. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11288. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11289. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11290. /********* Start of inlined file: juce_Application.h *********/
  11291. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11292. #define __JUCE_APPLICATION_JUCEHEADER__
  11293. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11294. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11295. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11296. /********* Start of inlined file: juce_Component.h *********/
  11297. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11298. #define __JUCE_COMPONENT_JUCEHEADER__
  11299. /********* Start of inlined file: juce_MouseCursor.h *********/
  11300. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11301. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11302. class Image;
  11303. class RefCountedMouseCursor;
  11304. class ComponentPeer;
  11305. class Component;
  11306. /**
  11307. Represents a mouse cursor image.
  11308. This object can either be used to represent one of the standard mouse
  11309. cursor shapes, or a custom one generated from an image.
  11310. */
  11311. class JUCE_API MouseCursor
  11312. {
  11313. public:
  11314. /** The set of available standard mouse cursors. */
  11315. enum StandardCursorType
  11316. {
  11317. NoCursor = 0, /**< An invisible cursor. */
  11318. NormalCursor, /**< The stardard arrow cursor. */
  11319. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11320. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11321. CrosshairCursor, /**< A pair of crosshairs. */
  11322. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11323. that you're dragging a copy of something. */
  11324. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11325. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11326. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11327. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11328. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11329. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11330. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11331. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11332. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11333. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11334. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11335. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11336. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11337. };
  11338. /** Creates the standard arrow cursor. */
  11339. MouseCursor() throw();
  11340. /** Creates one of the standard mouse cursor */
  11341. MouseCursor (const StandardCursorType type) throw();
  11342. /** Creates a custom cursor from an image.
  11343. @param image the image to use for the cursor - if this is bigger than the
  11344. system can manage, it might get scaled down first, and might
  11345. also have to be turned to black-and-white if it can't do colour
  11346. cursors.
  11347. @param hotSpotX the x position of the cursor's hotspot within the image
  11348. @param hotSpotY the y position of the cursor's hotspot within the image
  11349. */
  11350. MouseCursor (Image& image,
  11351. const int hotSpotX,
  11352. const int hotSpotY) throw();
  11353. /** Creates a copy of another cursor object. */
  11354. MouseCursor (const MouseCursor& other) throw();
  11355. /** Copies this cursor from another object. */
  11356. const MouseCursor& operator= (const MouseCursor& other) throw();
  11357. /** Destructor. */
  11358. ~MouseCursor() throw();
  11359. /** Checks whether two mouse cursors are the same.
  11360. For custom cursors, two cursors created from the same image won't be
  11361. recognised as the same, only MouseCursor objects that have been
  11362. copied from the same object.
  11363. */
  11364. bool operator== (const MouseCursor& other) const throw();
  11365. /** Checks whether two mouse cursors are the same.
  11366. For custom cursors, two cursors created from the same image won't be
  11367. recognised as the same, only MouseCursor objects that have been
  11368. copied from the same object.
  11369. */
  11370. bool operator!= (const MouseCursor& other) const throw();
  11371. /** Makes the system show its default 'busy' cursor.
  11372. This will turn the system cursor to an hourglass or spinning beachball
  11373. until the next time the mouse is moved, or hideWaitCursor() is called.
  11374. This is handy if the message loop is about to block for a couple of
  11375. seconds while busy and you want to give the user feedback about this.
  11376. @see MessageManager::setTimeBeforeShowingWaitCursor
  11377. */
  11378. static void showWaitCursor() throw();
  11379. /** If showWaitCursor has been called, this will return the mouse to its
  11380. normal state.
  11381. This will look at what component is under the mouse, and update the
  11382. cursor to be the correct one for that component.
  11383. @see showWaitCursor
  11384. */
  11385. static void hideWaitCursor() throw();
  11386. juce_UseDebuggingNewOperator
  11387. private:
  11388. RefCountedMouseCursor* cursorHandle;
  11389. friend class Component;
  11390. void showInWindow (ComponentPeer* window) const throw();
  11391. void showInAllWindows() const throw();
  11392. void* getHandle() const throw();
  11393. };
  11394. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11395. /********* End of inlined file: juce_MouseCursor.h *********/
  11396. /********* Start of inlined file: juce_MouseListener.h *********/
  11397. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11398. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11399. /********* Start of inlined file: juce_MouseEvent.h *********/
  11400. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11401. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11402. class Component;
  11403. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11404. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11405. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11406. /**
  11407. Represents the state of the mouse buttons and modifier keys.
  11408. This is used both by mouse events and by KeyPress objects to describe
  11409. the state of keys such as shift, control, alt, etc.
  11410. @see KeyPress, MouseEvent::mods
  11411. */
  11412. class JUCE_API ModifierKeys
  11413. {
  11414. public:
  11415. /** Creates a ModifierKeys object from a raw set of flags.
  11416. @param flags to represent the keys that are down
  11417. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11418. rightButtonModifier, commandModifier, popupMenuClickModifier
  11419. */
  11420. ModifierKeys (const int flags = 0) throw();
  11421. /** Creates a copy of another object. */
  11422. ModifierKeys (const ModifierKeys& other) throw();
  11423. /** Copies this object from another one. */
  11424. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11425. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11426. This is a platform-agnostic way of checking for the operating system's
  11427. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11428. Windows/Linux, it's actually checking for the CTRL key.
  11429. */
  11430. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11431. /** Checks whether the user is trying to launch a pop-up menu.
  11432. This checks for platform-specific modifiers that might indicate that the user
  11433. is following the operating system's normal method of showing a pop-up menu.
  11434. So on Windows/Linux, this method is really testing for a right-click.
  11435. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11436. */
  11437. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11438. /** Checks whether the flag is set for the left mouse-button. */
  11439. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11440. /** Checks whether the flag is set for the right mouse-button.
  11441. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11442. this is platform-independent (and makes your code more explanatory too).
  11443. */
  11444. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11445. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11446. /** Tests for any of the mouse-button flags. */
  11447. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11448. /** Tests for any of the modifier key flags. */
  11449. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11450. /** Checks whether the shift key's flag is set. */
  11451. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11452. /** Checks whether the CTRL key's flag is set.
  11453. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11454. popup-menu modifiers.
  11455. @see isCommandDown, isPopupMenu
  11456. */
  11457. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11458. /** Checks whether the shift key's flag is set. */
  11459. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11460. /** Flags that represent the different keys. */
  11461. enum Flags
  11462. {
  11463. /** Shift key flag. */
  11464. shiftModifier = 1,
  11465. /** CTRL key flag. */
  11466. ctrlModifier = 2,
  11467. /** ALT key flag. */
  11468. altModifier = 4,
  11469. /** Left mouse button flag. */
  11470. leftButtonModifier = 16,
  11471. /** Right mouse button flag. */
  11472. rightButtonModifier = 32,
  11473. /** Middle mouse button flag. */
  11474. middleButtonModifier = 64,
  11475. #if JUCE_MAC
  11476. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11477. commandModifier = 8,
  11478. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11479. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11480. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11481. #else
  11482. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11483. commandModifier = ctrlModifier,
  11484. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11485. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11486. popupMenuClickModifier = rightButtonModifier,
  11487. #endif
  11488. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11489. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11490. /** Represents a combination of all the mouse buttons at once. */
  11491. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11492. };
  11493. /** Returns the raw flags for direct testing. */
  11494. inline int getRawFlags() const throw() { return flags; }
  11495. /** Tests a combination of flags and returns true if any of them are set. */
  11496. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11497. /** Creates a ModifierKeys object to represent the last-known state of the
  11498. keyboard and mouse buttons.
  11499. @see getCurrentModifiersRealtime
  11500. */
  11501. static const ModifierKeys getCurrentModifiers() throw();
  11502. /** Creates a ModifierKeys object to represent the current state of the
  11503. keyboard and mouse buttons.
  11504. This isn't often needed and isn't recommended, but will actively check all the
  11505. mouse and key states rather than just returning their last-known state like
  11506. getCurrentModifiers() does.
  11507. This is only needed in special circumstances for up-to-date modifier information
  11508. at times when the app's event loop isn't running normally.
  11509. */
  11510. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11511. private:
  11512. int flags;
  11513. static int currentModifierFlags;
  11514. friend class ComponentPeer;
  11515. static void updateCurrentModifiers() throw();
  11516. };
  11517. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11518. /********* End of inlined file: juce_ModifierKeys.h *********/
  11519. /**
  11520. Contains position and status information about a mouse event.
  11521. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11522. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11523. */
  11524. class JUCE_API MouseEvent
  11525. {
  11526. public:
  11527. /** Creates a MouseEvent.
  11528. Normally an application will never need to use this.
  11529. @param x the x position of the mouse, relative to the component that is passed-in
  11530. @param y the y position of the mouse, relative to the component that is passed-in
  11531. @param modifiers the key modifiers at the time of the event
  11532. @param originator the component that the mouse event applies to
  11533. @param eventTime the time the event happened
  11534. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11535. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11536. the same as the current mouse-x position.
  11537. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11538. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11539. the same as the current mouse-y position.
  11540. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11541. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11542. the same as the current mouse-event time.
  11543. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11544. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11545. */
  11546. MouseEvent (const int x, const int y,
  11547. const ModifierKeys& modifiers,
  11548. Component* const originator,
  11549. const Time& eventTime,
  11550. const int mouseDownX,
  11551. const int mouseDownY,
  11552. const Time& mouseDownTime,
  11553. const int numberOfClicks,
  11554. const bool mouseWasDragged) throw();
  11555. /** Destructor. */
  11556. ~MouseEvent() throw();
  11557. /** The x-position of the mouse when the event occurred.
  11558. This value is relative to the top-left of the component to which the
  11559. event applies (as indicated by the MouseEvent::eventComponent field).
  11560. */
  11561. int x;
  11562. /** The y-position of the mouse when the event occurred.
  11563. This value is relative to the top-left of the component to which the
  11564. event applies (as indicated by the MouseEvent::eventComponent field).
  11565. */
  11566. int y;
  11567. /** The key modifiers associated with the event.
  11568. This will let you find out which mouse buttons were down, as well as which
  11569. modifier keys were held down.
  11570. When used for mouse-up events, this will indicate the state of the mouse buttons
  11571. just before they were released, so that you can tell which button they let go of.
  11572. */
  11573. ModifierKeys mods;
  11574. /** The component that this event applies to.
  11575. This is usually the component that the mouse was over at the time, but for mouse-drag
  11576. events the mouse could actually be over a different component and the events are
  11577. still sent to the component that the button was originally pressed on.
  11578. The x and y member variables are relative to this component's position.
  11579. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11580. component, this pointer will be updated, but originalComponent remains unchanged.
  11581. @see originalComponent
  11582. */
  11583. Component* eventComponent;
  11584. /** The component that the event first occurred on.
  11585. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11586. component, this value remains unchanged to indicate the first component that received it.
  11587. @see eventComponent
  11588. */
  11589. Component* originalComponent;
  11590. /** The time that this mouse-event occurred.
  11591. */
  11592. Time eventTime;
  11593. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11594. The co-ordinate is relative to the component specified in MouseEvent::component.
  11595. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11596. */
  11597. int getMouseDownX() const throw();
  11598. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11599. The co-ordinate is relative to the component specified in MouseEvent::component.
  11600. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11601. */
  11602. int getMouseDownY() const throw();
  11603. /** Returns the straight-line distance between where the mouse is now and where it
  11604. was the last time the button was pressed.
  11605. This is quite handy for things like deciding whether the user has moved far enough
  11606. for it to be considered a drag operation.
  11607. @see getDistanceFromDragStartX
  11608. */
  11609. int getDistanceFromDragStart() const throw();
  11610. /** Returns the difference between the mouse's current x postion and where it was
  11611. when the button was last pressed.
  11612. @see getDistanceFromDragStart
  11613. */
  11614. int getDistanceFromDragStartX() const throw();
  11615. /** Returns the difference between the mouse's current y postion and where it was
  11616. when the button was last pressed.
  11617. @see getDistanceFromDragStart
  11618. */
  11619. int getDistanceFromDragStartY() const throw();
  11620. /** Returns true if the mouse has just been clicked.
  11621. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11622. the user has dragged the mouse more than a few pixels from the place where the
  11623. mouse-down occurred.
  11624. Once they have dragged it far enough for this method to return false, it will continue
  11625. to return false until the mouse-up, even if they move the mouse back to the same
  11626. position where they originally pressed it. This means that it's very handy for
  11627. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11628. callback to ignore any small movements they might make while clicking.
  11629. @returns true if the mouse wasn't dragged by more than a few pixels between
  11630. the last time the button was pressed and released.
  11631. */
  11632. bool mouseWasClicked() const throw();
  11633. /** For a click event, the number of times the mouse was clicked in succession.
  11634. So for example a double-click event will return 2, a triple-click 3, etc.
  11635. */
  11636. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11637. /** Returns the time that the mouse button has been held down for.
  11638. If called from a mouseDrag or mouseUp callback, this will return the
  11639. number of milliseconds since the corresponding mouseDown event occurred.
  11640. If called in other contexts, e.g. a mouseMove, then the returned value
  11641. may be 0 or an undefined value.
  11642. */
  11643. int getLengthOfMousePress() const throw();
  11644. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11645. The co-ordinates are relative to the top-left of the main monitor.
  11646. @see getMouseDownScreenX, Desktop::getMousePosition
  11647. */
  11648. int getScreenX() const throw();
  11649. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11650. The co-ordinates are relative to the top-left of the main monitor.
  11651. @see getMouseDownScreenY, Desktop::getMousePosition
  11652. */
  11653. int getScreenY() const throw();
  11654. /** Returns the x co-ordinate at which the mouse button was last pressed.
  11655. The co-ordinates are relative to the top-left of the main monitor.
  11656. @see getScreenX, Desktop::getMousePosition
  11657. */
  11658. int getMouseDownScreenX() const throw();
  11659. /** Returns the y co-ordinate at which the mouse button was last pressed.
  11660. The co-ordinates are relative to the top-left of the main monitor.
  11661. @see getScreenY, Desktop::getMousePosition
  11662. */
  11663. int getMouseDownScreenY() const throw();
  11664. /** Creates a version of this event that is relative to a different component.
  11665. The x and y positions of the event that is returned will have been
  11666. adjusted to be relative to the new component.
  11667. */
  11668. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  11669. /** Changes the application-wide setting for the double-click time limit.
  11670. This is the maximum length of time between mouse-clicks for it to be
  11671. considered a double-click. It's used by the Component class.
  11672. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  11673. */
  11674. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  11675. /** Returns the application-wide setting for the double-click time limit.
  11676. This is the maximum length of time between mouse-clicks for it to be
  11677. considered a double-click. It's used by the Component class.
  11678. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  11679. */
  11680. static int getDoubleClickTimeout() throw();
  11681. juce_UseDebuggingNewOperator
  11682. private:
  11683. int mouseDownX, mouseDownY;
  11684. Time mouseDownTime;
  11685. int numberOfClicks;
  11686. bool wasMovedSinceMouseDown;
  11687. };
  11688. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  11689. /********* End of inlined file: juce_MouseEvent.h *********/
  11690. /**
  11691. A MouseListener can be registered with a component to receive callbacks
  11692. about mouse events that happen to that component.
  11693. @see Component::addMouseListener, Component::removeMouseListener
  11694. */
  11695. class JUCE_API MouseListener
  11696. {
  11697. public:
  11698. /** Destructor. */
  11699. virtual ~MouseListener() {}
  11700. /** Called when the mouse moves inside a component.
  11701. If the mouse button isn't pressed and the mouse moves over a component,
  11702. this will be called to let the component react to this.
  11703. A component will always get a mouseEnter callback before a mouseMove.
  11704. @param e details about the position and status of the mouse event, including
  11705. the source component in which it occurred
  11706. @see mouseEnter, mouseExit, mouseDrag, contains
  11707. */
  11708. virtual void mouseMove (const MouseEvent& e);
  11709. /** Called when the mouse first enters a component.
  11710. If the mouse button isn't pressed and the mouse moves into a component,
  11711. this will be called to let the component react to this.
  11712. When the mouse button is pressed and held down while being moved in
  11713. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  11714. mouseDrag messages are sent to the component that the mouse was originally
  11715. clicked on, until the button is released.
  11716. @param e details about the position and status of the mouse event, including
  11717. the source component in which it occurred
  11718. @see mouseExit, mouseDrag, mouseMove, contains
  11719. */
  11720. virtual void mouseEnter (const MouseEvent& e);
  11721. /** Called when the mouse moves out of a component.
  11722. This will be called when the mouse moves off the edge of this
  11723. component.
  11724. If the mouse button was pressed, and it was then dragged off the
  11725. edge of the component and released, then this callback will happen
  11726. when the button is released, after the mouseUp callback.
  11727. @param e details about the position and status of the mouse event, including
  11728. the source component in which it occurred
  11729. @see mouseEnter, mouseDrag, mouseMove, contains
  11730. */
  11731. virtual void mouseExit (const MouseEvent& e);
  11732. /** Called when a mouse button is pressed.
  11733. The MouseEvent object passed in contains lots of methods for finding out
  11734. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11735. were held down at the time.
  11736. Once a button is held down, the mouseDrag method will be called when the
  11737. mouse moves, until the button is released.
  11738. @param e details about the position and status of the mouse event, including
  11739. the source component in which it occurred
  11740. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  11741. */
  11742. virtual void mouseDown (const MouseEvent& e);
  11743. /** Called when the mouse is moved while a button is held down.
  11744. When a mouse button is pressed inside a component, that component
  11745. receives mouseDrag callbacks each time the mouse moves, even if the
  11746. mouse strays outside the component's bounds.
  11747. @param e details about the position and status of the mouse event, including
  11748. the source component in which it occurred
  11749. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  11750. */
  11751. virtual void mouseDrag (const MouseEvent& e);
  11752. /** Called when a mouse button is released.
  11753. A mouseUp callback is sent to the component in which a button was pressed
  11754. even if the mouse is actually over a different component when the
  11755. button is released.
  11756. The MouseEvent object passed in contains lots of methods for finding out
  11757. which buttons were down just before they were released.
  11758. @param e details about the position and status of the mouse event, including
  11759. the source component in which it occurred
  11760. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  11761. */
  11762. virtual void mouseUp (const MouseEvent& e);
  11763. /** Called when a mouse button has been double-clicked on a component.
  11764. The MouseEvent object passed in contains lots of methods for finding out
  11765. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11766. were held down at the time.
  11767. @param e details about the position and status of the mouse event, including
  11768. the source component in which it occurred
  11769. @see mouseDown, mouseUp
  11770. */
  11771. virtual void mouseDoubleClick (const MouseEvent& e);
  11772. /** Called when the mouse-wheel is moved.
  11773. This callback is sent to the component that the mouse is over when the
  11774. wheel is moved.
  11775. If not overridden, the component will forward this message to its parent, so
  11776. that parent components can collect mouse-wheel messages that happen to
  11777. child components which aren't interested in them.
  11778. @param e details about the position and status of the mouse event, including
  11779. the source component in which it occurred
  11780. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  11781. value means the wheel has been pushed to the right, negative means it
  11782. was pushed to the left
  11783. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  11784. value means the wheel has been pushed upwards, negative means it
  11785. was pushed downwards
  11786. */
  11787. virtual void mouseWheelMove (const MouseEvent& e,
  11788. float wheelIncrementX,
  11789. float wheelIncrementY);
  11790. private:
  11791. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  11792. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  11793. // if that happens, update your code to use the new one above.
  11794. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  11795. };
  11796. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  11797. /********* End of inlined file: juce_MouseListener.h *********/
  11798. /********* Start of inlined file: juce_ComponentListener.h *********/
  11799. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11800. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11801. class Component;
  11802. /**
  11803. Gets informed about changes to a component's hierarchy or position.
  11804. To monitor a component for changes, register a subclass of ComponentListener
  11805. with the component using Component::addComponentListener().
  11806. Be sure to deregister listeners before you delete them!
  11807. @see Component::addComponentListener, Component::removeComponentListener
  11808. */
  11809. class JUCE_API ComponentListener
  11810. {
  11811. public:
  11812. /** Destructor. */
  11813. virtual ~ComponentListener() {}
  11814. /** Called when the component's position or size changes.
  11815. @param component the component that was moved or resized
  11816. @param wasMoved true if the component's top-left corner has just moved
  11817. @param wasResized true if the component's width or height has just changed
  11818. @see Component::setBounds, Component::resized, Component::moved
  11819. */
  11820. virtual void componentMovedOrResized (Component& component,
  11821. bool wasMoved,
  11822. bool wasResized);
  11823. /** Called when the component is brought to the top of the z-order.
  11824. @param component the component that was moved
  11825. @see Component::toFront, Component::broughtToFront
  11826. */
  11827. virtual void componentBroughtToFront (Component& component);
  11828. /** Called when the component is made visible or invisible.
  11829. @param component the component that changed
  11830. @see Component::setVisible
  11831. */
  11832. virtual void componentVisibilityChanged (Component& component);
  11833. /** Called when the component has children added or removed.
  11834. @param component the component whose children were changed
  11835. @see Component::childrenChanged, Component::addChildComponent,
  11836. Component::removeChildComponent
  11837. */
  11838. virtual void componentChildrenChanged (Component& component);
  11839. /** Called to indicate that the component's parents have changed.
  11840. When a component is added or removed from its parent, all of its children
  11841. will produce this notification (recursively - so all children of its
  11842. children will also be called as well).
  11843. @param component the component that this listener is registered with
  11844. @see Component::parentHierarchyChanged
  11845. */
  11846. virtual void componentParentHierarchyChanged (Component& component);
  11847. /** Called when the component's name is changed.
  11848. @see Component::setName, Component::getName
  11849. */
  11850. virtual void componentNameChanged (Component& component);
  11851. };
  11852. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  11853. /********* End of inlined file: juce_ComponentListener.h *********/
  11854. /********* Start of inlined file: juce_KeyListener.h *********/
  11855. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  11856. #define __JUCE_KEYLISTENER_JUCEHEADER__
  11857. /********* Start of inlined file: juce_KeyPress.h *********/
  11858. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  11859. #define __JUCE_KEYPRESS_JUCEHEADER__
  11860. /**
  11861. Represents a key press, including any modifier keys that are needed.
  11862. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  11863. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  11864. */
  11865. class JUCE_API KeyPress
  11866. {
  11867. public:
  11868. /** Creates an (invalid) KeyPress.
  11869. @see isValid
  11870. */
  11871. KeyPress() throw();
  11872. /** Creates a KeyPress for a key and some modifiers.
  11873. e.g.
  11874. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  11875. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  11876. @param keyCode a code that represents the key - this value must be
  11877. one of special constants listed in this class, or an
  11878. 8-bit character code such as a letter (case is ignored),
  11879. digit or a simple key like "," or ".". Note that this
  11880. isn't the same as the textCharacter parameter, so for example
  11881. a keyCode of 'a' and a shift-key modifier should have a
  11882. textCharacter value of 'A'.
  11883. @param modifiers the modifiers to associate with the keystroke
  11884. @param textCharacter the character that would be printed if someone typed
  11885. this keypress into a text editor. This value may be
  11886. null if the keypress is a non-printing character
  11887. @see getKeyCode, isKeyCode, getModifiers
  11888. */
  11889. KeyPress (const int keyCode,
  11890. const ModifierKeys& modifiers,
  11891. const juce_wchar textCharacter) throw();
  11892. /** Creates a keypress with a keyCode but no modifiers or text character.
  11893. */
  11894. KeyPress (const int keyCode) throw();
  11895. /** Creates a copy of another KeyPress. */
  11896. KeyPress (const KeyPress& other) throw();
  11897. /** Copies this KeyPress from another one. */
  11898. const KeyPress& operator= (const KeyPress& other) throw();
  11899. /** Compares two KeyPress objects. */
  11900. bool operator== (const KeyPress& other) const throw();
  11901. /** Compares two KeyPress objects. */
  11902. bool operator!= (const KeyPress& other) const throw();
  11903. /** Returns true if this is a valid KeyPress.
  11904. A null keypress can be created by the default constructor, in case it's
  11905. needed.
  11906. */
  11907. bool isValid() const throw() { return keyCode != 0; }
  11908. /** Returns the key code itself.
  11909. This will either be one of the special constants defined in this class,
  11910. or an 8-bit character code.
  11911. */
  11912. int getKeyCode() const throw() { return keyCode; }
  11913. /** Returns the key modifiers.
  11914. @see ModifierKeys
  11915. */
  11916. const ModifierKeys getModifiers() const throw() { return mods; }
  11917. /** Returns the character that is associated with this keypress.
  11918. This is the character that you'd expect to see printed if you press this
  11919. keypress in a text editor or similar component.
  11920. */
  11921. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  11922. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  11923. the modifiers.
  11924. The values for key codes can either be one of the special constants defined in
  11925. this class, or an 8-bit character code.
  11926. @see getKeyCode
  11927. */
  11928. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  11929. /** Converts a textual key description to a KeyPress.
  11930. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  11931. This isn't designed to cope with any kind of input, but should be given the
  11932. strings that are created by the getTextDescription() method.
  11933. If the string can't be parsed, the object returned will be invalid.
  11934. @see getTextDescription
  11935. */
  11936. static const KeyPress createFromDescription (const String& textVersion) throw();
  11937. /** Creates a textual description of the key combination.
  11938. e.g. "CTRL + C" or "DELETE".
  11939. To store a keypress in a file, use this method, along with createFromDescription()
  11940. to retrieve it later.
  11941. */
  11942. const String getTextDescription() const throw();
  11943. /** Checks whether the user is currently holding down the keys that make up this
  11944. KeyPress.
  11945. Note that this will return false if any extra modifier keys are
  11946. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  11947. then it will be false.
  11948. */
  11949. bool isCurrentlyDown() const throw();
  11950. /** Checks whether a particular key is held down, irrespective of modifiers.
  11951. The values for key codes can either be one of the special constants defined in
  11952. this class, or an 8-bit character code.
  11953. */
  11954. static bool isKeyCurrentlyDown (int keyCode) throw();
  11955. // Key codes
  11956. //
  11957. // Note that the actual values of these are platform-specific and may change
  11958. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  11959. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  11960. //
  11961. static const int spaceKey; /**< key-code for the space bar */
  11962. static const int escapeKey; /**< key-code for the escape key */
  11963. static const int returnKey; /**< key-code for the return key*/
  11964. static const int tabKey; /**< key-code for the tab key*/
  11965. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  11966. static const int backspaceKey; /**< key-code for the backspace key */
  11967. static const int insertKey; /**< key-code for the insert key */
  11968. static const int upKey; /**< key-code for the cursor-up key */
  11969. static const int downKey; /**< key-code for the cursor-down key */
  11970. static const int leftKey; /**< key-code for the cursor-left key */
  11971. static const int rightKey; /**< key-code for the cursor-right key */
  11972. static const int pageUpKey; /**< key-code for the page-up key */
  11973. static const int pageDownKey; /**< key-code for the page-down key */
  11974. static const int homeKey; /**< key-code for the home key */
  11975. static const int endKey; /**< key-code for the end key */
  11976. static const int F1Key; /**< key-code for the F1 key */
  11977. static const int F2Key; /**< key-code for the F2 key */
  11978. static const int F3Key; /**< key-code for the F3 key */
  11979. static const int F4Key; /**< key-code for the F4 key */
  11980. static const int F5Key; /**< key-code for the F5 key */
  11981. static const int F6Key; /**< key-code for the F6 key */
  11982. static const int F7Key; /**< key-code for the F7 key */
  11983. static const int F8Key; /**< key-code for the F8 key */
  11984. static const int F9Key; /**< key-code for the F9 key */
  11985. static const int F10Key; /**< key-code for the F10 key */
  11986. static const int F11Key; /**< key-code for the F11 key */
  11987. static const int F12Key; /**< key-code for the F12 key */
  11988. static const int F13Key; /**< key-code for the F13 key */
  11989. static const int F14Key; /**< key-code for the F14 key */
  11990. static const int F15Key; /**< key-code for the F15 key */
  11991. static const int F16Key; /**< key-code for the F16 key */
  11992. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  11993. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  11994. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  11995. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  11996. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  11997. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  11998. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  11999. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  12000. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  12001. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  12002. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  12003. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  12004. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  12005. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  12006. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  12007. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  12008. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  12009. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  12010. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  12011. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  12012. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  12013. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  12014. juce_UseDebuggingNewOperator
  12015. private:
  12016. int keyCode;
  12017. ModifierKeys mods;
  12018. juce_wchar textCharacter;
  12019. };
  12020. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  12021. /********* End of inlined file: juce_KeyPress.h *********/
  12022. class Component;
  12023. /**
  12024. Receives callbacks when keys are pressed.
  12025. You can add a key listener to a component to be informed when that component
  12026. gets key events. See the Component::addListener method for more details.
  12027. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  12028. */
  12029. class JUCE_API KeyListener
  12030. {
  12031. public:
  12032. /** Destructor. */
  12033. virtual ~KeyListener() {}
  12034. /** Called to indicate that a key has been pressed.
  12035. If your implementation returns true, then the key event is considered to have
  12036. been consumed, and will not be passed on to any other components. If it returns
  12037. false, then the key will be passed to other components that might want to use it.
  12038. @param key the keystroke, including modifier keys
  12039. @param originatingComponent the component that received the key event
  12040. @see keyStateChanged, Component::keyPressed
  12041. */
  12042. virtual bool keyPressed (const KeyPress& key,
  12043. Component* originatingComponent) = 0;
  12044. /** Called when any key is pressed or released.
  12045. When this is called, classes that might be interested in
  12046. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  12047. check whether their key has changed.
  12048. If your implementation returns true, then the key event is considered to have
  12049. been consumed, and will not be passed on to any other components. If it returns
  12050. false, then the key will be passed to other components that might want to use it.
  12051. @param originatingComponent the component that received the key event
  12052. @see KeyPress, Component::keyStateChanged
  12053. */
  12054. virtual bool keyStateChanged (Component* originatingComponent);
  12055. };
  12056. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  12057. /********* End of inlined file: juce_KeyListener.h *********/
  12058. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  12059. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12060. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12061. class Component;
  12062. /**
  12063. Controls the order in which focus moves between components.
  12064. The default algorithm used by this class to work out the order of traversal
  12065. is as follows:
  12066. - if two components both have an explicit focus order specified, then the
  12067. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  12068. method).
  12069. - any component with an explicit focus order greater than 0 comes before ones
  12070. that don't have an order specified.
  12071. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  12072. order.
  12073. If you need traversal in a more customised way, you can create a subclass
  12074. of KeyboardFocusTraverser that uses your own algorithm, and use
  12075. Component::createFocusTraverser() to create it.
  12076. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  12077. */
  12078. class JUCE_API KeyboardFocusTraverser
  12079. {
  12080. public:
  12081. KeyboardFocusTraverser();
  12082. /** Destructor. */
  12083. virtual ~KeyboardFocusTraverser();
  12084. /** Returns the component that should be given focus after the specified one
  12085. when moving "forwards".
  12086. The default implementation will return the next component which is to the
  12087. right of or below this one.
  12088. This may return 0 if there's no suitable candidate.
  12089. */
  12090. virtual Component* getNextComponent (Component* current);
  12091. /** Returns the component that should be given focus after the specified one
  12092. when moving "backwards".
  12093. The default implementation will return the next component which is to the
  12094. left of or above this one.
  12095. This may return 0 if there's no suitable candidate.
  12096. */
  12097. virtual Component* getPreviousComponent (Component* current);
  12098. /** Returns the component that should receive focus be default within the given
  12099. parent component.
  12100. The default implementation will just return the foremost child component that
  12101. wants focus.
  12102. This may return 0 if there's no suitable candidate.
  12103. */
  12104. virtual Component* getDefaultComponent (Component* parentComponent);
  12105. };
  12106. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12107. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12108. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12109. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12110. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12111. /********* Start of inlined file: juce_Graphics.h *********/
  12112. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12113. #define __JUCE_GRAPHICS_JUCEHEADER__
  12114. /********* Start of inlined file: juce_Font.h *********/
  12115. #ifndef __JUCE_FONT_JUCEHEADER__
  12116. #define __JUCE_FONT_JUCEHEADER__
  12117. /********* Start of inlined file: juce_Typeface.h *********/
  12118. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12119. #define __JUCE_TYPEFACE_JUCEHEADER__
  12120. /********* Start of inlined file: juce_Path.h *********/
  12121. #ifndef __JUCE_PATH_JUCEHEADER__
  12122. #define __JUCE_PATH_JUCEHEADER__
  12123. /********* Start of inlined file: juce_AffineTransform.h *********/
  12124. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12125. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12126. /**
  12127. Represents a 2D affine-transformation matrix.
  12128. An affine transformation is a transformation such as a rotation, scale, shear,
  12129. resize or translation.
  12130. These are used for various 2D transformation tasks, e.g. with Path objects.
  12131. @see Path, Point, Line
  12132. */
  12133. class JUCE_API AffineTransform
  12134. {
  12135. public:
  12136. /** Creates an identity transform. */
  12137. AffineTransform() throw();
  12138. /** Creates a copy of another transform. */
  12139. AffineTransform (const AffineTransform& other) throw();
  12140. /** Creates a transform from a set of raw matrix values.
  12141. The resulting matrix is:
  12142. (mat00 mat01 mat02)
  12143. (mat10 mat11 mat12)
  12144. ( 0 0 1 )
  12145. */
  12146. AffineTransform (const float mat00, const float mat01, const float mat02,
  12147. const float mat10, const float mat11, const float mat12) throw();
  12148. /** Copies from another AffineTransform object */
  12149. const AffineTransform& operator= (const AffineTransform& other) throw();
  12150. /** Compares two transforms. */
  12151. bool operator== (const AffineTransform& other) const throw();
  12152. /** Compares two transforms. */
  12153. bool operator!= (const AffineTransform& other) const throw();
  12154. /** A ready-to-use identity transform, which you can use to append other
  12155. transformations to.
  12156. e.g. @code
  12157. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12158. .scaled (2.0f);
  12159. @endcode
  12160. */
  12161. static const AffineTransform identity;
  12162. /** Transforms a 2D co-ordinate using this matrix. */
  12163. void transformPoint (float& x,
  12164. float& y) const throw();
  12165. /** Transforms a 2D co-ordinate using this matrix. */
  12166. void transformPoint (double& x,
  12167. double& y) const throw();
  12168. /** Returns a new transform which is the same as this one followed by a translation. */
  12169. const AffineTransform translated (const float deltaX,
  12170. const float deltaY) const throw();
  12171. /** Returns a new transform which is a translation. */
  12172. static const AffineTransform translation (const float deltaX,
  12173. const float deltaY) throw();
  12174. /** Returns a transform which is the same as this one followed by a rotation.
  12175. The rotation is specified by a number of radians to rotate clockwise, centred around
  12176. the origin (0, 0).
  12177. */
  12178. const AffineTransform rotated (const float angleInRadians) const throw();
  12179. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12180. The rotation is specified by a number of radians to rotate clockwise, centred around
  12181. the co-ordinates passed in.
  12182. */
  12183. const AffineTransform rotated (const float angleInRadians,
  12184. const float pivotX,
  12185. const float pivotY) const throw();
  12186. /** Returns a new transform which is a rotation about (0, 0). */
  12187. static const AffineTransform rotation (const float angleInRadians) throw();
  12188. /** Returns a new transform which is a rotation about a given point. */
  12189. static const AffineTransform rotation (const float angleInRadians,
  12190. const float pivotX,
  12191. const float pivotY) throw();
  12192. /** Returns a transform which is the same as this one followed by a re-scaling.
  12193. The scaling is centred around the origin (0, 0).
  12194. */
  12195. const AffineTransform scaled (const float factorX,
  12196. const float factorY) const throw();
  12197. /** Returns a new transform which is a re-scale about the origin. */
  12198. static const AffineTransform scale (const float factorX,
  12199. const float factorY) throw();
  12200. /** Returns a transform which is the same as this one followed by a shear.
  12201. The shear is centred around the origin (0, 0).
  12202. */
  12203. const AffineTransform sheared (const float shearX,
  12204. const float shearY) const throw();
  12205. /** Returns a matrix which is the inverse operation of this one.
  12206. Some matrices don't have an inverse - in this case, the method will just return
  12207. an identity transform.
  12208. */
  12209. const AffineTransform inverted() const throw();
  12210. /** Returns the result of concatenating another transformation after this one. */
  12211. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12212. /** Returns true if this transform has no effect on points. */
  12213. bool isIdentity() const throw();
  12214. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12215. bool isSingularity() const throw();
  12216. juce_UseDebuggingNewOperator
  12217. /* The transform matrix is:
  12218. (mat00 mat01 mat02)
  12219. (mat10 mat11 mat12)
  12220. ( 0 0 1 )
  12221. */
  12222. float mat00, mat01, mat02;
  12223. float mat10, mat11, mat12;
  12224. private:
  12225. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12226. const float mat10, const float mat11, const float mat12) const throw();
  12227. };
  12228. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12229. /********* End of inlined file: juce_AffineTransform.h *********/
  12230. /********* Start of inlined file: juce_Point.h *********/
  12231. #ifndef __JUCE_POINT_JUCEHEADER__
  12232. #define __JUCE_POINT_JUCEHEADER__
  12233. /**
  12234. A pair of (x, y) co-ordinates.
  12235. Uses 32-bit floating point accuracy.
  12236. @see Line, Path, AffineTransform
  12237. */
  12238. class JUCE_API Point
  12239. {
  12240. public:
  12241. /** Creates a point with co-ordinates (0, 0). */
  12242. Point() throw();
  12243. /** Creates a copy of another point. */
  12244. Point (const Point& other) throw();
  12245. /** Creates a point from an (x, y) position. */
  12246. Point (const float x, const float y) throw();
  12247. /** Copies this point from another one.
  12248. @see setXY
  12249. */
  12250. const Point& operator= (const Point& other) throw();
  12251. /** Destructor. */
  12252. ~Point() throw();
  12253. /** Returns the point's x co-ordinate. */
  12254. inline float getX() const throw() { return x; }
  12255. /** Returns the point's y co-ordinate. */
  12256. inline float getY() const throw() { return y; }
  12257. /** Changes the point's x and y co-ordinates. */
  12258. void setXY (const float x,
  12259. const float y) throw();
  12260. /** Uses a transform to change the point's co-ordinates.
  12261. @see AffineTransform::transformPoint
  12262. */
  12263. void applyTransform (const AffineTransform& transform) throw();
  12264. juce_UseDebuggingNewOperator
  12265. private:
  12266. float x, y;
  12267. };
  12268. #endif // __JUCE_POINT_JUCEHEADER__
  12269. /********* End of inlined file: juce_Point.h *********/
  12270. /********* Start of inlined file: juce_Justification.h *********/
  12271. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12272. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12273. /**
  12274. Represents a type of justification to be used when positioning graphical items.
  12275. e.g. it indicates whether something should be placed top-left, top-right,
  12276. centred, etc.
  12277. It is used in various places wherever this kind of information is needed.
  12278. */
  12279. class JUCE_API Justification
  12280. {
  12281. public:
  12282. /** Creates a Justification object using a combination of flags. */
  12283. inline Justification (const int flags_) throw() : flags (flags_) {}
  12284. /** Creates a copy of another Justification object. */
  12285. Justification (const Justification& other) throw();
  12286. /** Copies another Justification object. */
  12287. const Justification& operator= (const Justification& other) throw();
  12288. /** Returns the raw flags that are set for this Justification object. */
  12289. inline int getFlags() const throw() { return flags; }
  12290. /** Tests a set of flags for this object.
  12291. @returns true if any of the flags passed in are set on this object.
  12292. */
  12293. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12294. /** Returns just the flags from this object that deal with vertical layout. */
  12295. int getOnlyVerticalFlags() const throw();
  12296. /** Returns just the flags from this object that deal with horizontal layout. */
  12297. int getOnlyHorizontalFlags() const throw();
  12298. /** Adjusts the position of a rectangle to fit it into a space.
  12299. The (x, y) position of the rectangle will be updated to position it inside the
  12300. given space according to the justification flags.
  12301. */
  12302. void applyToRectangle (int& x, int& y,
  12303. const int w, const int h,
  12304. const int spaceX, const int spaceY,
  12305. const int spaceW, const int spaceH) const throw();
  12306. /** Flag values that can be combined and used in the constructor. */
  12307. enum
  12308. {
  12309. /** Indicates that the item should be aligned against the left edge of the available space. */
  12310. left = 1,
  12311. /** Indicates that the item should be aligned against the right edge of the available space. */
  12312. right = 2,
  12313. /** Indicates that the item should be placed in the centre between the left and right
  12314. sides of the available space. */
  12315. horizontallyCentred = 4,
  12316. /** Indicates that the item should be aligned against the top edge of the available space. */
  12317. top = 8,
  12318. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12319. bottom = 16,
  12320. /** Indicates that the item should be placed in the centre between the top and bottom
  12321. sides of the available space. */
  12322. verticallyCentred = 32,
  12323. /** Indicates that lines of text should be spread out to fill the maximum width
  12324. available, so that both margins are aligned vertically.
  12325. */
  12326. horizontallyJustified = 64,
  12327. /** Indicates that the item should be centred vertically and horizontally.
  12328. This is equivalent to (horizontallyCentred | verticallyCentred)
  12329. */
  12330. centred = 36,
  12331. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12332. This is equivalent to (left | verticallyCentred)
  12333. */
  12334. centredLeft = 33,
  12335. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12336. This is equivalent to (right | verticallyCentred)
  12337. */
  12338. centredRight = 34,
  12339. /** Indicates that the item should be centred horizontally and placed at the top.
  12340. This is equivalent to (horizontallyCentred | top)
  12341. */
  12342. centredTop = 12,
  12343. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12344. This is equivalent to (horizontallyCentred | bottom)
  12345. */
  12346. centredBottom = 20,
  12347. /** Indicates that the item should be placed in the top-left corner.
  12348. This is equivalent to (left | top)
  12349. */
  12350. topLeft = 9,
  12351. /** Indicates that the item should be placed in the top-right corner.
  12352. This is equivalent to (right | top)
  12353. */
  12354. topRight = 10,
  12355. /** Indicates that the item should be placed in the bottom-left corner.
  12356. This is equivalent to (left | bottom)
  12357. */
  12358. bottomLeft = 17,
  12359. /** Indicates that the item should be placed in the bottom-left corner.
  12360. This is equivalent to (right | bottom)
  12361. */
  12362. bottomRight = 18
  12363. };
  12364. private:
  12365. int flags;
  12366. };
  12367. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12368. /********* End of inlined file: juce_Justification.h *********/
  12369. /**
  12370. A path is a sequence of lines and curves that may either form a closed shape
  12371. or be open-ended.
  12372. To use a path, you can create an empty one, then add lines and curves to it
  12373. to create shapes, then it can be rendered by a Graphics context or used
  12374. for geometric operations.
  12375. e.g. @code
  12376. Path myPath;
  12377. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  12378. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  12379. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  12380. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  12381. // add an ellipse as well, which will form a second sub-path within the path..
  12382. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  12383. // double the width of the whole thing..
  12384. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  12385. // and draw it to a graphics context with a 5-pixel thick outline.
  12386. g.strokePath (myPath, PathStrokeType (5.0f));
  12387. @endcode
  12388. A path object can actually contain multiple sub-paths, which may themselves
  12389. be open or closed.
  12390. @see PathFlatteningIterator, PathStrokeType, Graphics
  12391. */
  12392. class JUCE_API Path : private ArrayAllocationBase <float>
  12393. {
  12394. public:
  12395. /** Creates an empty path. */
  12396. Path() throw();
  12397. /** Creates a copy of another path. */
  12398. Path (const Path& other) throw();
  12399. /** Destructor. */
  12400. ~Path() throw();
  12401. /** Copies this path from another one. */
  12402. const Path& operator= (const Path& other) throw();
  12403. /** Returns true if the path doesn't contain any lines or curves. */
  12404. bool isEmpty() const throw();
  12405. /** Returns the smallest rectangle that contains all points within the path.
  12406. */
  12407. void getBounds (float& x, float& y,
  12408. float& w, float& h) const throw();
  12409. /** Returns the smallest rectangle that contains all points within the path
  12410. after it's been transformed with the given tranasform matrix.
  12411. */
  12412. void getBoundsTransformed (const AffineTransform& transform,
  12413. float& x, float& y,
  12414. float& w, float& h) const throw();
  12415. /** Checks whether a point lies within the path.
  12416. This is only relevent for closed paths (see closeSubPath()), and
  12417. may produce false results if used on a path which has open sub-paths.
  12418. The path's winding rule is taken into account by this method.
  12419. @see closeSubPath, setUsingNonZeroWinding
  12420. */
  12421. bool contains (const float x,
  12422. const float y) const throw();
  12423. /** Checks whether a line crosses the path.
  12424. This will return positive if the line crosses any of the paths constituent
  12425. lines or curves. It doesn't take into account whether the line is inside
  12426. or outside the path, or whether the path is open or closed.
  12427. */
  12428. bool intersectsLine (const float x1, const float y1,
  12429. const float x2, const float y2) throw();
  12430. /** Removes all lines and curves, resetting the path completely. */
  12431. void clear() throw();
  12432. /** Begins a new subpath with a given starting position.
  12433. This will move the path's current position to the co-ordinates passed in and
  12434. make it ready to draw lines or curves starting from this position.
  12435. After adding whatever lines and curves are needed, you can either
  12436. close the current sub-path using closeSubPath() or call startNewSubPath()
  12437. to move to a new sub-path, leaving the old one open-ended.
  12438. @see lineTo, quadraticTo, cubicTo, closeSubPath
  12439. */
  12440. void startNewSubPath (const float startX,
  12441. const float startY) throw();
  12442. /** Closes a the current sub-path with a line back to its start-point.
  12443. When creating a closed shape such as a triangle, don't use 3 lineTo()
  12444. calls - instead use two lineTo() calls, followed by a closeSubPath()
  12445. to join the final point back to the start.
  12446. This ensures that closes shapes are recognised as such, and this is
  12447. important for tasks like drawing strokes, which needs to know whether to
  12448. draw end-caps or not.
  12449. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  12450. */
  12451. void closeSubPath() throw();
  12452. /** Adds a line from the shape's last position to a new end-point.
  12453. This will connect the end-point of the last line or curve that was added
  12454. to a new point, using a straight line.
  12455. See the class description for an example of how to add lines and curves to a path.
  12456. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  12457. */
  12458. void lineTo (const float endX,
  12459. const float endY) throw();
  12460. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  12461. This will connect the end-point of the last line or curve that was added
  12462. to a new point, using a quadratic spline with one control-point.
  12463. See the class description for an example of how to add lines and curves to a path.
  12464. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  12465. */
  12466. void quadraticTo (const float controlPointX,
  12467. const float controlPointY,
  12468. const float endPointX,
  12469. const float endPointY) throw();
  12470. /** Adds a cubic bezier curve from the shape's last position to a new position.
  12471. This will connect the end-point of the last line or curve that was added
  12472. to a new point, using a cubic spline with two control-points.
  12473. See the class description for an example of how to add lines and curves to a path.
  12474. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  12475. */
  12476. void cubicTo (const float controlPoint1X,
  12477. const float controlPoint1Y,
  12478. const float controlPoint2X,
  12479. const float controlPoint2Y,
  12480. const float endPointX,
  12481. const float endPointY) throw();
  12482. /** Returns the last point that was added to the path by one of the drawing methods.
  12483. */
  12484. const Point getCurrentPosition() const;
  12485. /** Adds a rectangle to the path.
  12486. The rectangle is added as a new sub-path. (Any currently open paths will be
  12487. left open).
  12488. @see addRoundedRectangle, addTriangle
  12489. */
  12490. void addRectangle (const float x, const float y,
  12491. const float w, const float h) throw();
  12492. /** Adds a rectangle with rounded corners to the path.
  12493. The rectangle is added as a new sub-path. (Any currently open paths will be
  12494. left open).
  12495. @see addRectangle, addTriangle
  12496. */
  12497. void addRoundedRectangle (const float x, const float y,
  12498. const float w, const float h,
  12499. float cornerSize) throw();
  12500. /** Adds a rectangle with rounded corners to the path.
  12501. The rectangle is added as a new sub-path. (Any currently open paths will be
  12502. left open).
  12503. @see addRectangle, addTriangle
  12504. */
  12505. void addRoundedRectangle (const float x, const float y,
  12506. const float w, const float h,
  12507. float cornerSizeX,
  12508. float cornerSizeY) throw();
  12509. /** Adds a triangle to the path.
  12510. The triangle is added as a new closed sub-path. (Any currently open paths will be
  12511. left open).
  12512. Note that whether the vertices are specified in clockwise or anticlockwise
  12513. order will affect how the triangle is filled when it overlaps other
  12514. shapes (the winding order setting will affect this of course).
  12515. */
  12516. void addTriangle (const float x1, const float y1,
  12517. const float x2, const float y2,
  12518. const float x3, const float y3) throw();
  12519. /** Adds a quadrilateral to the path.
  12520. The quad is added as a new closed sub-path. (Any currently open paths will be
  12521. left open).
  12522. Note that whether the vertices are specified in clockwise or anticlockwise
  12523. order will affect how the quad is filled when it overlaps other
  12524. shapes (the winding order setting will affect this of course).
  12525. */
  12526. void addQuadrilateral (const float x1, const float y1,
  12527. const float x2, const float y2,
  12528. const float x3, const float y3,
  12529. const float x4, const float y4) throw();
  12530. /** Adds an ellipse to the path.
  12531. The shape is added as a new sub-path. (Any currently open paths will be
  12532. left open).
  12533. @see addArc
  12534. */
  12535. void addEllipse (const float x, const float y,
  12536. const float width, const float height) throw();
  12537. /** Adds an elliptical arc to the current path.
  12538. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12539. or anti-clockwise according to whether the end angle is greater than the start. This means
  12540. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12541. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12542. @param y the top edge of the rectangle in which the elliptical outline fits
  12543. @param width the width of the rectangle in which the elliptical outline fits
  12544. @param height the height of the rectangle in which the elliptical outline fits
  12545. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12546. top-centre of the ellipse)
  12547. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12548. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12549. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12550. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12551. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12552. it will be added to the current sub-path, continuing from the current postition
  12553. @see addCentredArc, arcTo, addPieSegment, addEllipse
  12554. */
  12555. void addArc (const float x, const float y,
  12556. const float width, const float height,
  12557. const float fromRadians,
  12558. const float toRadians,
  12559. const bool startAsNewSubPath = false) throw();
  12560. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  12561. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12562. or anti-clockwise according to whether the end angle is greater than the start. This means
  12563. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12564. @param centreX the centre x of the ellipse
  12565. @param centreY the centre y of the ellipse
  12566. @param radiusX the horizontal radius of the ellipse
  12567. @param radiusY the vertical radius of the ellipse
  12568. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  12569. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12570. top-centre of the ellipse)
  12571. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12572. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12573. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12574. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12575. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12576. it will be added to the current sub-path, continuing from the current postition
  12577. @see addArc, arcTo
  12578. */
  12579. void addCentredArc (const float centreX, const float centreY,
  12580. const float radiusX, const float radiusY,
  12581. const float rotationOfEllipse,
  12582. const float fromRadians,
  12583. const float toRadians,
  12584. const bool startAsNewSubPath = false) throw();
  12585. /** Adds a "pie-chart" shape to the path.
  12586. The shape is added as a new sub-path. (Any currently open paths will be
  12587. left open).
  12588. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12589. or anti-clockwise according to whether the end angle is greater than the start. This means
  12590. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12591. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12592. @param y the top edge of the rectangle in which the elliptical outline fits
  12593. @param width the width of the rectangle in which the elliptical outline fits
  12594. @param height the height of the rectangle in which the elliptical outline fits
  12595. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12596. top-centre of the ellipse)
  12597. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12598. top-centre of the ellipse)
  12599. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  12600. ellipse at its centre, where this value indicates the inner ellipse's size with
  12601. respect to the outer one.
  12602. @see addArc
  12603. */
  12604. void addPieSegment (const float x, const float y,
  12605. const float width, const float height,
  12606. const float fromRadians,
  12607. const float toRadians,
  12608. const float innerCircleProportionalSize);
  12609. /** Adds a line with a specified thickness.
  12610. The line is added as a new closed sub-path. (Any currently open paths will be
  12611. left open).
  12612. @see addArrow
  12613. */
  12614. void addLineSegment (const float startX, const float startY,
  12615. const float endX, const float endY,
  12616. float lineThickness) throw();
  12617. /** Adds a line with an arrowhead on the end.
  12618. The arrow is added as a new closed sub-path. (Any currently open paths will be
  12619. left open).
  12620. */
  12621. void addArrow (const float startX, const float startY,
  12622. const float endX, const float endY,
  12623. float lineThickness,
  12624. float arrowheadWidth,
  12625. float arrowheadLength) throw();
  12626. /** Adds a star shape to the path.
  12627. */
  12628. void addStar (const float centreX,
  12629. const float centreY,
  12630. const int numberOfPoints,
  12631. const float innerRadius,
  12632. const float outerRadius,
  12633. const float startAngle = 0.0f);
  12634. /** Adds a speech-bubble shape to the path.
  12635. @param bodyX the left of the main body area of the bubble
  12636. @param bodyY the top of the main body area of the bubble
  12637. @param bodyW the width of the main body area of the bubble
  12638. @param bodyH the height of the main body area of the bubble
  12639. @param cornerSize the amount by which to round off the corners of the main body rectangle
  12640. @param arrowTipX the x position that the tip of the arrow should connect to
  12641. @param arrowTipY the y position that the tip of the arrow should connect to
  12642. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  12643. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  12644. arrow's base should be - this is a proportional distance between 0 and 1.0
  12645. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  12646. */
  12647. void addBubble (float bodyX, float bodyY,
  12648. float bodyW, float bodyH,
  12649. float cornerSize,
  12650. float arrowTipX,
  12651. float arrowTipY,
  12652. int whichSide,
  12653. float arrowPositionAlongEdgeProportional,
  12654. float arrowWidth);
  12655. /** Adds another path to this one.
  12656. The new path is added as a new sub-path. (Any currently open paths in this
  12657. path will be left open).
  12658. @param pathToAppend the path to add
  12659. */
  12660. void addPath (const Path& pathToAppend) throw();
  12661. /** Adds another path to this one, transforming it on the way in.
  12662. The new path is added as a new sub-path, its points being transformed by the given
  12663. matrix before being added.
  12664. @param pathToAppend the path to add
  12665. @param transformToApply an optional transform to apply to the incoming vertices
  12666. */
  12667. void addPath (const Path& pathToAppend,
  12668. const AffineTransform& transformToApply) throw();
  12669. /** Swaps the contents of this path with another one.
  12670. The internal data of the two paths is swapped over, so this is much faster than
  12671. copying it to a temp variable and back.
  12672. */
  12673. void swapWithPath (Path& other);
  12674. /** Applies a 2D transform to all the vertices in the path.
  12675. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  12676. */
  12677. void applyTransform (const AffineTransform& transform) throw();
  12678. /** Rescales this path to make it fit neatly into a given space.
  12679. This is effectively a quick way of calling
  12680. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  12681. @param x the x position of the rectangle to fit the path inside
  12682. @param y the y position of the rectangle to fit the path inside
  12683. @param width the width of the rectangle to fit the path inside
  12684. @param height the height of the rectangle to fit the path inside
  12685. @param preserveProportions if true, it will fit the path into the space without altering its
  12686. horizontal/vertical scale ratio; if false, it will distort the
  12687. path to fill the specified ratio both horizontally and vertically
  12688. @see applyTransform, getTransformToScaleToFit
  12689. */
  12690. void scaleToFit (const float x, const float y,
  12691. const float width, const float height,
  12692. const bool preserveProportions) throw();
  12693. /** Returns a transform that can be used to rescale the path to fit into a given space.
  12694. @param x the x position of the rectangle to fit the path inside
  12695. @param y the y position of the rectangle to fit the path inside
  12696. @param width the width of the rectangle to fit the path inside
  12697. @param height the height of the rectangle to fit the path inside
  12698. @param preserveProportions if true, it will fit the path into the space without altering its
  12699. horizontal/vertical scale ratio; if false, it will distort the
  12700. path to fill the specified ratio both horizontally and vertically
  12701. @param justificationType if the proportions are preseved, the resultant path may be smaller
  12702. than the available rectangle, so this describes how it should be
  12703. positioned within the space.
  12704. @returns an appropriate transformation
  12705. @see applyTransform, scaleToFit
  12706. */
  12707. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  12708. const float width, const float height,
  12709. const bool preserveProportions,
  12710. const Justification& justificationType = Justification::centred) const throw();
  12711. /** Creates a version of this path where all sharp corners have been replaced by curves.
  12712. Wherever two lines meet at an angle, this will replace the corner with a curve
  12713. of the given radius.
  12714. */
  12715. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  12716. /** Changes the winding-rule to be used when filling the path.
  12717. If set to true (which is the default), then the path uses a non-zero-winding rule
  12718. to determine which points are inside the path. If set to false, it uses an
  12719. alternate-winding rule.
  12720. The winding-rule comes into play when areas of the shape overlap other
  12721. areas, and determines whether the overlapping regions are considered to be
  12722. inside or outside.
  12723. Changing this value just sets a flag - it doesn't affect the contents of the
  12724. path.
  12725. @see isUsingNonZeroWinding
  12726. */
  12727. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  12728. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  12729. The default for a new path is true.
  12730. @see setUsingNonZeroWinding
  12731. */
  12732. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  12733. /** Iterates the lines and curves that a path contains.
  12734. @see Path, PathFlatteningIterator
  12735. */
  12736. class JUCE_API Iterator
  12737. {
  12738. public:
  12739. Iterator (const Path& path);
  12740. ~Iterator();
  12741. /** Moves onto the next element in the path.
  12742. If this returns false, there are no more elements. If it returns true,
  12743. the elementType variable will be set to the type of the current element,
  12744. and some of the x and y variables will be filled in with values.
  12745. */
  12746. bool next();
  12747. enum PathElementType
  12748. {
  12749. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  12750. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  12751. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  12752. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  12753. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  12754. };
  12755. PathElementType elementType;
  12756. float x1, y1, x2, y2, x3, y3;
  12757. private:
  12758. const Path& path;
  12759. int index;
  12760. Iterator (const Iterator&);
  12761. const Iterator& operator= (const Iterator&);
  12762. };
  12763. /** Loads a stored path from a data stream.
  12764. The data in the stream must have been written using writePathToStream().
  12765. Note that this will append the stored path to whatever is currently in
  12766. this path, so you might need to call clear() beforehand.
  12767. @see loadPathFromData, writePathToStream
  12768. */
  12769. void loadPathFromStream (InputStream& source);
  12770. /** Loads a stored path from a block of data.
  12771. This is similar to loadPathFromStream(), but just reads from a block
  12772. of data. Useful if you're including stored shapes in your code as a
  12773. block of static data.
  12774. @see loadPathFromStream, writePathToStream
  12775. */
  12776. void loadPathFromData (const unsigned char* const data,
  12777. const int numberOfBytes) throw();
  12778. /** Stores the path by writing it out to a stream.
  12779. After writing out a path, you can reload it using loadPathFromStream().
  12780. @see loadPathFromStream, loadPathFromData
  12781. */
  12782. void writePathToStream (OutputStream& destination) const;
  12783. /** Creates a string containing a textual representation of this path.
  12784. @see restoreFromString
  12785. */
  12786. const String toString() const;
  12787. /** Restores this path from a string that was created with the toString() method.
  12788. @see toString()
  12789. */
  12790. void restoreFromString (const String& stringVersion);
  12791. juce_UseDebuggingNewOperator
  12792. private:
  12793. friend class PathFlatteningIterator;
  12794. friend class Path::Iterator;
  12795. int numElements;
  12796. float pathXMin, pathXMax, pathYMin, pathYMax;
  12797. bool useNonZeroWinding;
  12798. static const float lineMarker;
  12799. static const float moveMarker;
  12800. static const float quadMarker;
  12801. static const float cubicMarker;
  12802. static const float closeSubPathMarker;
  12803. };
  12804. #endif // __JUCE_PATH_JUCEHEADER__
  12805. /********* End of inlined file: juce_Path.h *********/
  12806. class Font;
  12807. class Typeface;
  12808. /**
  12809. Stores information about the shape and kerning of one of the glyphs in a Typeface.
  12810. @see Typeface, PositionedGlyph, GlyphArrangement
  12811. */
  12812. class JUCE_API TypefaceGlyphInfo
  12813. {
  12814. public:
  12815. /** Returns the path that describes the glyph's outline.
  12816. This is normalised to a height of 1.0, and its origin is the
  12817. left-hand edge of the glyph's baseline.
  12818. */
  12819. const Path& getPath() const throw() { return path; }
  12820. /** Returns the unicode character that this glyph represents. */
  12821. juce_wchar getCharacter() const throw() { return character; }
  12822. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  12823. /** Returns the distance to leave between this and a following character.
  12824. The value returned is expressed as a proportion of the font's height.
  12825. */
  12826. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw();
  12827. /** Returns the typeface that this glyph belongs to. */
  12828. Typeface* getTypeface() const throw() { return typeface; }
  12829. private:
  12830. friend class Typeface;
  12831. struct KerningPair
  12832. {
  12833. juce_wchar character2;
  12834. float kerningAmount;
  12835. };
  12836. const juce_wchar character;
  12837. const Path path;
  12838. float width;
  12839. MemoryBlock kerningPairs;
  12840. Typeface* const typeface;
  12841. TypefaceGlyphInfo (const juce_wchar character,
  12842. const Path& shape,
  12843. const float horizontalSeparation,
  12844. Typeface* const typeface) throw();
  12845. ~TypefaceGlyphInfo() throw();
  12846. KerningPair& getKerningPair (const int index) const throw();
  12847. int getNumKerningPairs() const throw();
  12848. void addKerningPair (const juce_wchar subsequentCharacter,
  12849. const float extraKerningAmount) throw();
  12850. const TypefaceGlyphInfo& operator= (const TypefaceGlyphInfo&);
  12851. };
  12852. /**
  12853. Represents a size-independent system font.
  12854. A Font object represents a particular Typeface along with a specific size,
  12855. style, kerning, scale, etc, wheras the Typeface is just a generalised description
  12856. of the shapes of the glyphs and their properties.
  12857. */
  12858. class JUCE_API Typeface : public ReferenceCountedObject
  12859. {
  12860. public:
  12861. /** Tries to load a named system font and to initialise all the glyphs
  12862. appropriately from it.
  12863. @param faceName the name of the typeface, e.g. "Times"
  12864. @param bold whether to try to find a bold version of the font (may not always be available)
  12865. @param italic whether to try to find an italicised version of the font (may not always be available)
  12866. */
  12867. Typeface (const String& faceName,
  12868. const bool bold,
  12869. const bool italic);
  12870. /** Creates a copy of another typeface */
  12871. Typeface (const Typeface& other);
  12872. /** Destructor. */
  12873. ~Typeface();
  12874. /** Copies another typeface over this one. */
  12875. const Typeface& operator= (const Typeface& other) throw();
  12876. /** Returns a unique ID for the typeface.
  12877. This is based on the name and style, so can be used to compare two Typeface objects.
  12878. */
  12879. int hashCode() const throw() { return hash; }
  12880. /** Returns the name of the typeface, e.g. "Times", "Verdana", etc */
  12881. const String& getName() const throw() { return typefaceName; }
  12882. /** Returns the font's ascent as a proportion of its height. */
  12883. float getAscent() const throw() { return ascent; }
  12884. /** Returns true if the font is flagged as being bold. */
  12885. bool isBold() const throw() { return bold; }
  12886. /** Returns true if the typeface's 'italic' flag is set. */
  12887. bool isItalic() const throw() { return italic; }
  12888. /** Finds the Path that describes the outline shape of a character.
  12889. The height of the path is normalised to 1.0 (i.e. a distance of 1.0 is the
  12890. height of the font).
  12891. This may return 0 if the typeface has no characters, but if the character
  12892. that is asked for is not found, it will first try to return a default
  12893. character instead.
  12894. */
  12895. const Path* getOutlineForGlyph (const juce_wchar character) throw();
  12896. /** Tries to find the information describing a glyph for this character.
  12897. If there isn't a glyph specifically for the character it will return
  12898. a default glyph instead; if the typeface is empty, it may return a null
  12899. pointer.
  12900. */
  12901. const TypefaceGlyphInfo* getGlyph (const juce_wchar character) throw();
  12902. /** Deletes all the glyphs and kerning data fom the typeface. */
  12903. void clear() throw();
  12904. /** Adds a glyph to the typeface.
  12905. This is typically only called by the platform-specific code that generates
  12906. the typeface from a system font.
  12907. */
  12908. void addGlyph (const juce_wchar character,
  12909. const Path& path,
  12910. const float horizontalSpacing) throw();
  12911. /** Adds a kerning distance to the typeface.
  12912. The extra amount passed in is expressed as a proportion of the font's
  12913. height, normalised to 1.0.
  12914. This is typically only called by the platform-specific code that generates
  12915. the typeface from a system font.
  12916. */
  12917. void addKerningPair (const juce_wchar firstChar,
  12918. const juce_wchar secondChar,
  12919. const float extraAmount) throw();
  12920. /** Sets the typeface's name.
  12921. This is typically only called by the platform-specific code that generates
  12922. the typeface from a system font. Calling this method won't actually affect
  12923. the underlying font being used.
  12924. */
  12925. void setName (const String& name) throw();
  12926. /** Sets the font's ascent value, as a proportion of the font height.
  12927. This is typically only called by the platform-specific code that generates
  12928. the typeface from a system font.
  12929. */
  12930. void setAscent (const float newAscent) throw();
  12931. /** Sets the typeface's 'bold' flag.
  12932. This is typically only called by the platform-specific code that generates
  12933. the typeface from a system font.
  12934. */
  12935. void setBold (const bool shouldBeBold) throw();
  12936. /** Sets the typeface's 'italic' flag.
  12937. This is typically only called by the platform-specific code that generates
  12938. the typeface from a system font.
  12939. */
  12940. void setItalic (const bool shouldBeItalic) throw();
  12941. /** Changes the character index to use as the default character.
  12942. This is the character that gets returned for characters which don't have a
  12943. glyph set for them.
  12944. */
  12945. void setDefaultCharacter (const juce_wchar newDefaultCharacter) throw();
  12946. /** Creates a typeface from data created using Typeface::serialise().
  12947. This will attempt to load a compressed typeface that was created using
  12948. the Typeface::serialise() method. This is handy if you want to store
  12949. a typeface in your application as a binary blob, and use it without
  12950. having to actually install it on the computer.
  12951. @see Typeface::serialise()
  12952. */
  12953. Typeface (InputStream& serialisedTypefaceStream);
  12954. /** Writes the typeface to a stream (using a proprietary format).
  12955. This lets you save a typeface and reload it using the
  12956. Typeface::Typeface (InputStream&) constructor. The data's saved in
  12957. a compressed format.
  12958. @see Typeface::Typeface (InputStream&)
  12959. */
  12960. void serialise (OutputStream& outputStream);
  12961. /** A name that represents the default sans-serif typeface name.
  12962. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  12963. is a generic string that represents whatever that font is, such as "DefaultSans".
  12964. If you try to create a typeface with this name, the global default LookAndFeel
  12965. object will be asked to provide an appropriate typeface.
  12966. */
  12967. static const tchar* defaultTypefaceNameSans;
  12968. /** A name that represents the default serif typeface name.
  12969. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  12970. is a generic string that represents it, such as "DefaultSans".
  12971. If you try to create a typeface with this name, the global default LookAndFeel
  12972. object will be asked to provide an appropriate typeface.
  12973. */
  12974. static const tchar* defaultTypefaceNameSerif;
  12975. /** A name that represents the default monospaced typeface name.
  12976. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  12977. is a generic string that represents it, such as "DefaultSans".
  12978. If you try to create a typeface with this name, the global default LookAndFeel
  12979. object will be asked to provide an appropriate typeface.
  12980. */
  12981. static const tchar* defaultTypefaceNameMono;
  12982. /** A handy typedef to make it easy to use ref counted pointers to this class. */
  12983. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  12984. juce_UseDebuggingNewOperator
  12985. private:
  12986. VoidArray glyphs;
  12987. short lookupTable [128];
  12988. String typefaceName;
  12989. int hash;
  12990. float ascent; // as a proportion of the height
  12991. bool bold, italic, isFullyPopulated;
  12992. juce_wchar defaultCharacter; // the char to use if a matching glyph can't be found.
  12993. Typeface() throw();
  12994. void addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw();
  12995. friend class Font;
  12996. friend class TypefaceCache;
  12997. friend class FontGlyphAlphaMap;
  12998. static const Ptr getTypefaceFor (const Font& font) throw();
  12999. // this is a platform-dependent method that will look for the given typeface
  13000. // and set up its kerning tables, etc. accordingly.
  13001. // If addAllGlyphsToFont is true, it should also add all the glyphs in the font
  13002. // to the typeface immediately, rather than having to add them later on-demand.
  13003. void initialiseTypefaceCharacteristics (const String& fontName,
  13004. bool bold, bool italic,
  13005. bool addAllGlyphsToFont) throw();
  13006. // platform-specific routine to look up and add a glyph to this typeface
  13007. bool findAndAddSystemGlyph (juce_wchar character) throw();
  13008. void updateHashCode() throw();
  13009. friend class LookAndFeel;
  13010. static void getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13011. };
  13012. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  13013. /********* End of inlined file: juce_Typeface.h *********/
  13014. /**
  13015. Represents a particular font, including its size, style, etc.
  13016. Apart from the typeface to be used, a Font object also dictates whether
  13017. the font is bold, italic, underlined, how big it is, and its kerning and
  13018. horizontal scale factor.
  13019. @see Typeface
  13020. */
  13021. class JUCE_API Font
  13022. {
  13023. public:
  13024. /** A combination of these values is used by the constructor to specify the
  13025. style of font to use.
  13026. */
  13027. enum FontStyleFlags
  13028. {
  13029. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  13030. bold = 1, /**< boldens the font. @see setStyleFlags */
  13031. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  13032. underlined = 4 /**< underlines the font. @see setStyleFlags */
  13033. };
  13034. /** Creates a sans-serif font in a given size.
  13035. @param fontHeight the height in pixels (can be fractional)
  13036. @param styleFlags the style to use - this can be a combination of the
  13037. Font::bold, Font::italic and Font::underlined, or
  13038. just Font::plain for the normal style.
  13039. @see FontStyleFlags, getDefaultSansSerifFontName
  13040. */
  13041. Font (const float fontHeight,
  13042. const int styleFlags = plain) throw();
  13043. /** Creates a font with a given typeface and parameters.
  13044. @param typefaceName the name of the typeface to use
  13045. @param fontHeight the height in pixels (can be fractional)
  13046. @param styleFlags the style to use - this can be a combination of the
  13047. Font::bold, Font::italic and Font::underlined, or
  13048. just Font::plain for the normal style.
  13049. @see FontStyleFlags, getDefaultSansSerifFontName
  13050. */
  13051. Font (const String& typefaceName,
  13052. const float fontHeight,
  13053. const int styleFlags) throw();
  13054. /** Creates a copy of another Font object. */
  13055. Font (const Font& other) throw();
  13056. /** Creates a font based on a typeface.
  13057. The font object stores its own internal copy of the typeface, so you can safely
  13058. delete the one passed in after calling this.
  13059. */
  13060. Font (const Typeface& typeface) throw();
  13061. /** Creates a basic sans-serif font at a default height.
  13062. You should use one of the other constructors for creating a font that you're planning
  13063. on drawing with - this constructor is here to help initialise objects before changing
  13064. the font's settings later.
  13065. */
  13066. Font() throw();
  13067. /** Copies this font from another one. */
  13068. const Font& operator= (const Font& other) throw();
  13069. bool operator== (const Font& other) const throw();
  13070. bool operator!= (const Font& other) const throw();
  13071. /** Destructor. */
  13072. ~Font() throw();
  13073. /** Changes the name of the typeface family.
  13074. e.g. "Arial", "Courier", etc.
  13075. This may also be set to Typeface::defaultTypefaceNameSans, Typeface::defaultTypefaceNameSerif,
  13076. or Typeface::defaultTypefaceNameMono, which are not actual platform-specific font names, but
  13077. are generic names that are used to represent the various default fonts.
  13078. If a suitable font isn't found on the machine, it'll just use a default instead.
  13079. */
  13080. void setTypefaceName (const String& faceName) throw();
  13081. /** Returns the name of the typeface family that this font uses.
  13082. e.g. "Arial", "Courier", etc.
  13083. Note that this may also be one of the values: Typeface::defaultTypefaceNameSans,
  13084. Typeface::defaultTypefaceNameSerif, or Typeface::defaultTypefaceNameMono, which are not actual
  13085. platform-specific font names, but are generic names that are used to represent the various
  13086. default fonts. If you need to know the exact typeface name being used, you can call
  13087. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  13088. */
  13089. const String& getTypefaceName() const throw() { return typefaceName; }
  13090. /** Returns a typeface name that represents the default sans-serif font.
  13091. This is also the typeface that will be used when a font is created without
  13092. specifying any typeface details.
  13093. Note that this method just returns the same value as Typeface::defaultTypefaceNameSans,
  13094. which is a generic placeholder string, and not a platform-specific font name.
  13095. @see Typeface::defaultTypefaceNameSans, setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName,
  13096. */
  13097. static const String getDefaultSansSerifFontName() throw() { return Typeface::defaultTypefaceNameSans; }
  13098. /** Returns a typeface name that represents the default sans-serif font.
  13099. Note that this method just returns the same value as Typeface::defaultTypefaceNameSerif,
  13100. which is a generic placeholder string, and not a platform-specific font name.
  13101. @see Typeface::defaultTypefaceNameSerif, setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  13102. */
  13103. static const String getDefaultSerifFontName() throw() { return Typeface::defaultTypefaceNameSerif; }
  13104. /** Returns a typeface name that represents the default sans-serif font.
  13105. Note that this method just returns the same value as Typeface::defaultTypefaceNameMono,
  13106. which is a generic placeholder string, and not a platform-specific font name.
  13107. @see Typeface::defaultTypefaceNameMono, setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  13108. */
  13109. static const String getDefaultMonospacedFontName() throw() { return Typeface::defaultTypefaceNameMono; }
  13110. /** Returns the total height of this font.
  13111. This is the maximum height, from the top of the ascent to the bottom of the
  13112. descenders.
  13113. @see setHeight, setHeightWithoutChangingWidth, getAscent
  13114. */
  13115. float getHeight() const throw() { return height; }
  13116. /** Changes the font's height.
  13117. @see getHeight, setHeightWithoutChangingWidth
  13118. */
  13119. void setHeight (float newHeight) throw();
  13120. /** Changes the font's height without changing its width.
  13121. This alters the horizontal scale to compensate for the change in height.
  13122. */
  13123. void setHeightWithoutChangingWidth (float newHeight) throw();
  13124. /** Returns the height of the font above its baseline.
  13125. This is the maximum height from the baseline to the top.
  13126. @see getHeight, getDescent
  13127. */
  13128. float getAscent() const throw();
  13129. /** Returns the amount that the font descends below its baseline.
  13130. This is calculated as (getHeight() - getAscent()).
  13131. @see getAscent, getHeight
  13132. */
  13133. float getDescent() const throw();
  13134. /** Returns the font's style flags.
  13135. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13136. enum, to describe whether the font is bold, italic, etc.
  13137. @see FontStyleFlags
  13138. */
  13139. int getStyleFlags() const throw() { return styleFlags; }
  13140. /** Changes the font's style.
  13141. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13142. enum, to set the font's properties
  13143. @see FontStyleFlags
  13144. */
  13145. void setStyleFlags (const int newFlags) throw();
  13146. /** Makes the font bold or non-bold. */
  13147. void setBold (const bool shouldBeBold) throw();
  13148. /** Returns true if the font is bold. */
  13149. bool isBold() const throw();
  13150. /** Makes the font italic or non-italic. */
  13151. void setItalic (const bool shouldBeItalic) throw();
  13152. /** Returns true if the font is italic. */
  13153. bool isItalic() const throw();
  13154. /** Makes the font underlined or non-underlined. */
  13155. void setUnderline (const bool shouldBeUnderlined) throw();
  13156. /** Returns true if the font is underlined. */
  13157. bool isUnderlined() const throw();
  13158. /** Changes the font's horizontal scale factor.
  13159. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13160. narrower, greater than 1.0 will be stretched out.
  13161. */
  13162. void setHorizontalScale (const float scaleFactor) throw();
  13163. /** Returns the font's horizontal scale.
  13164. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13165. than 1.0 will be stretched out.
  13166. @see setHorizontalScale
  13167. */
  13168. float getHorizontalScale() const throw() { return horizontalScale; }
  13169. /** Changes the font's kerning.
  13170. @param extraKerning a multiple of the font's height that will be added
  13171. to space between the characters. So a value of zero is
  13172. normal spacing, positive values spread the letters out,
  13173. negative values make them closer together.
  13174. */
  13175. void setExtraKerningFactor (const float extraKerning) throw();
  13176. /** Returns the font's kerning.
  13177. This is the extra space added between adjacent characters, as a proportion
  13178. of the font's height.
  13179. A value of zero is normal spacing, positive values will spread the letters
  13180. out more, and negative values make them closer together.
  13181. */
  13182. float getExtraKerningFactor() const throw() { return kerning; }
  13183. /** Changes all the font's characteristics with one call. */
  13184. void setSizeAndStyle (const float newHeight,
  13185. const int newStyleFlags,
  13186. const float newHorizontalScale,
  13187. const float newKerningAmount) throw();
  13188. /** Resets this font's characteristics.
  13189. This is basically like saying "myFont = Font();", because it resets the
  13190. typeface, size, style, etc to a default state. Not very useful to most
  13191. people, its raison d'etre is to help the Graphics class be more efficient.
  13192. */
  13193. void resetToDefaultState() throw();
  13194. /** Returns the total width of a string as it would be drawn using this font.
  13195. For a more accurate floating-point result, use getStringWidthFloat().
  13196. */
  13197. int getStringWidth (const String& text) const throw();
  13198. /** Returns the total width of a string as it would be drawn using this font.
  13199. @see getStringWidth
  13200. */
  13201. float getStringWidthFloat (const String& text) const throw();
  13202. /** Returns the typeface used by this font.
  13203. Note that the object returned may go out of scope if this font is deleted
  13204. or has its style changed.
  13205. */
  13206. Typeface* getTypeface() const throw();
  13207. /** Creates an array of Font objects to represent all the fonts on the system.
  13208. If you just need the names of the typefaces, you can also use
  13209. findAllTypefaceNames() instead.
  13210. @param results the array to which new Font objects will be added.
  13211. */
  13212. static void findFonts (OwnedArray<Font>& results) throw();
  13213. /** Returns a list of all the available typeface names.
  13214. The names returned can be passed into setTypefaceName().
  13215. You can use this instead of findFonts() if you only need their names, and not
  13216. font objects.
  13217. */
  13218. static const StringArray findAllTypefaceNames() throw();
  13219. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13220. in the requested typeface.
  13221. */
  13222. static const String getFallbackFontName() throw();
  13223. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13224. available in whatever font you're trying to use.
  13225. */
  13226. static void setFallbackFontName (const String& name) throw();
  13227. juce_UseDebuggingNewOperator
  13228. private:
  13229. friend class FontGlyphAlphaMap;
  13230. friend class TypefaceCache;
  13231. String typefaceName;
  13232. float height, horizontalScale, kerning;
  13233. mutable float ascent;
  13234. int styleFlags;
  13235. mutable Typeface::Ptr typeface;
  13236. };
  13237. #endif // __JUCE_FONT_JUCEHEADER__
  13238. /********* End of inlined file: juce_Font.h *********/
  13239. /********* Start of inlined file: juce_Rectangle.h *********/
  13240. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13241. #define __JUCE_RECTANGLE_JUCEHEADER__
  13242. /**
  13243. A rectangle, specified using integer co-ordinates.
  13244. @see RectangleList, Path, Line, Point
  13245. */
  13246. class JUCE_API Rectangle
  13247. {
  13248. public:
  13249. /** Creates a rectangle of zero size.
  13250. The default co-ordinates will be (0, 0, 0, 0).
  13251. */
  13252. Rectangle() throw();
  13253. /** Creates a copy of another rectangle. */
  13254. Rectangle (const Rectangle& other) throw();
  13255. /** Creates a rectangle with a given position and size. */
  13256. Rectangle (const int x, const int y,
  13257. const int width, const int height) throw();
  13258. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13259. Rectangle (const int width, const int height) throw();
  13260. /** Destructor. */
  13261. ~Rectangle() throw();
  13262. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13263. inline int getX() const throw() { return x; }
  13264. /** Returns the y co-ordinate of the rectangle's top edge. */
  13265. inline int getY() const throw() { return y; }
  13266. /** Returns the width of the rectangle. */
  13267. inline int getWidth() const throw() { return w; }
  13268. /** Returns the height of the rectangle. */
  13269. inline int getHeight() const throw() { return h; }
  13270. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13271. inline int getRight() const throw() { return x + w; }
  13272. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13273. inline int getBottom() const throw() { return y + h; }
  13274. /** Returns the x co-ordinate of the rectangle's centre. */
  13275. inline int getCentreX() const throw() { return x + (w >> 1); }
  13276. /** Returns the y co-ordinate of the rectangle's centre. */
  13277. inline int getCentreY() const throw() { return y + (h >> 1); }
  13278. /** Returns true if the rectangle's width and height are both zero or less */
  13279. bool isEmpty() const throw();
  13280. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13281. void setPosition (const int x, const int y) throw();
  13282. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13283. void setSize (const int w, const int h) throw();
  13284. /** Changes all the rectangle's co-ordinates. */
  13285. void setBounds (const int newX, const int newY,
  13286. const int newWidth, const int newHeight) throw();
  13287. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13288. void translate (const int deltaX,
  13289. const int deltaY) throw();
  13290. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13291. const Rectangle translated (const int deltaX,
  13292. const int deltaY) const throw();
  13293. /** Expands the rectangle by a given amount.
  13294. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13295. @see expanded, reduce, reduced
  13296. */
  13297. void expand (const int deltaX,
  13298. const int deltaY) throw();
  13299. /** Returns a rectangle that is larger than this one by a given amount.
  13300. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13301. @see expand, reduce, reduced
  13302. */
  13303. const Rectangle expanded (const int deltaX,
  13304. const int deltaY) const throw();
  13305. /** Shrinks the rectangle by a given amount.
  13306. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13307. @see reduced, expand, expanded
  13308. */
  13309. void reduce (const int deltaX,
  13310. const int deltaY) throw();
  13311. /** Returns a rectangle that is smaller than this one by a given amount.
  13312. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13313. @see reduce, expand, expanded
  13314. */
  13315. const Rectangle reduced (const int deltaX,
  13316. const int deltaY) const throw();
  13317. /** Returns true if the two rectangles are identical. */
  13318. bool operator== (const Rectangle& other) const throw();
  13319. /** Returns true if the two rectangles are not identical. */
  13320. bool operator!= (const Rectangle& other) const throw();
  13321. /** Returns true if this co-ordinate is inside the rectangle. */
  13322. bool contains (const int x, const int y) const throw();
  13323. /** Returns true if this other rectangle is completely inside this one. */
  13324. bool contains (const Rectangle& other) const throw();
  13325. /** Returns true if any part of another rectangle overlaps this one. */
  13326. bool intersects (const Rectangle& other) const throw();
  13327. /** Returns the region that is the overlap between this and another rectangle.
  13328. If the two rectangles don't overlap, the rectangle returned will be empty.
  13329. */
  13330. const Rectangle getIntersection (const Rectangle& other) const throw();
  13331. /** Clips a rectangle so that it lies only within this one.
  13332. This is a non-static version of intersectRectangles().
  13333. Returns false if the two regions didn't overlap.
  13334. */
  13335. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13336. /** Returns the smallest rectangle that contains both this one and the one
  13337. passed-in.
  13338. */
  13339. const Rectangle getUnion (const Rectangle& other) const throw();
  13340. /** If this rectangle merged with another one results in a simple rectangle, this
  13341. will set this rectangle to the result, and return true.
  13342. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13343. or if they form a complex region.
  13344. */
  13345. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13346. /** If after removing another rectangle from this one the result is a simple rectangle,
  13347. this will set this object's bounds to be the result, and return true.
  13348. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13349. or if removing the other one would form a complex region.
  13350. */
  13351. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13352. /** Static utility to intersect two sets of rectangular co-ordinates.
  13353. Returns false if the two regions didn't overlap.
  13354. @see intersectRectangle
  13355. */
  13356. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13357. int x2, int y2, int w2, int h2) throw();
  13358. /** Creates a string describing this rectangle.
  13359. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13360. Coupled with the fromString() method, this is very handy for things like
  13361. storing rectangles (particularly component positions) in XML attributes.
  13362. @see fromString
  13363. */
  13364. const String toString() const throw();
  13365. /** Parses a string containing a rectangle's details.
  13366. The string should contain 4 integer tokens, in the form "x y width height". They
  13367. can be comma or whitespace separated.
  13368. This method is intended to go with the toString() method, to form an easy way
  13369. of saving/loading rectangles as strings.
  13370. @see toString
  13371. */
  13372. static const Rectangle fromString (const String& stringVersion);
  13373. juce_UseDebuggingNewOperator
  13374. private:
  13375. friend class RectangleList;
  13376. int x, y, w, h;
  13377. };
  13378. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13379. /********* End of inlined file: juce_Rectangle.h *********/
  13380. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13381. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13382. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13383. /**
  13384. Describes a type of stroke used to render a solid outline along a path.
  13385. A PathStrokeType object can be used directly to create the shape of an outline
  13386. around a path, and is used by Graphics::strokePath to specify the type of
  13387. stroke to draw.
  13388. @see Path, Graphics::strokePath
  13389. */
  13390. class JUCE_API PathStrokeType
  13391. {
  13392. public:
  13393. /** The type of shape to use for the corners between two adjacent line segments. */
  13394. enum JointStyle
  13395. {
  13396. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13397. Note that for angles that curve back on themselves, drawing a
  13398. mitre could require extending the point too far away from the
  13399. path, so a mitre limit is imposed and any corners that exceed it
  13400. are drawn as bevelled instead. */
  13401. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13402. beveled /**< Indicates that corners should be drawn with a line flattening their
  13403. outside edge. */
  13404. };
  13405. /** The type shape to use for the ends of lines. */
  13406. enum EndCapStyle
  13407. {
  13408. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13409. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13410. the thickness of the stroke. */
  13411. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13412. };
  13413. /** Creates a stroke type.
  13414. @param strokeThickness the width of the line to use
  13415. @param jointStyle the type of joints to use for corners
  13416. @param endStyle the type of end-caps to use for the ends of open paths.
  13417. */
  13418. PathStrokeType (const float strokeThickness,
  13419. const JointStyle jointStyle = mitered,
  13420. const EndCapStyle endStyle = butt) throw();
  13421. /** Createes a copy of another stroke type. */
  13422. PathStrokeType (const PathStrokeType& other) throw();
  13423. /** Copies another stroke onto this one. */
  13424. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13425. /** Destructor. */
  13426. ~PathStrokeType() throw();
  13427. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13428. @param destPath the resultant stroked outline shape will be copied into this path.
  13429. Note that it's ok for the source and destination Paths to be
  13430. the same object, so you can easily turn a path into a stroked version
  13431. of itself.
  13432. @param sourcePath the path to use as the source
  13433. @param transform an optional transform to apply to the points from the source path
  13434. as they are being used
  13435. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13436. a higher resolution, which improved the quality if you'll later want
  13437. to enlarge the stroked path
  13438. @see createDashedStroke
  13439. */
  13440. void createStrokedPath (Path& destPath,
  13441. const Path& sourcePath,
  13442. const AffineTransform& transform = AffineTransform::identity,
  13443. const float extraAccuracy = 1.0f) const throw();
  13444. /** Applies this stroke type to a path, creating a dashed line.
  13445. This is similar to createStrokedPath, but uses the array passed in to
  13446. break the stroke up into a series of dashes.
  13447. @param destPath the resultant stroked outline shape will be copied into this path.
  13448. Note that it's ok for the source and destination Paths to be
  13449. the same object, so you can easily turn a path into a stroked version
  13450. of itself.
  13451. @param sourcePath the path to use as the source
  13452. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13453. a line of length 2, then skip a length of 3, then add a line of length 4,
  13454. skip 5, and keep repeating this pattern.
  13455. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13456. an even number, otherwise the pattern will get out of step as it
  13457. repeats.
  13458. @param transform an optional transform to apply to the points from the source path
  13459. as they are being used
  13460. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13461. a higher resolution, which improved the quality if you'll later want
  13462. to enlarge the stroked path
  13463. */
  13464. void createDashedStroke (Path& destPath,
  13465. const Path& sourcePath,
  13466. const float* dashLengths,
  13467. int numDashLengths,
  13468. const AffineTransform& transform = AffineTransform::identity,
  13469. const float extraAccuracy = 1.0f) const throw();
  13470. /** Returns the stroke thickness. */
  13471. float getStrokeThickness() const throw() { return thickness; }
  13472. /** Returns the joint style. */
  13473. JointStyle getJointStyle() const throw() { return jointStyle; }
  13474. /** Returns the end-cap style. */
  13475. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13476. juce_UseDebuggingNewOperator
  13477. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13478. bool operator== (const PathStrokeType& other) const throw();
  13479. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13480. bool operator!= (const PathStrokeType& other) const throw();
  13481. private:
  13482. float thickness;
  13483. JointStyle jointStyle;
  13484. EndCapStyle endStyle;
  13485. };
  13486. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13487. /********* End of inlined file: juce_PathStrokeType.h *********/
  13488. /********* Start of inlined file: juce_Line.h *********/
  13489. #ifndef __JUCE_LINE_JUCEHEADER__
  13490. #define __JUCE_LINE_JUCEHEADER__
  13491. /**
  13492. Represents a line, using 32-bit float co-ordinates.
  13493. This class contains a bunch of useful methods for various geometric
  13494. tasks.
  13495. @see Point, Rectangle, Path, Graphics::drawLine
  13496. */
  13497. class JUCE_API Line
  13498. {
  13499. public:
  13500. /** Creates a line, using (0, 0) as its start and end points. */
  13501. Line() throw();
  13502. /** Creates a copy of another line. */
  13503. Line (const Line& other) throw();
  13504. /** Creates a line based on the co-ordinates of its start and end points. */
  13505. Line (const float startX,
  13506. const float startY,
  13507. const float endX,
  13508. const float endY) throw();
  13509. /** Creates a line from its start and end points. */
  13510. Line (const Point& start,
  13511. const Point& end) throw();
  13512. /** Copies a line from another one. */
  13513. const Line& operator= (const Line& other) throw();
  13514. /** Destructor. */
  13515. ~Line() throw();
  13516. /** Returns the x co-ordinate of the line's start point. */
  13517. inline float getStartX() const throw() { return startX; }
  13518. /** Returns the y co-ordinate of the line's start point. */
  13519. inline float getStartY() const throw() { return startY; }
  13520. /** Returns the x co-ordinate of the line's end point. */
  13521. inline float getEndX() const throw() { return endX; }
  13522. /** Returns the y co-ordinate of the line's end point. */
  13523. inline float getEndY() const throw() { return endY; }
  13524. /** Returns the line's start point. */
  13525. const Point getStart() const throw();
  13526. /** Returns the line's end point. */
  13527. const Point getEnd() const throw();
  13528. /** Changes this line's start point */
  13529. void setStart (const float newStartX,
  13530. const float newStartY) throw();
  13531. /** Changes this line's end point */
  13532. void setEnd (const float newEndX,
  13533. const float newEndY) throw();
  13534. /** Changes this line's start point */
  13535. void setStart (const Point& newStart) throw();
  13536. /** Changes this line's end point */
  13537. void setEnd (const Point& newEnd) throw();
  13538. /** Applies an affine transform to the line's start and end points. */
  13539. void applyTransform (const AffineTransform& transform) throw();
  13540. /** Returns the length of the line. */
  13541. float getLength() const throw();
  13542. /** Returns true if the line's start and end x co-ordinates are the same. */
  13543. bool isVertical() const throw();
  13544. /** Returns true if the line's start and end y co-ordinates are the same. */
  13545. bool isHorizontal() const throw();
  13546. /** Returns the line's angle.
  13547. This value is the number of radians clockwise from the 3 o'clock direction,
  13548. where the line's start point is considered to be at the centre.
  13549. */
  13550. float getAngle() const throw();
  13551. /** Compares two lines. */
  13552. bool operator== (const Line& other) const throw();
  13553. /** Compares two lines. */
  13554. bool operator!= (const Line& other) const throw();
  13555. /** Finds the intersection between two lines.
  13556. @param line the other line
  13557. @param intersectionX the x co-ordinate of the point where the lines meet (or
  13558. where they would meet if they were infinitely long)
  13559. the intersection (if the lines intersect). If the lines
  13560. are parallel, this will just be set to the position
  13561. of one of the line's endpoints.
  13562. @param intersectionY the y co-ordinate of the point where the lines meet
  13563. @returns true if the line segments intersect; false if they dont. Even if they
  13564. don't intersect, the intersection co-ordinates returned will still
  13565. be valid
  13566. */
  13567. bool intersects (const Line& line,
  13568. float& intersectionX,
  13569. float& intersectionY) const throw();
  13570. /** Returns the location of the point which is a given distance along this line.
  13571. @param distanceFromStart the distance to move along the line from its
  13572. start point. This value can be negative or longer
  13573. than the line itself
  13574. @see getPointAlongLineProportionally
  13575. */
  13576. const Point getPointAlongLine (const float distanceFromStart) const throw();
  13577. /** Returns a point which is a certain distance along and to the side of this line.
  13578. This effectively moves a given distance along the line, then another distance
  13579. perpendicularly to this, and returns the resulting position.
  13580. @param distanceFromStart the distance to move along the line from its
  13581. start point. This value can be negative or longer
  13582. than the line itself
  13583. @param perpendicularDistance how far to move sideways from the line. If you're
  13584. looking along the line from its start towards its
  13585. end, then a positive value here will move to the
  13586. right, negative value move to the left.
  13587. */
  13588. const Point getPointAlongLine (const float distanceFromStart,
  13589. const float perpendicularDistance) const throw();
  13590. /** Returns the location of the point which is a given distance along this line
  13591. proportional to the line's length.
  13592. @param proportionOfLength the distance to move along the line from its
  13593. start point, in multiples of the line's length.
  13594. So a value of 0.0 will return the line's start point
  13595. and a value of 1.0 will return its end point. (This value
  13596. can be negative or greater than 1.0).
  13597. @see getPointAlongLine
  13598. */
  13599. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  13600. /** Returns the smallest distance between this line segment and a given point.
  13601. So if the point is close to the line, this will return the perpendicular
  13602. distance from the line; if the point is a long way beyond one of the line's
  13603. end-point's, it'll return the straight-line distance to the nearest end-point.
  13604. @param x x position of the point to test
  13605. @param y y position of the point to test
  13606. @returns the point's distance from the line
  13607. @see getPositionAlongLineOfNearestPoint
  13608. */
  13609. float getDistanceFromLine (const float x,
  13610. const float y) const throw();
  13611. /** Finds the point on this line which is nearest to a given point, and
  13612. returns its position as a proportional position along the line.
  13613. @param x x position of the point to test
  13614. @param y y position of the point to test
  13615. @returns a value 0 to 1.0 which is the distance along this line from the
  13616. line's start to the point which is nearest to the point passed-in. To
  13617. turn this number into a position, use getPointAlongLineProportionally().
  13618. @see getDistanceFromLine, getPointAlongLineProportionally
  13619. */
  13620. float findNearestPointTo (const float x,
  13621. const float y) const throw();
  13622. /** Returns true if the given point lies above this line.
  13623. The return value is true if the point's y coordinate is less than the y
  13624. coordinate of this line at the given x (assuming the line extends infinitely
  13625. in both directions).
  13626. */
  13627. bool isPointAbove (const float x, const float y) const throw();
  13628. /** Returns a shortened copy of this line.
  13629. This will chop off part of the start of this line by a certain amount, (leaving the
  13630. end-point the same), and return the new line.
  13631. */
  13632. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  13633. /** Returns a shortened copy of this line.
  13634. This will chop off part of the end of this line by a certain amount, (leaving the
  13635. start-point the same), and return the new line.
  13636. */
  13637. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  13638. /** Cuts off parts of this line to keep the parts that are either inside or
  13639. outside a path.
  13640. Note that this isn't smart enough to cope with situations where the
  13641. line would need to be cut into multiple pieces to correctly clip against
  13642. a re-entrant shape.
  13643. @param path the path to clip against
  13644. @param keepSectionOutsidePath if true, it's the section outside the path
  13645. that will be kept; if false its the section inside
  13646. the path
  13647. @returns true if the line was changed.
  13648. */
  13649. bool clipToPath (const Path& path,
  13650. const bool keepSectionOutsidePath) throw();
  13651. juce_UseDebuggingNewOperator
  13652. private:
  13653. float startX, startY, endX, endY;
  13654. };
  13655. #endif // __JUCE_LINE_JUCEHEADER__
  13656. /********* End of inlined file: juce_Line.h *********/
  13657. /********* Start of inlined file: juce_Colours.h *********/
  13658. #ifndef __JUCE_COLOURS_JUCEHEADER__
  13659. #define __JUCE_COLOURS_JUCEHEADER__
  13660. /********* Start of inlined file: juce_Colour.h *********/
  13661. #ifndef __JUCE_COLOUR_JUCEHEADER__
  13662. #define __JUCE_COLOUR_JUCEHEADER__
  13663. /********* Start of inlined file: juce_PixelFormats.h *********/
  13664. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  13665. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  13666. #if JUCE_MSVC
  13667. #pragma pack (push, 1)
  13668. #define PACKED
  13669. #elif JUCE_GCC
  13670. #define PACKED __attribute__((packed))
  13671. #else
  13672. #define PACKED
  13673. #endif
  13674. /**
  13675. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  13676. operations with it.
  13677. This is used internally by the imaging classes.
  13678. @see PixelRGB
  13679. */
  13680. class JUCE_API PixelARGB
  13681. {
  13682. public:
  13683. /** Creates a pixel without defining its colour. */
  13684. PixelARGB() throw() {}
  13685. ~PixelARGB() throw() {}
  13686. /** Creates a pixel from a 32-bit argb value.
  13687. */
  13688. PixelARGB (const uint32 argb_) throw()
  13689. : argb (argb_)
  13690. {
  13691. }
  13692. forcedinline uint32 getARGB() const throw() { return argb; }
  13693. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  13694. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  13695. forcedinline uint8 getAlpha() const throw() { return components.a; }
  13696. forcedinline uint8 getRed() const throw() { return components.r; }
  13697. forcedinline uint8 getGreen() const throw() { return components.g; }
  13698. forcedinline uint8 getBlue() const throw() { return components.b; }
  13699. /** Blends another pixel onto this one.
  13700. This takes into account the opacity of the pixel being overlaid, and blends
  13701. it accordingly.
  13702. */
  13703. template <class Pixel>
  13704. forcedinline void blend (const Pixel& src) throw()
  13705. {
  13706. uint32 sargb = src.getARGB();
  13707. const uint32 alpha = 0x100 - (sargb >> 24);
  13708. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13709. sargb += 0xff00ff00 & (getAG() * alpha);
  13710. argb = sargb;
  13711. }
  13712. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13713. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13714. being used, so this can blend semi-transparently from a PixelRGB argument.
  13715. */
  13716. template <class Pixel>
  13717. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13718. {
  13719. ++extraAlpha;
  13720. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  13721. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  13722. const uint32 alpha = 0x100 - (sargb >> 24);
  13723. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13724. sargb += 0xff00ff00 & (getAG() * alpha);
  13725. argb = sargb;
  13726. }
  13727. /** Blends another pixel with this one, creating a colour that is somewhere
  13728. between the two, as specified by the amount.
  13729. */
  13730. template <class Pixel>
  13731. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13732. {
  13733. uint32 drb = getRB();
  13734. drb += (((src.getRB() - drb) * amount) >> 8);
  13735. drb &= 0x00ff00ff;
  13736. uint32 dag = getAG();
  13737. dag += (((src.getAG() - dag) * amount) >> 8);
  13738. dag &= 0x00ff00ff;
  13739. dag <<= 8;
  13740. dag |= drb;
  13741. argb = dag;
  13742. }
  13743. /** Copies another pixel colour over this one.
  13744. This doesn't blend it - this colour is simply replaced by the other one.
  13745. */
  13746. template <class Pixel>
  13747. forcedinline void set (const Pixel& src) throw()
  13748. {
  13749. argb = src.getARGB();
  13750. }
  13751. /** Replaces the colour's alpha value with another one. */
  13752. forcedinline void setAlpha (const uint8 newAlpha) throw()
  13753. {
  13754. components.a = newAlpha;
  13755. }
  13756. /** Multiplies the colour's alpha value with another one. */
  13757. forcedinline void multiplyAlpha (int multiplier) throw()
  13758. {
  13759. ++multiplier;
  13760. argb = ((multiplier * getAG()) & 0xff00ff00)
  13761. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  13762. }
  13763. forcedinline void multiplyAlpha (const float multiplier) throw()
  13764. {
  13765. multiplyAlpha ((int) (multiplier * 256.0f));
  13766. }
  13767. /** Sets the pixel's colour from individual components. */
  13768. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  13769. {
  13770. components.b = b;
  13771. components.g = g;
  13772. components.r = r;
  13773. components.a = a;
  13774. }
  13775. /** Premultiplies the pixel's RGB values by its alpha. */
  13776. forcedinline void premultiply() throw()
  13777. {
  13778. const uint32 alpha = components.a;
  13779. if (alpha < 0xff)
  13780. {
  13781. if (alpha == 0)
  13782. {
  13783. components.b = 0;
  13784. components.g = 0;
  13785. components.r = 0;
  13786. }
  13787. else
  13788. {
  13789. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  13790. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  13791. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  13792. }
  13793. }
  13794. }
  13795. /** Unpremultiplies the pixel's RGB values. */
  13796. forcedinline void unpremultiply() throw()
  13797. {
  13798. const uint32 alpha = components.a;
  13799. if (alpha < 0xff)
  13800. {
  13801. if (alpha == 0)
  13802. {
  13803. components.b = 0;
  13804. components.g = 0;
  13805. components.r = 0;
  13806. }
  13807. else
  13808. {
  13809. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  13810. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  13811. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  13812. }
  13813. }
  13814. }
  13815. forcedinline void desaturate() throw()
  13816. {
  13817. if (components.a < 0xff && components.a > 0)
  13818. {
  13819. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  13820. components.r = components.g = components.b
  13821. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  13822. }
  13823. else
  13824. {
  13825. components.r = components.g = components.b
  13826. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  13827. }
  13828. }
  13829. private:
  13830. union
  13831. {
  13832. uint32 argb;
  13833. struct
  13834. {
  13835. #if JUCE_BIG_ENDIAN
  13836. uint8 a : 8, r : 8, g : 8, b : 8;
  13837. #else
  13838. uint8 b, g, r, a;
  13839. #endif
  13840. } PACKED components;
  13841. };
  13842. } PACKED;
  13843. /**
  13844. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  13845. This is used internally by the imaging classes.
  13846. @see PixelARGB
  13847. */
  13848. class JUCE_API PixelRGB
  13849. {
  13850. public:
  13851. /** Creates a pixel without defining its colour. */
  13852. PixelRGB() throw() {}
  13853. ~PixelRGB() throw() {}
  13854. /** Creates a pixel from a 32-bit argb value.
  13855. (The argb format is that used by PixelARGB)
  13856. */
  13857. PixelRGB (const uint32 argb) throw()
  13858. {
  13859. r = (uint8) (argb >> 16);
  13860. g = (uint8) (argb >> 8);
  13861. b = (uint8) (argb);
  13862. }
  13863. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  13864. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  13865. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  13866. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  13867. forcedinline uint8 getRed() const throw() { return r; }
  13868. forcedinline uint8 getGreen() const throw() { return g; }
  13869. forcedinline uint8 getBlue() const throw() { return b; }
  13870. /** Blends another pixel onto this one.
  13871. This takes into account the opacity of the pixel being overlaid, and blends
  13872. it accordingly.
  13873. */
  13874. forcedinline void blend (const PixelARGB& src) throw()
  13875. {
  13876. uint32 sargb = src.getARGB();
  13877. const uint32 alpha = 0x100 - (sargb >> 24);
  13878. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13879. sargb += 0x0000ff00 & (g * alpha);
  13880. r = (uint8) (sargb >> 16);
  13881. g = (uint8) (sargb >> 8);
  13882. b = (uint8) sargb;
  13883. }
  13884. forcedinline void blend (const PixelRGB& src) throw()
  13885. {
  13886. set (src);
  13887. }
  13888. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  13889. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  13890. being used, so this can blend semi-transparently from a PixelRGB argument.
  13891. */
  13892. template <class Pixel>
  13893. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  13894. {
  13895. ++extraAlpha;
  13896. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  13897. const uint32 sag = extraAlpha * src.getAG();
  13898. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  13899. const uint32 alpha = 0x100 - (sargb >> 24);
  13900. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  13901. sargb += 0x0000ff00 & (g * alpha);
  13902. b = (uint8) sargb;
  13903. g = (uint8) (sargb >> 8);
  13904. r = (uint8) (sargb >> 16);
  13905. }
  13906. /** Blends another pixel with this one, creating a colour that is somewhere
  13907. between the two, as specified by the amount.
  13908. */
  13909. template <class Pixel>
  13910. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  13911. {
  13912. uint32 drb = getRB();
  13913. drb += (((src.getRB() - drb) * amount) >> 8);
  13914. uint32 dag = getAG();
  13915. dag += (((src.getAG() - dag) * amount) >> 8);
  13916. b = (uint8) drb;
  13917. g = (uint8) dag;
  13918. r = (uint8) (drb >> 16);
  13919. }
  13920. /** Copies another pixel colour over this one.
  13921. This doesn't blend it - this colour is simply replaced by the other one.
  13922. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  13923. is thrown away.
  13924. */
  13925. template <class Pixel>
  13926. forcedinline void set (const Pixel& src) throw()
  13927. {
  13928. b = src.getBlue();
  13929. g = src.getGreen();
  13930. r = src.getRed();
  13931. }
  13932. /** This method is included for compatibility with the PixelARGB class. */
  13933. forcedinline void setAlpha (const uint8) throw() {}
  13934. /** Multiplies the colour's alpha value with another one. */
  13935. forcedinline void multiplyAlpha (int) throw() {}
  13936. /** Sets the pixel's colour from individual components. */
  13937. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  13938. {
  13939. r = r_;
  13940. g = g_;
  13941. b = b_;
  13942. }
  13943. /** Premultiplies the pixel's RGB values by its alpha. */
  13944. forcedinline void premultiply() throw() {}
  13945. /** Unpremultiplies the pixel's RGB values. */
  13946. forcedinline void unpremultiply() throw() {}
  13947. forcedinline void desaturate() throw()
  13948. {
  13949. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  13950. }
  13951. private:
  13952. #if JUCE_MAC
  13953. uint8 r, g, b;
  13954. #else
  13955. uint8 b, g, r;
  13956. #endif
  13957. } PACKED;
  13958. #if JUCE_MSVC
  13959. #pragma pack (pop)
  13960. #endif
  13961. #undef PACKED
  13962. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  13963. /********* End of inlined file: juce_PixelFormats.h *********/
  13964. /**
  13965. Represents a colour, also including a transparency value.
  13966. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  13967. */
  13968. class JUCE_API Colour
  13969. {
  13970. public:
  13971. /** Creates a transparent black colour. */
  13972. Colour() throw();
  13973. /** Creates a copy of another Colour object. */
  13974. Colour (const Colour& other) throw();
  13975. /** Creates a colour from a 32-bit ARGB value.
  13976. The format of this number is:
  13977. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  13978. All components in the range 0x00 to 0xff.
  13979. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  13980. @see getPixelARGB
  13981. */
  13982. explicit Colour (const uint32 argb) throw();
  13983. /** Creates an opaque colour using 8-bit red, green and blue values */
  13984. Colour (const uint8 red,
  13985. const uint8 green,
  13986. const uint8 blue) throw();
  13987. /** Creates an opaque colour using 8-bit red, green and blue values */
  13988. static const Colour fromRGB (const uint8 red,
  13989. const uint8 green,
  13990. const uint8 blue) throw();
  13991. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13992. Colour (const uint8 red,
  13993. const uint8 green,
  13994. const uint8 blue,
  13995. const uint8 alpha) throw();
  13996. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  13997. static const Colour fromRGBA (const uint8 red,
  13998. const uint8 green,
  13999. const uint8 blue,
  14000. const uint8 alpha) throw();
  14001. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  14002. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  14003. Values outside the valid range will be clipped.
  14004. */
  14005. Colour (const uint8 red,
  14006. const uint8 green,
  14007. const uint8 blue,
  14008. const float alpha) throw();
  14009. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  14010. static const Colour fromRGBAFloat (const uint8 red,
  14011. const uint8 green,
  14012. const uint8 blue,
  14013. const float alpha) throw();
  14014. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14015. The floating point values must be between 0.0 and 1.0.
  14016. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14017. Values outside the valid range will be clipped.
  14018. */
  14019. Colour (const float hue,
  14020. const float saturation,
  14021. const float brightness,
  14022. const uint8 alpha) throw();
  14023. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  14024. All values must be between 0.0 and 1.0.
  14025. Numbers outside the valid range will be clipped.
  14026. */
  14027. Colour (const float hue,
  14028. const float saturation,
  14029. const float brightness,
  14030. const float alpha) throw();
  14031. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14032. The floating point values must be between 0.0 and 1.0.
  14033. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14034. Values outside the valid range will be clipped.
  14035. */
  14036. static const Colour fromHSV (const float hue,
  14037. const float saturation,
  14038. const float brightness,
  14039. const float alpha) throw();
  14040. /** Destructor. */
  14041. ~Colour() throw();
  14042. /** Copies another Colour object. */
  14043. const Colour& operator= (const Colour& other) throw();
  14044. /** Compares two colours. */
  14045. bool operator== (const Colour& other) const throw();
  14046. /** Compares two colours. */
  14047. bool operator!= (const Colour& other) const throw();
  14048. /** Returns the red component of this colour.
  14049. @returns a value between 0x00 and 0xff.
  14050. */
  14051. uint8 getRed() const throw() { return argb.getRed(); }
  14052. /** Returns the green component of this colour.
  14053. @returns a value between 0x00 and 0xff.
  14054. */
  14055. uint8 getGreen() const throw() { return argb.getGreen(); }
  14056. /** Returns the blue component of this colour.
  14057. @returns a value between 0x00 and 0xff.
  14058. */
  14059. uint8 getBlue() const throw() { return argb.getBlue(); }
  14060. /** Returns the red component of this colour as a floating point value.
  14061. @returns a value between 0.0 and 1.0
  14062. */
  14063. float getFloatRed() const throw();
  14064. /** Returns the green component of this colour as a floating point value.
  14065. @returns a value between 0.0 and 1.0
  14066. */
  14067. float getFloatGreen() const throw();
  14068. /** Returns the blue component of this colour as a floating point value.
  14069. @returns a value between 0.0 and 1.0
  14070. */
  14071. float getFloatBlue() const throw();
  14072. /** Returns a premultiplied ARGB pixel object that represents this colour.
  14073. */
  14074. const PixelARGB getPixelARGB() const throw();
  14075. /** Returns a 32-bit integer that represents this colour.
  14076. The format of this number is:
  14077. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  14078. */
  14079. uint32 getARGB() const throw();
  14080. /** Returns the colour's alpha (opacity).
  14081. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  14082. */
  14083. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  14084. /** Returns the colour's alpha (opacity) as a floating point value.
  14085. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  14086. */
  14087. float getFloatAlpha() const throw();
  14088. /** Returns true if this colour is completely opaque.
  14089. Equivalent to (getAlpha() == 0xff).
  14090. */
  14091. bool isOpaque() const throw();
  14092. /** Returns true if this colour is completely transparent.
  14093. Equivalent to (getAlpha() == 0x00).
  14094. */
  14095. bool isTransparent() const throw();
  14096. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14097. const Colour withAlpha (const uint8 newAlpha) const throw();
  14098. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14099. const Colour withAlpha (const float newAlpha) const throw();
  14100. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  14101. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  14102. */
  14103. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  14104. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  14105. If the foreground colour is semi-transparent, it is blended onto this colour
  14106. accordingly.
  14107. */
  14108. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  14109. /** Returns the colour's hue component.
  14110. The value returned is in the range 0.0 to 1.0
  14111. */
  14112. float getHue() const throw();
  14113. /** Returns the colour's saturation component.
  14114. The value returned is in the range 0.0 to 1.0
  14115. */
  14116. float getSaturation() const throw();
  14117. /** Returns the colour's brightness component.
  14118. The value returned is in the range 0.0 to 1.0
  14119. */
  14120. float getBrightness() const throw();
  14121. /** Returns the colour's hue, saturation and brightness components all at once.
  14122. The values returned are in the range 0.0 to 1.0
  14123. */
  14124. void getHSB (float& hue,
  14125. float& saturation,
  14126. float& brightness) const throw();
  14127. /** Returns a copy of this colour with a different hue. */
  14128. const Colour withHue (const float newHue) const throw();
  14129. /** Returns a copy of this colour with a different saturation. */
  14130. const Colour withSaturation (const float newSaturation) const throw();
  14131. /** Returns a copy of this colour with a different brightness.
  14132. @see brighter, darker, withMultipliedBrightness
  14133. */
  14134. const Colour withBrightness (const float newBrightness) const throw();
  14135. /** Returns a copy of this colour with it hue rotated.
  14136. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14137. @see brighter, darker, withMultipliedBrightness
  14138. */
  14139. const Colour withRotatedHue (const float amountToRotate) const throw();
  14140. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14141. The new colour's saturation is (this->getSaturation() * multiplier)
  14142. (the result is clipped to legal limits).
  14143. */
  14144. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14145. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14146. The new colour's saturation is (this->getBrightness() * multiplier)
  14147. (the result is clipped to legal limits).
  14148. */
  14149. const Colour withMultipliedBrightness (const float amount) const throw();
  14150. /** Returns a brighter version of this colour.
  14151. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14152. unchanged, and higher values make it brighter
  14153. @see withMultipliedBrightness
  14154. */
  14155. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14156. /** Returns a darker version of this colour.
  14157. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14158. unchanged, and higher values make it darker
  14159. @see withMultipliedBrightness
  14160. */
  14161. const Colour darker (float amountDarker = 0.4f) const throw();
  14162. /** Returns a colour that will be clearly visible against this colour.
  14163. The amount parameter indicates how contrasting the new colour should
  14164. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14165. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14166. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14167. */
  14168. const Colour contrasting (const float amount = 1.0f) const throw();
  14169. /** Returns a colour that contrasts against two colours.
  14170. Looks for a colour that contrasts with both of the colours passed-in.
  14171. Handy for things like choosing a highlight colour in text editors, etc.
  14172. */
  14173. static const Colour contrasting (const Colour& colour1,
  14174. const Colour& colour2) throw();
  14175. /** Returns an opaque shade of grey.
  14176. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14177. */
  14178. static const Colour greyLevel (const float brightness) throw();
  14179. /** Returns a stringified version of this colour.
  14180. The string can be turned back into a colour using the fromString() method.
  14181. */
  14182. const String toString() const throw();
  14183. /** Reads the colour from a string that was created with toString().
  14184. */
  14185. static const Colour fromString (const String& encodedColourString);
  14186. juce_UseDebuggingNewOperator
  14187. private:
  14188. PixelARGB argb;
  14189. };
  14190. #endif // __JUCE_COLOUR_JUCEHEADER__
  14191. /********* End of inlined file: juce_Colour.h *********/
  14192. /**
  14193. Contains a set of predefined named colours (mostly standard HTML colours)
  14194. @see Colour, Colours::greyLevel
  14195. */
  14196. class Colours
  14197. {
  14198. public:
  14199. static JUCE_API const Colour
  14200. transparentBlack, /**< ARGB = 0x00000000 */
  14201. transparentWhite, /**< ARGB = 0x00ffffff */
  14202. black, /**< ARGB = 0xff000000 */
  14203. white, /**< ARGB = 0xffffffff */
  14204. blue, /**< ARGB = 0xff0000ff */
  14205. grey, /**< ARGB = 0xff808080 */
  14206. green, /**< ARGB = 0xff008000 */
  14207. red, /**< ARGB = 0xffff0000 */
  14208. yellow, /**< ARGB = 0xffffff00 */
  14209. aliceblue, antiquewhite, aqua, aquamarine,
  14210. azure, beige, bisque, blanchedalmond,
  14211. blueviolet, brown, burlywood, cadetblue,
  14212. chartreuse, chocolate, coral, cornflowerblue,
  14213. cornsilk, crimson, cyan, darkblue,
  14214. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14215. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14216. darkorchid, darkred, darksalmon, darkseagreen,
  14217. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14218. deeppink, deepskyblue, dimgrey, dodgerblue,
  14219. firebrick, floralwhite, forestgreen, fuchsia,
  14220. gainsboro, gold, goldenrod, greenyellow,
  14221. honeydew, hotpink, indianred, indigo,
  14222. ivory, khaki, lavender, lavenderblush,
  14223. lemonchiffon, lightblue, lightcoral, lightcyan,
  14224. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14225. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14226. lightsteelblue, lightyellow, lime, limegreen,
  14227. linen, magenta, maroon, mediumaquamarine,
  14228. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14229. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14230. midnightblue, mintcream, mistyrose, navajowhite,
  14231. navy, oldlace, olive, olivedrab,
  14232. orange, orangered, orchid, palegoldenrod,
  14233. palegreen, paleturquoise, palevioletred, papayawhip,
  14234. peachpuff, peru, pink, plum,
  14235. powderblue, purple, rosybrown, royalblue,
  14236. saddlebrown, salmon, sandybrown, seagreen,
  14237. seashell, sienna, silver, skyblue,
  14238. slateblue, slategrey, snow, springgreen,
  14239. steelblue, tan, teal, thistle,
  14240. tomato, turquoise, violet, wheat,
  14241. whitesmoke, yellowgreen;
  14242. /** Attempts to look up a string in the list of known colour names, and return
  14243. the appropriate colour.
  14244. A non-case-sensitive search is made of the list of predefined colours, and
  14245. if a match is found, that colour is returned. If no match is found, the
  14246. colour passed in as the defaultColour parameter is returned.
  14247. */
  14248. static JUCE_API const Colour findColourForName (const String& colourName,
  14249. const Colour& defaultColour);
  14250. private:
  14251. // this isn't a class you should ever instantiate - it's just here for the
  14252. // static values in it.
  14253. Colours();
  14254. };
  14255. #endif // __JUCE_COLOURS_JUCEHEADER__
  14256. /********* End of inlined file: juce_Colours.h *********/
  14257. /********* Start of inlined file: juce_SolidColourBrush.h *********/
  14258. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14259. #define __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14260. /********* Start of inlined file: juce_Brush.h *********/
  14261. #ifndef __JUCE_BRUSH_JUCEHEADER__
  14262. #define __JUCE_BRUSH_JUCEHEADER__
  14263. class Path;
  14264. class AffineTransform;
  14265. class LowLevelGraphicsContext;
  14266. class Image;
  14267. class Graphics;
  14268. /**
  14269. A brush is used to fill areas with colours, patterns, or images.
  14270. The Graphics class has an idea of a current brush which it uses to render
  14271. shapes, rectangles, lines, text, etc.
  14272. This is the base class - there are subclasses for useful types of fill pattern,
  14273. and applications can define their own brushes too.
  14274. @see Graphics::setBrush, SolidColourBrush, GradientBrush, ImageBrush
  14275. */
  14276. class JUCE_API Brush
  14277. {
  14278. protected:
  14279. /** Creates a Brush.
  14280. (Nothing much happens in the base class).
  14281. */
  14282. Brush() throw();
  14283. public:
  14284. /** Destructor. */
  14285. virtual ~Brush() throw();
  14286. /** Creates a copy of whatever class of Brush this is. */
  14287. virtual Brush* createCopy() const throw() = 0;
  14288. /** Does whatever is relevent to transform the geometry of this brush. */
  14289. virtual void applyTransform (const AffineTransform& transform) throw() = 0;
  14290. /** Does whatever is relevent to change the opacity of this brush. */
  14291. virtual void multiplyOpacity (const float multiple) throw() = 0;
  14292. /** Must return true if this brush won't draw any pixels. */
  14293. virtual bool isInvisible() const throw() = 0;
  14294. virtual void paintPath (LowLevelGraphicsContext& context,
  14295. const Path& path, const AffineTransform& transform) throw() = 0;
  14296. virtual void paintRectangle (LowLevelGraphicsContext& context,
  14297. int x, int y, int w, int h) throw() = 0;
  14298. virtual void paintAlphaChannel (LowLevelGraphicsContext& context,
  14299. const Image& alphaChannelImage, int imageX, int imageY,
  14300. int x, int y, int w, int h) throw() = 0;
  14301. virtual void paintVerticalLine (LowLevelGraphicsContext& context,
  14302. int x, float y1, float y2) throw();
  14303. virtual void paintHorizontalLine (LowLevelGraphicsContext& context,
  14304. int y, float x1, float x2) throw();
  14305. virtual void paintLine (LowLevelGraphicsContext& context,
  14306. float x1, float y1, float x2, float y2) throw();
  14307. private:
  14308. Brush (const Brush&);
  14309. const Brush& operator= (const Brush&);
  14310. };
  14311. #endif // __JUCE_BRUSH_JUCEHEADER__
  14312. /********* End of inlined file: juce_Brush.h *********/
  14313. /**
  14314. A Brush that fills its area with a solid (or semi-transparent) colour.
  14315. An application won't normally need to use this class directly, as drawing
  14316. with solid colours is taken care of automatically by the Graphics class
  14317. (it actually uses one of these brushes internally when you set the colour
  14318. with the Graphics::setColour() method).
  14319. @see Brush, Graphics::setBrush, GradientBrush, ImageBrush
  14320. */
  14321. class JUCE_API SolidColourBrush : public Brush
  14322. {
  14323. public:
  14324. /** Creates a SolidColourBrush to draw with the given colour.
  14325. The colour can be changed later with the setColour() method.
  14326. */
  14327. SolidColourBrush (const Colour& colour) throw();
  14328. /** Creates a SolidColourBrush set to black.
  14329. The colour can be changed later with the setColour() method.
  14330. */
  14331. SolidColourBrush() throw();
  14332. /** Destructor. */
  14333. ~SolidColourBrush() throw();
  14334. /** Returns the colour currently being used. */
  14335. const Colour& getColour() const throw() { return colour; }
  14336. /** Sets the colour to use for drawing. */
  14337. void setColour (const Colour& newColour) throw() { colour = newColour; }
  14338. Brush* createCopy() const throw();
  14339. void applyTransform (const AffineTransform& transform) throw();
  14340. bool isInvisible() const throw();
  14341. void multiplyOpacity (const float multiple) throw();
  14342. void paintPath (LowLevelGraphicsContext& context,
  14343. const Path& path, const AffineTransform& transform) throw();
  14344. void paintRectangle (LowLevelGraphicsContext& context,
  14345. int x, int y, int w, int h) throw();
  14346. void paintAlphaChannel (LowLevelGraphicsContext& context,
  14347. const Image& alphaChannelImage, int imageX, int imageY,
  14348. int x, int y, int w, int h) throw();
  14349. void paintVerticalLine (LowLevelGraphicsContext& context,
  14350. int x, float y1, float y2) throw();
  14351. void paintHorizontalLine (LowLevelGraphicsContext& context,
  14352. int y, float x1, float x2) throw();
  14353. void paintLine (LowLevelGraphicsContext& context,
  14354. float x1, float y1, float x2, float y2) throw();
  14355. juce_UseDebuggingNewOperator
  14356. private:
  14357. Colour colour;
  14358. SolidColourBrush (const SolidColourBrush&);
  14359. const SolidColourBrush& operator= (const SolidColourBrush&);
  14360. };
  14361. #endif // __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14362. /********* End of inlined file: juce_SolidColourBrush.h *********/
  14363. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  14364. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14365. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14366. /**
  14367. Defines the method used to postion some kind of rectangular object within
  14368. a rectangular viewport.
  14369. Although similar to Justification, this is more specific, and has some extra
  14370. options.
  14371. */
  14372. class JUCE_API RectanglePlacement
  14373. {
  14374. public:
  14375. /** Creates a RectanglePlacement object using a combination of flags. */
  14376. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  14377. /** Creates a copy of another Justification object. */
  14378. RectanglePlacement (const RectanglePlacement& other) throw();
  14379. /** Copies another Justification object. */
  14380. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  14381. /** Flag values that can be combined and used in the constructor. */
  14382. enum
  14383. {
  14384. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  14385. xLeft = 1,
  14386. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  14387. xRight = 2,
  14388. /** Indicates that the source should be placed in the centre between the left and right
  14389. sides of the available space. */
  14390. xMid = 4,
  14391. /** Indicates that the source's top edge should be aligned with the top edge of the
  14392. destination rectangle. */
  14393. yTop = 8,
  14394. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  14395. destination rectangle. */
  14396. yBottom = 16,
  14397. /** Indicates that the source should be placed in the centre between the top and bottom
  14398. sides of the available space. */
  14399. yMid = 32,
  14400. /** If this flag is set, then the source rectangle will be resized to completely fill
  14401. the destination rectangle, and all other flags are ignored.
  14402. */
  14403. stretchToFit = 64,
  14404. /** If this flag is set, then the source rectangle will be resized so that it is the
  14405. minimum size to completely fill the destination rectangle. This means that some
  14406. of the source rectangle may fall outside the destination.
  14407. If this flag is not set, the source will be given the maximum size at which none
  14408. of it falls outside the destination rectangle.
  14409. */
  14410. fillDestination = 128,
  14411. /** Indicates that the source rectangle can be reduced in size if required, but should
  14412. never be made larger than its original size.
  14413. */
  14414. onlyReduceInSize = 256,
  14415. /** Indicates that the source rectangle can be enlarged if required, but should
  14416. never be made smaller than its original size.
  14417. */
  14418. onlyIncreaseInSize = 512,
  14419. /** Indicates that the source rectangle's size should be left unchanged.
  14420. */
  14421. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  14422. /** A shorthand value that is equivalent to (xMid | yMid). */
  14423. centred = 4 + 32
  14424. };
  14425. /** Returns the raw flags that are set for this object. */
  14426. inline int getFlags() const throw() { return flags; }
  14427. /** Tests a set of flags for this object.
  14428. @returns true if any of the flags passed in are set on this object.
  14429. */
  14430. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14431. /** Adjusts the position and size of a rectangle to fit it into a space.
  14432. The source rectangle co-ordinates will be adjusted so that they fit into
  14433. the destination rectangle based on this object's flags.
  14434. */
  14435. void applyTo (double& sourceX,
  14436. double& sourceY,
  14437. double& sourceW,
  14438. double& sourceH,
  14439. const double destinationX,
  14440. const double destinationY,
  14441. const double destinationW,
  14442. const double destinationH) const throw();
  14443. /** Returns the transform that should be applied to these source co-ordinates to fit them
  14444. into the destination rectangle using the current flags.
  14445. */
  14446. const AffineTransform getTransformToFit (float sourceX,
  14447. float sourceY,
  14448. float sourceW,
  14449. float sourceH,
  14450. const float destinationX,
  14451. const float destinationY,
  14452. const float destinationW,
  14453. const float destinationH) const throw();
  14454. private:
  14455. int flags;
  14456. };
  14457. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14458. /********* End of inlined file: juce_RectanglePlacement.h *********/
  14459. class LowLevelGraphicsContext;
  14460. class Image;
  14461. class RectangleList;
  14462. /**
  14463. A graphics context, used for drawing a component or image.
  14464. When a Component needs painting, a Graphics context is passed to its
  14465. Component::paint() method, and this you then call methods within this
  14466. object to actually draw the component's content.
  14467. A Graphics can also be created from an image, to allow drawing directly onto
  14468. that image.
  14469. @see Component::paint
  14470. */
  14471. class JUCE_API Graphics
  14472. {
  14473. public:
  14474. /** Creates a Graphics object to draw directly onto the given image.
  14475. The graphics object that is created will be set up to draw onto the image,
  14476. with the context's clipping area being the entire size of the image, and its
  14477. origin being the image's origin. To draw into a subsection of an image, use the
  14478. reduceClipRegion() and setOrigin() methods.
  14479. Obviously you shouldn't delete the image before this context is deleted.
  14480. */
  14481. Graphics (Image& imageToDrawOnto) throw();
  14482. /** Destructor. */
  14483. ~Graphics() throw();
  14484. /** Changes the current drawing colour.
  14485. This sets the colour that will now be used for drawing operations - it also
  14486. sets the opacity to that of the colour passed-in.
  14487. If a brush is being used when this method is called, the brush will be deselected,
  14488. and any subsequent drawing will be done with a solid colour brush instead.
  14489. @see setOpacity, setBrush, getColour
  14490. */
  14491. void setColour (const Colour& newColour) throw();
  14492. /** Returns the colour that's currently being used.
  14493. This will return the last colour set by setColour(), even if the colour's not
  14494. currently being used for drawing because a brush has been selected instead.
  14495. @see setColour
  14496. */
  14497. const Colour& getCurrentColour() const throw();
  14498. /** Changes the opacity to use with the current colour.
  14499. If a solid colour is being used for drawing, this changes its opacity (and this
  14500. will be reflected by calls to the getColour() method).
  14501. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  14502. */
  14503. void setOpacity (const float newOpacity) throw();
  14504. /** Changes the current brush to use for drawing.
  14505. If a null pointer is passed in, the context will revert to using a solid
  14506. colour for drawing (using the last colour set by setColour()).
  14507. If a brush is passed in, a copy of it will be used for subsequent drawing
  14508. operations until setColour() or setBrush() is called.
  14509. @see SolidColourBrush, GradientBrush, ImageBrush, Brush
  14510. */
  14511. void setBrush (const Brush* const newBrush) throw();
  14512. /** Changes the font to use for subsequent text-drawing functions.
  14513. Note there's also a setFont (float, int) method to quickly change the size and
  14514. style of the current font.
  14515. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  14516. */
  14517. void setFont (const Font& newFont) throw();
  14518. /** Changes the size and style of the currently-selected font.
  14519. This is a convenient shortcut that changes the context's current font to a
  14520. different size or style. The typeface won't be changed.
  14521. @see Font
  14522. */
  14523. void setFont (const float newFontHeight,
  14524. const int fontStyleFlags = Font::plain) throw();
  14525. /** Returns the font that's currently being used for text operations.
  14526. @see setFont
  14527. */
  14528. const Font& getCurrentFont() const throw();
  14529. /** Draws a one-line text string.
  14530. This will use the current colour (or brush) to fill the text. The font is the last
  14531. one specified by setFont().
  14532. @param text the string to draw
  14533. @param startX the position to draw the left-hand edge of the text
  14534. @param baselineY the position of the text's baseline
  14535. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  14536. */
  14537. void drawSingleLineText (const String& text,
  14538. const int startX,
  14539. const int baselineY) const throw();
  14540. /** Draws text across multiple lines.
  14541. This will break the text onto a new line where there's a new-line or
  14542. carriage-return character, or at a word-boundary when the text becomes wider
  14543. than the size specified by the maximumLineWidth parameter.
  14544. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  14545. */
  14546. void drawMultiLineText (const String& text,
  14547. const int startX,
  14548. const int baselineY,
  14549. const int maximumLineWidth) const throw();
  14550. /** Renders a string of text as a vector path.
  14551. This allows a string to be transformed with an arbitrary AffineTransform and
  14552. rendered using the current colour/brush. It's much slower than the normal text methods
  14553. but more accurate.
  14554. @see setFont
  14555. */
  14556. void drawTextAsPath (const String& text,
  14557. const AffineTransform& transform) const throw();
  14558. /** Draws a line of text within a specified rectangle.
  14559. The text will be positioned within the rectangle based on the justification
  14560. flags passed-in. If the string is too long to fit inside the rectangle, it will
  14561. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  14562. flag is true).
  14563. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  14564. */
  14565. void drawText (const String& text,
  14566. const int x,
  14567. const int y,
  14568. const int width,
  14569. const int height,
  14570. const Justification& justificationType,
  14571. const bool useEllipsesIfTooBig) const throw();
  14572. /** Tries to draw a text string inside a given space.
  14573. This does its best to make the given text readable within the specified rectangle,
  14574. so it useful for labelling things.
  14575. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  14576. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  14577. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  14578. it's been truncated.
  14579. A Justification parameter lets you specify how the text is laid out within the rectangle,
  14580. both horizontally and vertically.
  14581. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  14582. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  14583. can set this value to 1.0f.
  14584. @see GlyphArrangement::addFittedText
  14585. */
  14586. void drawFittedText (const String& text,
  14587. const int x,
  14588. const int y,
  14589. const int width,
  14590. const int height,
  14591. const Justification& justificationFlags,
  14592. const int maximumNumberOfLines,
  14593. const float minimumHorizontalScale = 0.7f) const throw();
  14594. /** Fills the context's entire clip region with the current colour or brush.
  14595. (See also the fillAll (const Colour&) method which is a quick way of filling
  14596. it with a given colour).
  14597. */
  14598. void fillAll() const throw();
  14599. /** Fills the context's entire clip region with a given colour.
  14600. This leaves the context's current colour and brush unchanged, it just
  14601. uses the specified colour temporarily.
  14602. */
  14603. void fillAll (const Colour& colourToUse) const throw();
  14604. /** Fills a rectangle with the current colour or brush.
  14605. @see drawRect, fillRoundedRectangle
  14606. */
  14607. void fillRect (int x,
  14608. int y,
  14609. int width,
  14610. int height) const throw();
  14611. /** Fills a rectangle with the current colour or brush. */
  14612. void fillRect (const Rectangle& rectangle) const throw();
  14613. /** Fills a rectangle with the current colour or brush.
  14614. This uses sub-pixel positioning so is slower than the fillRect method which
  14615. takes integer co-ordinates.
  14616. */
  14617. void fillRect (const float x,
  14618. const float y,
  14619. const float width,
  14620. const float height) const throw();
  14621. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14622. @see drawRoundedRectangle, Path::addRoundedRectangle
  14623. */
  14624. void fillRoundedRectangle (const float x,
  14625. const float y,
  14626. const float width,
  14627. const float height,
  14628. const float cornerSize) const throw();
  14629. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14630. @see drawRoundedRectangle, Path::addRoundedRectangle
  14631. */
  14632. void fillRoundedRectangle (const Rectangle& rectangle,
  14633. const float cornerSize) const throw();
  14634. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  14635. */
  14636. void fillCheckerBoard (int x, int y,
  14637. int width, int height,
  14638. const int checkWidth,
  14639. const int checkHeight,
  14640. const Colour& colour1,
  14641. const Colour& colour2) const throw();
  14642. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14643. The lines are drawn inside the given rectangle, and greater line thicknesses
  14644. extend inwards.
  14645. @see fillRect
  14646. */
  14647. void drawRect (const int x,
  14648. const int y,
  14649. const int width,
  14650. const int height,
  14651. const int lineThickness = 1) const throw();
  14652. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14653. The lines are drawn inside the given rectangle, and greater line thicknesses
  14654. extend inwards.
  14655. @see fillRect
  14656. */
  14657. void drawRect (const float x,
  14658. const float y,
  14659. const float width,
  14660. const float height,
  14661. const float lineThickness = 1.0f) const throw();
  14662. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14663. The lines are drawn inside the given rectangle, and greater line thicknesses
  14664. extend inwards.
  14665. @see fillRect
  14666. */
  14667. void drawRect (const Rectangle& rectangle,
  14668. const int lineThickness = 1) const throw();
  14669. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14670. @see fillRoundedRectangle, Path::addRoundedRectangle
  14671. */
  14672. void drawRoundedRectangle (const float x,
  14673. const float y,
  14674. const float width,
  14675. const float height,
  14676. const float cornerSize,
  14677. const float lineThickness) const throw();
  14678. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14679. @see fillRoundedRectangle, Path::addRoundedRectangle
  14680. */
  14681. void drawRoundedRectangle (const Rectangle& rectangle,
  14682. const float cornerSize,
  14683. const float lineThickness) const throw();
  14684. /** Draws a 3D raised (or indented) bevel using two colours.
  14685. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  14686. extend inwards.
  14687. The top-left colour is used for the top- and left-hand edges of the
  14688. bevel; the bottom-right colour is used for the bottom- and right-hand
  14689. edges.
  14690. */
  14691. void drawBevel (const int x,
  14692. const int y,
  14693. const int width,
  14694. const int height,
  14695. const int bevelThickness,
  14696. const Colour& topLeftColour = Colours::white,
  14697. const Colour& bottomRightColour = Colours::black,
  14698. const bool useGradient = true) const throw();
  14699. /** Draws a pixel using the current colour or brush.
  14700. */
  14701. void setPixel (int x, int y) const throw();
  14702. /** Fills an ellipse with the current colour or brush.
  14703. The ellipse is drawn to fit inside the given rectangle.
  14704. @see drawEllipse, Path::addEllipse
  14705. */
  14706. void fillEllipse (const float x,
  14707. const float y,
  14708. const float width,
  14709. const float height) const throw();
  14710. /** Draws an elliptical stroke using the current colour or brush.
  14711. @see fillEllipse, Path::addEllipse
  14712. */
  14713. void drawEllipse (const float x,
  14714. const float y,
  14715. const float width,
  14716. const float height,
  14717. const float lineThickness) const throw();
  14718. /** Draws a line between two points.
  14719. The line is 1 pixel wide and drawn with the current colour or brush.
  14720. */
  14721. void drawLine (float startX,
  14722. float startY,
  14723. float endX,
  14724. float endY) const throw();
  14725. /** Draws a line between two points with a given thickness.
  14726. @see Path::addLineSegment
  14727. */
  14728. void drawLine (const float startX,
  14729. const float startY,
  14730. const float endX,
  14731. const float endY,
  14732. const float lineThickness) const throw();
  14733. /** Draws a line between two points.
  14734. The line is 1 pixel wide and drawn with the current colour or brush.
  14735. */
  14736. void drawLine (const Line& line) const throw();
  14737. /** Draws a line between two points with a given thickness.
  14738. @see Path::addLineSegment
  14739. */
  14740. void drawLine (const Line& line,
  14741. const float lineThickness) const throw();
  14742. /** Draws a dashed line using a custom set of dash-lengths.
  14743. @param startX the line's start x co-ordinate
  14744. @param startY the line's start y co-ordinate
  14745. @param endX the line's end x co-ordinate
  14746. @param endY the line's end y co-ordinate
  14747. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  14748. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  14749. draw 6 pixels, skip 7 pixels, and then repeat.
  14750. @param numDashLengths the number of elements in the array (this must be an even number).
  14751. @param lineThickness the thickness of the line to draw
  14752. @see PathStrokeType::createDashedStroke
  14753. */
  14754. void drawDashedLine (const float startX,
  14755. const float startY,
  14756. const float endX,
  14757. const float endY,
  14758. const float* const dashLengths,
  14759. const int numDashLengths,
  14760. const float lineThickness = 1.0f) const throw();
  14761. /** Draws a vertical line of pixels at a given x position.
  14762. The x position is an integer, but the top and bottom of the line can be sub-pixel
  14763. positions, and these will be anti-aliased if necessary.
  14764. */
  14765. void drawVerticalLine (const int x, float top, float bottom) const throw();
  14766. /** Draws a horizontal line of pixels at a given y position.
  14767. The y position is an integer, but the left and right ends of the line can be sub-pixel
  14768. positions, and these will be anti-aliased if necessary.
  14769. */
  14770. void drawHorizontalLine (const int y, float left, float right) const throw();
  14771. /** Fills a path using the currently selected colour or brush.
  14772. */
  14773. void fillPath (const Path& path,
  14774. const AffineTransform& transform = AffineTransform::identity) const throw();
  14775. /** Draws a path's outline using the currently selected colour or brush.
  14776. */
  14777. void strokePath (const Path& path,
  14778. const PathStrokeType& strokeType,
  14779. const AffineTransform& transform = AffineTransform::identity) const throw();
  14780. /** Draws a line with an arrowhead.
  14781. @param startX the line's start x co-ordinate
  14782. @param startY the line's start y co-ordinate
  14783. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  14784. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  14785. @param lineThickness the thickness of the line
  14786. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  14787. @param arrowheadLength the length of the arrow head (along the length of the line)
  14788. */
  14789. void drawArrow (const float startX,
  14790. const float startY,
  14791. const float endX,
  14792. const float endY,
  14793. const float lineThickness,
  14794. const float arrowheadWidth,
  14795. const float arrowheadLength) const throw();
  14796. /** Types of rendering quality that can be specified when drawing images.
  14797. @see blendImage, Graphics::setImageResamplingQuality
  14798. */
  14799. enum ResamplingQuality
  14800. {
  14801. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  14802. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  14803. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  14804. };
  14805. /** Changes the quality that will be used when resampling images.
  14806. By default a Graphics object will be set to mediumRenderingQuality.
  14807. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  14808. */
  14809. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  14810. /** Draws an image.
  14811. This will draw the whole of an image, positioning its top-left corner at the
  14812. given co-ordinates, and keeping its size the same. This is the simplest image
  14813. drawing method - the others give more control over the scaling and clipping
  14814. of the images.
  14815. Images are composited using the context's current opacity, so if you
  14816. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14817. (or setColour() with an opaque colour) before drawing images.
  14818. */
  14819. void drawImageAt (const Image* const imageToDraw,
  14820. const int topLeftX,
  14821. const int topLeftY,
  14822. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14823. /** Draws part of an image, rescaling it to fit in a given target region.
  14824. The specified area of the source image is rescaled and drawn to fill the
  14825. specifed destination rectangle.
  14826. Images are composited using the context's current opacity, so if you
  14827. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14828. (or setColour() with an opaque colour) before drawing images.
  14829. @param imageToDraw the image to overlay
  14830. @param destX the left of the destination rectangle
  14831. @param destY the top of the destination rectangle
  14832. @param destWidth the width of the destination rectangle
  14833. @param destHeight the height of the destination rectangle
  14834. @param sourceX the left of the rectangle to copy from the source image
  14835. @param sourceY the top of the rectangle to copy from the source image
  14836. @param sourceWidth the width of the rectangle to copy from the source image
  14837. @param sourceHeight the height of the rectangle to copy from the source image
  14838. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  14839. the source image's alpha channel is used as a mask with
  14840. which to fill the destination using the current colour
  14841. or brush. (If the source is has no alpha channel, then
  14842. it will just fill the target with a solid rectangle)
  14843. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  14844. */
  14845. void drawImage (const Image* const imageToDraw,
  14846. int destX,
  14847. int destY,
  14848. int destWidth,
  14849. int destHeight,
  14850. int sourceX,
  14851. int sourceY,
  14852. int sourceWidth,
  14853. int sourceHeight,
  14854. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14855. /** Draws part of an image, having applied an affine transform to it.
  14856. This lets you throw the image around in some wacky ways, rotate it, shear,
  14857. scale it, etc.
  14858. A clipping subregion is specified within the source image and no pixels
  14859. outside this region will be used.
  14860. Images are composited using the context's current opacity, so if you
  14861. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  14862. (or setColour() with an opaque colour) before drawing images.
  14863. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  14864. are ignored and it is filled with the current brush, masked by its alpha channel.
  14865. @see setImageResamplingQuality, drawImage
  14866. */
  14867. void drawImageTransformed (const Image* const imageToDraw,
  14868. int sourceClipX,
  14869. int sourceClipY,
  14870. int sourceClipWidth,
  14871. int sourceClipHeight,
  14872. const AffineTransform& transform,
  14873. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14874. /** Draws an image to fit within a designated rectangle.
  14875. If the image is too big or too small for the space, it will be rescaled
  14876. to fit as nicely as it can do without affecting its aspect ratio. It will
  14877. then be placed within the target rectangle according to the justification flags
  14878. specified.
  14879. @param imageToDraw the source image to draw
  14880. @param destX top-left of the target rectangle to fit it into
  14881. @param destY top-left of the target rectangle to fit it into
  14882. @param destWidth size of the target rectangle to fit the image into
  14883. @param destHeight size of the target rectangle to fit the image into
  14884. @param placementWithinTarget this specifies how the image should be positioned
  14885. within the target rectangle - see the RectanglePlacement
  14886. class for more details about this.
  14887. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  14888. alpha channel will be used as a mask with which to
  14889. draw with the current brush or colour. This is
  14890. similar to fillAlphaMap(), and see also drawImage()
  14891. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  14892. */
  14893. void drawImageWithin (const Image* const imageToDraw,
  14894. const int destX,
  14895. const int destY,
  14896. const int destWidth,
  14897. const int destHeight,
  14898. const RectanglePlacement& placementWithinTarget,
  14899. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  14900. /** Returns the position of the bounding box for the current clipping region.
  14901. @see getClipRegion, clipRegionIntersects
  14902. */
  14903. const Rectangle getClipBounds() const throw();
  14904. /** Checks whether a rectangle overlaps the context's clipping region.
  14905. If this returns false, no part of the given area can be drawn onto, so this
  14906. method can be used to optimise a component's paint() method, by letting it
  14907. avoid drawing complex objects that aren't within the region being repainted.
  14908. */
  14909. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  14910. /** Intersects the current clipping region with another region.
  14911. @returns true if the resulting clipping region is non-zero in size
  14912. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14913. */
  14914. bool reduceClipRegion (const int x, const int y,
  14915. const int width, const int height) throw();
  14916. /** Intersects the current clipping region with a rectangle list region.
  14917. @returns true if the resulting clipping region is non-zero in size
  14918. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  14919. */
  14920. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  14921. /** Excludes a rectangle to stop it being drawn into. */
  14922. void excludeClipRegion (const int x, const int y,
  14923. const int width, const int height) throw();
  14924. /** Returns true if no drawing can be done because the clip region is zero. */
  14925. bool isClipEmpty() const throw();
  14926. /** Saves the current graphics state on an internal stack.
  14927. To restore the state, use restoreState().
  14928. */
  14929. void saveState() throw();
  14930. /** Restores a graphics state that was previously saved with saveState().
  14931. */
  14932. void restoreState() throw();
  14933. /** Moves the position of the context's origin.
  14934. This changes the position that the context considers to be (0, 0) to
  14935. the specified position.
  14936. So if you call setOrigin (100, 100), then the position that was previously
  14937. referred to as (100, 100) will subsequently be considered to be (0, 0).
  14938. @see reduceClipRegion
  14939. */
  14940. void setOrigin (const int newOriginX,
  14941. const int newOriginY) throw();
  14942. /** Resets the current colour, brush, and font to default settings. */
  14943. void resetToDefaultState() throw();
  14944. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  14945. bool isVectorDevice() const throw();
  14946. juce_UseDebuggingNewOperator
  14947. /** Create a graphics that uses a given low-level renderer.
  14948. For internal use only.
  14949. NB. The context will NOT be deleted by this object when it is deleted.
  14950. */
  14951. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  14952. /** @internal */
  14953. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  14954. private:
  14955. LowLevelGraphicsContext* const context;
  14956. const bool ownsContext;
  14957. struct GraphicsState
  14958. {
  14959. GraphicsState() throw();
  14960. GraphicsState (const GraphicsState&) throw();
  14961. ~GraphicsState() throw();
  14962. Colour colour;
  14963. Brush* brush;
  14964. Font font;
  14965. ResamplingQuality quality;
  14966. };
  14967. GraphicsState* state;
  14968. OwnedArray <GraphicsState> stateStack;
  14969. bool saveStatePending;
  14970. void saveStateIfPending() throw();
  14971. const Graphics& operator= (const Graphics& other);
  14972. Graphics (const Graphics&);
  14973. };
  14974. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  14975. /********* End of inlined file: juce_Graphics.h *********/
  14976. /**
  14977. A graphical effect filter that can be applied to components.
  14978. An ImageEffectFilter can be applied to the image that a component
  14979. paints before it hits the screen.
  14980. This is used for adding effects like shadows, blurs, etc.
  14981. @see Component::setComponentEffect
  14982. */
  14983. class JUCE_API ImageEffectFilter
  14984. {
  14985. public:
  14986. /** Overridden to render the effect.
  14987. The implementation of this method must use the image that is passed in
  14988. as its source, and should render its output to the graphics context passed in.
  14989. @param sourceImage the image that the source component has just rendered with
  14990. its paint() method. The image may or may not have an alpha
  14991. channel, depending on whether the component is opaque.
  14992. @param destContext the graphics context to use to draw the resultant image.
  14993. */
  14994. virtual void applyEffect (Image& sourceImage,
  14995. Graphics& destContext) = 0;
  14996. /** Destructor. */
  14997. virtual ~ImageEffectFilter() {}
  14998. };
  14999. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15000. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  15001. /********* Start of inlined file: juce_RectangleList.h *********/
  15002. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  15003. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  15004. /**
  15005. Maintains a set of rectangles as a complex region.
  15006. This class allows a set of rectangles to be treated as a solid shape, and can
  15007. add and remove rectangular sections of it, and simplify overlapping or
  15008. adjacent rectangles.
  15009. @see Rectangle
  15010. */
  15011. class JUCE_API RectangleList
  15012. {
  15013. public:
  15014. /** Creates an empty RectangleList */
  15015. RectangleList() throw();
  15016. /** Creates a copy of another list */
  15017. RectangleList (const RectangleList& other) throw();
  15018. /** Creates a list containing just one rectangle. */
  15019. RectangleList (const Rectangle& rect) throw();
  15020. /** Copies this list from another one. */
  15021. const RectangleList& operator= (const RectangleList& other) throw();
  15022. /** Destructor. */
  15023. ~RectangleList() throw();
  15024. /** Returns true if the region is empty. */
  15025. bool isEmpty() const throw();
  15026. /** Returns the number of rectangles in the list. */
  15027. int getNumRectangles() const throw() { return rects.size(); }
  15028. /** Returns one of the rectangles at a particular index.
  15029. @returns the rectangle at the index, or an empty rectangle if the
  15030. index is out-of-range.
  15031. */
  15032. const Rectangle getRectangle (const int index) const throw();
  15033. /** Removes all rectangles to leave an empty region. */
  15034. void clear() throw();
  15035. /** Merges a new rectangle into the list.
  15036. The rectangle being added will first be clipped to remove any parts of it
  15037. that overlap existing rectangles in the list.
  15038. */
  15039. void add (const int x, const int y,
  15040. const int w, const int h) throw();
  15041. /** Merges a new rectangle into the list.
  15042. The rectangle being added will first be clipped to remove any parts of it
  15043. that overlap existing rectangles in the list, and adjacent rectangles will be
  15044. merged into it.
  15045. */
  15046. void add (const Rectangle& rect) throw();
  15047. /** Dumbly adds a rectangle to the list without checking for overlaps.
  15048. This simply adds the rectangle to the end, it doesn't merge it or remove
  15049. any overlapping bits.
  15050. */
  15051. void addWithoutMerging (const Rectangle& rect) throw();
  15052. /** Merges another rectangle list into this one.
  15053. Any overlaps between the two lists will be clipped, so that the result is
  15054. the union of both lists.
  15055. */
  15056. void add (const RectangleList& other) throw();
  15057. /** Removes a rectangular region from the list.
  15058. Any rectangles in the list which overlap this will be clipped and subdivided
  15059. if necessary.
  15060. */
  15061. void subtract (const Rectangle& rect) throw();
  15062. /** Removes all areas in another RectangleList from this one.
  15063. Any rectangles in the list which overlap this will be clipped and subdivided
  15064. if necessary.
  15065. */
  15066. void subtract (const RectangleList& otherList) throw();
  15067. /** Removes any areas of the region that lie outside a given rectangle.
  15068. Any rectangles in the list which overlap this will be clipped and subdivided
  15069. if necessary.
  15070. Returns true if the resulting region is not empty, false if it is empty.
  15071. @see getIntersectionWith
  15072. */
  15073. bool clipTo (const Rectangle& rect) throw();
  15074. /** Removes any areas of the region that lie outside a given rectangle list.
  15075. Any rectangles in this object which overlap the specified list will be clipped
  15076. and subdivided if necessary.
  15077. Returns true if the resulting region is not empty, false if it is empty.
  15078. @see getIntersectionWith
  15079. */
  15080. bool clipTo (const RectangleList& other) throw();
  15081. /** Creates a region which is the result of clipping this one to a given rectangle.
  15082. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  15083. resulting region into the list whose reference is passed-in.
  15084. Returns true if the resulting region is not empty, false if it is empty.
  15085. @see clipTo
  15086. */
  15087. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  15088. /** Swaps the contents of this and another list.
  15089. This swaps their internal pointers, so is hugely faster than using copy-by-value
  15090. to swap them.
  15091. */
  15092. void swapWith (RectangleList& otherList) throw();
  15093. /** Checks whether the region contains a given point.
  15094. @returns true if the point lies within one of the rectangles in the list
  15095. */
  15096. bool containsPoint (const int x, const int y) const throw();
  15097. /** Checks whether the region contains the whole of a given rectangle.
  15098. @returns true all parts of the rectangle passed in lie within the region
  15099. defined by this object
  15100. @see intersectsRectangle, containsPoint
  15101. */
  15102. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  15103. /** Checks whether the region contains any part of a given rectangle.
  15104. @returns true if any part of the rectangle passed in lies within the region
  15105. defined by this object
  15106. @see containsRectangle
  15107. */
  15108. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  15109. /** Checks whether this region intersects any part of another one.
  15110. @see intersectsRectangle
  15111. */
  15112. bool intersects (const RectangleList& other) const throw();
  15113. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15114. const Rectangle getBounds() const throw();
  15115. /** Optimises the list into a minimum number of constituent rectangles.
  15116. This will try to combine any adjacent rectangles into larger ones where
  15117. possible, to simplify lists that might have been fragmented by repeated
  15118. add/subtract calls.
  15119. */
  15120. void consolidate() throw();
  15121. /** Adds an x and y value to all the co-ordinates. */
  15122. void offsetAll (const int dx, const int dy) throw();
  15123. /** Creates a Path object to represent this region. */
  15124. const Path toPath() const throw();
  15125. /** An iterator for accessing all the rectangles in a RectangleList. */
  15126. class Iterator
  15127. {
  15128. public:
  15129. Iterator (const RectangleList& list) throw();
  15130. ~Iterator() throw();
  15131. /** Advances to the next rectangle, and returns true if it's not finished.
  15132. Call this before using getRectangle() to find the rectangle that was returned.
  15133. */
  15134. bool next() throw();
  15135. /** Returns the current rectangle. */
  15136. const Rectangle* getRectangle() const throw() { return current; }
  15137. juce_UseDebuggingNewOperator
  15138. private:
  15139. const Rectangle* current;
  15140. const RectangleList& owner;
  15141. int index;
  15142. Iterator (const Iterator&);
  15143. const Iterator& operator= (const Iterator&);
  15144. };
  15145. juce_UseDebuggingNewOperator
  15146. private:
  15147. friend class Iterator;
  15148. Array <Rectangle> rects;
  15149. };
  15150. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15151. /********* End of inlined file: juce_RectangleList.h *********/
  15152. /********* Start of inlined file: juce_BorderSize.h *********/
  15153. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15154. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15155. /**
  15156. Specifies a set of gaps to be left around the sides of a rectangle.
  15157. This is basically the size of the spaces at the top, bottom, left and right of
  15158. a rectangle. It's used by various component classes to specify borders.
  15159. @see Rectangle
  15160. */
  15161. class JUCE_API BorderSize
  15162. {
  15163. public:
  15164. /** Creates a null border.
  15165. All sizes are left as 0.
  15166. */
  15167. BorderSize() throw();
  15168. /** Creates a copy of another border. */
  15169. BorderSize (const BorderSize& other) throw();
  15170. /** Creates a border with the given gaps. */
  15171. BorderSize (const int topGap,
  15172. const int leftGap,
  15173. const int bottomGap,
  15174. const int rightGap) throw();
  15175. /** Creates a border with the given gap on all sides. */
  15176. BorderSize (const int allGaps) throw();
  15177. /** Destructor. */
  15178. ~BorderSize() throw();
  15179. /** Returns the gap that should be left at the top of the region. */
  15180. int getTop() const throw() { return top; }
  15181. /** Returns the gap that should be left at the top of the region. */
  15182. int getLeft() const throw() { return left; }
  15183. /** Returns the gap that should be left at the top of the region. */
  15184. int getBottom() const throw() { return bottom; }
  15185. /** Returns the gap that should be left at the top of the region. */
  15186. int getRight() const throw() { return right; }
  15187. /** Returns the sum of the top and bottom gaps. */
  15188. int getTopAndBottom() const throw() { return top + bottom; }
  15189. /** Returns the sum of the left and right gaps. */
  15190. int getLeftAndRight() const throw() { return left + right; }
  15191. /** Changes the top gap. */
  15192. void setTop (const int newTopGap) throw();
  15193. /** Changes the left gap. */
  15194. void setLeft (const int newLeftGap) throw();
  15195. /** Changes the bottom gap. */
  15196. void setBottom (const int newBottomGap) throw();
  15197. /** Changes the right gap. */
  15198. void setRight (const int newRightGap) throw();
  15199. /** Returns a rectangle with these borders removed from it. */
  15200. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15201. /** Removes this border from a given rectangle. */
  15202. void subtractFrom (Rectangle& rectangle) const throw();
  15203. /** Returns a rectangle with these borders added around it. */
  15204. const Rectangle addedTo (const Rectangle& original) const throw();
  15205. /** Adds this border around a given rectangle. */
  15206. void addTo (Rectangle& original) const throw();
  15207. bool operator== (const BorderSize& other) const throw();
  15208. bool operator!= (const BorderSize& other) const throw();
  15209. juce_UseDebuggingNewOperator
  15210. private:
  15211. int top, left, bottom, right;
  15212. };
  15213. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15214. /********* End of inlined file: juce_BorderSize.h *********/
  15215. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15216. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15217. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15218. class Component;
  15219. class Graphics;
  15220. /********* Start of inlined file: juce_MessageListener.h *********/
  15221. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15222. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15223. /********* Start of inlined file: juce_Message.h *********/
  15224. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15225. #define __JUCE_MESSAGE_JUCEHEADER__
  15226. class MessageListener;
  15227. class MessageManager;
  15228. /** The base class for objects that can be delivered to a MessageListener.
  15229. The simplest Message object contains a few integer and pointer parameters
  15230. that the user can set, and this is enough for a lot of purposes. For passing more
  15231. complex data, subclasses of Message can also be used.
  15232. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15233. */
  15234. class JUCE_API Message
  15235. {
  15236. public:
  15237. /** Creates an uninitialised message.
  15238. The class's variables will also be left uninitialised.
  15239. */
  15240. Message() throw();
  15241. /** Creates a message object, filling in the member variables.
  15242. The corresponding public member variables will be set from the parameters
  15243. passed in.
  15244. */
  15245. Message (const int intParameter1,
  15246. const int intParameter2,
  15247. const int intParameter3,
  15248. void* const pointerParameter) throw();
  15249. /** Destructor. */
  15250. virtual ~Message() throw();
  15251. // These values can be used for carrying simple data that the application needs to
  15252. // pass around. For more complex messages, just create a subclass.
  15253. int intParameter1; /**< user-defined integer value. */
  15254. int intParameter2; /**< user-defined integer value. */
  15255. int intParameter3; /**< user-defined integer value. */
  15256. void* pointerParameter; /**< user-defined pointer value. */
  15257. juce_UseDebuggingNewOperator
  15258. private:
  15259. friend class MessageListener;
  15260. friend class MessageManager;
  15261. MessageListener* messageRecipient;
  15262. Message (const Message&);
  15263. const Message& operator= (const Message&);
  15264. };
  15265. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15266. /********* End of inlined file: juce_Message.h *********/
  15267. /**
  15268. MessageListener subclasses can post and receive Message objects.
  15269. @see Message, MessageManager, ActionListener, ChangeListener
  15270. */
  15271. class JUCE_API MessageListener
  15272. {
  15273. protected:
  15274. /** Creates a MessageListener. */
  15275. MessageListener() throw();
  15276. public:
  15277. /** Destructor.
  15278. When a MessageListener is deleted, it removes itself from a global list
  15279. of registered listeners, so that the isValidMessageListener() method
  15280. will no longer return true.
  15281. */
  15282. virtual ~MessageListener();
  15283. /** This is the callback method that receives incoming messages.
  15284. This is called by the MessageManager from its dispatch loop.
  15285. @see postMessage
  15286. */
  15287. virtual void handleMessage (const Message& message) = 0;
  15288. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15289. later on.
  15290. This method can be called safely by any thread.
  15291. @param message the message object to send - this will be deleted
  15292. automatically by the message queue, so don't keep any
  15293. references to it after calling this method.
  15294. @see handleMessage
  15295. */
  15296. void postMessage (Message* const message) const throw();
  15297. /** Checks whether this MessageListener has been deleted.
  15298. Although not foolproof, this method is safe to call on dangling or null
  15299. pointers. A list of active MessageListeners is kept internally, so this
  15300. checks whether the object is on this list or not.
  15301. Note that it's possible to get a false-positive here, if an object is
  15302. deleted and another is subsequently created that happens to be at the
  15303. exact same memory location, but I can't think of a good way of avoiding
  15304. this.
  15305. */
  15306. bool isValidMessageListener() const throw();
  15307. };
  15308. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  15309. /********* End of inlined file: juce_MessageListener.h *********/
  15310. class ComponentBoundsConstrainer;
  15311. class ComponentDeletionWatcher;
  15312. /**
  15313. The base class for window objects that wrap a component as a real operating
  15314. system object.
  15315. This is an abstract base class - the platform specific code contains default
  15316. implementations of it that create and manage windows.
  15317. @see Component::createNewPeer
  15318. */
  15319. class JUCE_API ComponentPeer : public MessageListener
  15320. {
  15321. public:
  15322. /** A combination of these flags is passed to the ComponentPeer constructor. */
  15323. enum StyleFlags
  15324. {
  15325. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  15326. entry on the taskbar (ignored on MacOSX) */
  15327. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  15328. tooltip, etc. */
  15329. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  15330. through it (may not be possible on some platforms). */
  15331. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  15332. title bar and frame\. if not specified, the window will be
  15333. borderless. */
  15334. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  15335. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  15336. minimise button on it. */
  15337. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  15338. maximise button on it. */
  15339. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  15340. close button on it. */
  15341. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  15342. not be possible on all platforms). */
  15343. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  15344. do its own repainting, but only to repaint when the
  15345. performAnyPendingRepaintsNow() method is called. */
  15346. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  15347. be used for things like plugin windows, to stop them interfering
  15348. with the host's shortcut keys */
  15349. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  15350. };
  15351. /** Creates a peer.
  15352. The component is the one that we intend to represent, and the style flags are
  15353. a combination of the values in the StyleFlags enum
  15354. */
  15355. ComponentPeer (Component* const component,
  15356. const int styleFlags) throw();
  15357. /** Destructor. */
  15358. virtual ~ComponentPeer();
  15359. /** Returns the component being represented by this peer. */
  15360. Component* getComponent() const throw() { return component; }
  15361. /** Returns the set of style flags that were set when the window was created.
  15362. @see Component::addToDesktop
  15363. */
  15364. int getStyleFlags() const throw() { return styleFlags; }
  15365. /** Returns the raw handle to whatever kind of window is being used.
  15366. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  15367. but rememeber there's no guarantees what you'll get back.
  15368. */
  15369. virtual void* getNativeHandle() const = 0;
  15370. /** Shows or hides the window. */
  15371. virtual void setVisible (bool shouldBeVisible) = 0;
  15372. /** Changes the title of the window. */
  15373. virtual void setTitle (const String& title) = 0;
  15374. /** Moves the window without changing its size.
  15375. If the native window is contained in another window, then the co-ordinates are
  15376. relative to the parent window's origin, not the screen origin.
  15377. This should result in a callback to handleMovedOrResized().
  15378. */
  15379. virtual void setPosition (int x, int y) = 0;
  15380. /** Resizes the window without changing its position.
  15381. This should result in a callback to handleMovedOrResized().
  15382. */
  15383. virtual void setSize (int w, int h) = 0;
  15384. /** Moves and resizes the window.
  15385. If the native window is contained in another window, then the co-ordinates are
  15386. relative to the parent window's origin, not the screen origin.
  15387. This should result in a callback to handleMovedOrResized().
  15388. */
  15389. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  15390. /** Returns the current position and size of the window.
  15391. If the native window is contained in another window, then the co-ordinates are
  15392. relative to the parent window's origin, not the screen origin.
  15393. */
  15394. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  15395. /** Returns the x-position of this window, relative to the screen's origin. */
  15396. virtual int getScreenX() const = 0;
  15397. /** Returns the y-position of this window, relative to the screen's origin. */
  15398. virtual int getScreenY() const = 0;
  15399. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  15400. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  15401. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  15402. virtual void globalPositionToRelative (int& x, int& y) = 0;
  15403. /** Minimises the window. */
  15404. virtual void setMinimised (bool shouldBeMinimised) = 0;
  15405. /** True if the window is currently minimised. */
  15406. virtual bool isMinimised() const = 0;
  15407. /** Enable/disable fullscreen mode for the window. */
  15408. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  15409. /** True if the window is currently full-screen. */
  15410. virtual bool isFullScreen() const = 0;
  15411. /** Sets the size to restore to if fullscreen mode is turned off. */
  15412. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  15413. /** Returns the size to restore to if fullscreen mode is turned off. */
  15414. const Rectangle& getNonFullScreenBounds() const throw();
  15415. /** Attempts to change the icon associated with this window.
  15416. */
  15417. virtual void setIcon (const Image& newIcon) = 0;
  15418. /** Sets a constrainer to use if the peer can resize itself.
  15419. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  15420. */
  15421. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  15422. /** Returns the current constrainer, if one has been set. */
  15423. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  15424. /** Checks if a point is in the window.
  15425. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  15426. is false, then this returns false if the point is actually inside a child of this
  15427. window.
  15428. */
  15429. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  15430. /** Returns the size of the window frame that's around this window.
  15431. Whether or not the window has a normal window frame depends on the flags
  15432. that were set when the window was created by Component::addToDesktop()
  15433. */
  15434. virtual const BorderSize getFrameSize() const = 0;
  15435. /** This is called when the window's bounds change.
  15436. A peer implementation must call this when the window is moved and resized, so that
  15437. this method can pass the message on to the component.
  15438. */
  15439. void handleMovedOrResized();
  15440. /** This is called if the screen resolution changes.
  15441. A peer implementation must call this if the monitor arrangement changes or the available
  15442. screen size changes.
  15443. */
  15444. void handleScreenSizeChange();
  15445. /** This is called to repaint the component into the given context. */
  15446. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  15447. /** Sets this window to either be always-on-top or normal.
  15448. Some kinds of window might not be able to do this, so should return false.
  15449. */
  15450. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  15451. /** Brings the window to the top, optionally also giving it focus. */
  15452. virtual void toFront (bool makeActive) = 0;
  15453. /** Moves the window to be just behind another one. */
  15454. virtual void toBehind (ComponentPeer* other) = 0;
  15455. /** Called when the window is brought to the front, either by the OS or by a call
  15456. to toFront().
  15457. */
  15458. void handleBroughtToFront();
  15459. /** True if the window has the keyboard focus. */
  15460. virtual bool isFocused() const = 0;
  15461. /** Tries to give the window keyboard focus. */
  15462. virtual void grabFocus() = 0;
  15463. /** Tells the window that text input may be required at the given position.
  15464. This may cause things like a virtual on-screen keyboard to appear, depending
  15465. on the OS.
  15466. */
  15467. virtual void textInputRequired (int x, int y) = 0;
  15468. /** Called when the window gains keyboard focus. */
  15469. void handleFocusGain();
  15470. /** Called when the window loses keyboard focus. */
  15471. void handleFocusLoss();
  15472. Component* getLastFocusedSubcomponent() const throw();
  15473. /** Called when a key is pressed.
  15474. For keycode info, see the KeyPress class.
  15475. Returns true if the keystroke was used.
  15476. */
  15477. bool handleKeyPress (const int keyCode,
  15478. const juce_wchar textCharacter);
  15479. /** Called whenever a key is pressed or released.
  15480. Returns true if the keystroke was used.
  15481. */
  15482. bool handleKeyUpOrDown();
  15483. /** Called whenever a modifier key is pressed or released. */
  15484. void handleModifierKeysChange();
  15485. /** Invalidates a region of the window to be repainted asynchronously. */
  15486. virtual void repaint (int x, int y, int w, int h) = 0;
  15487. /** This can be called (from the message thread) to cause the immediate redrawing
  15488. of any areas of this window that need repainting.
  15489. You shouldn't ever really need to use this, it's mainly for special purposes
  15490. like supporting audio plugins where the host's event loop is out of our control.
  15491. */
  15492. virtual void performAnyPendingRepaintsNow() = 0;
  15493. void handleMouseEnter (int x, int y, const int64 time);
  15494. void handleMouseMove (int x, int y, const int64 time);
  15495. void handleMouseDown (int x, int y, const int64 time);
  15496. void handleMouseDrag (int x, int y, const int64 time);
  15497. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  15498. void handleMouseExit (int x, int y, const int64 time);
  15499. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  15500. /** Causes a mouse-move callback to be made asynchronously. */
  15501. void sendFakeMouseMove() throw();
  15502. void handleUserClosingWindow();
  15503. void handleFileDragMove (const StringArray& files, int x, int y);
  15504. void handleFileDragExit (const StringArray& files);
  15505. void handleFileDragDrop (const StringArray& files, int x, int y);
  15506. /** Resets the masking region.
  15507. The subclass should call this every time it's about to call the handlePaint
  15508. method.
  15509. @see addMaskedRegion
  15510. */
  15511. void clearMaskedRegion() throw();
  15512. /** Adds a rectangle to the set of areas not to paint over.
  15513. A component can call this on its peer during its paint() method, to signal
  15514. that the painting code should ignore a given region. The reason
  15515. for this is to stop embedded windows (such as OpenGL) getting painted over.
  15516. The masked region is cleared each time before a paint happens, so a component
  15517. will have to make sure it calls this every time it's painted.
  15518. */
  15519. void addMaskedRegion (int x, int y, int w, int h) throw();
  15520. /** Returns the number of currently-active peers.
  15521. @see getPeer
  15522. */
  15523. static int getNumPeers() throw();
  15524. /** Returns one of the currently-active peers.
  15525. @see getNumPeers
  15526. */
  15527. static ComponentPeer* getPeer (const int index) throw();
  15528. /** Checks if this peer object is valid.
  15529. @see getNumPeers
  15530. */
  15531. static bool isValidPeer (const ComponentPeer* const peer) throw();
  15532. juce_UseDebuggingNewOperator
  15533. protected:
  15534. Component* const component;
  15535. const int styleFlags;
  15536. RectangleList maskedRegion;
  15537. Rectangle lastNonFullscreenBounds;
  15538. uint32 lastPaintTime;
  15539. ComponentBoundsConstrainer* constrainer;
  15540. static void updateCurrentModifiers() throw();
  15541. /** @internal */
  15542. void handleMessage (const Message& message);
  15543. private:
  15544. Component* lastFocusedComponent;
  15545. ComponentDeletionWatcher* dragAndDropTargetComponent;
  15546. Component* lastDragAndDropCompUnderMouse;
  15547. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  15548. friend class Component;
  15549. static ComponentPeer* getPeerFor (const Component* const component) throw();
  15550. void setLastDragDropTarget (Component* comp);
  15551. ComponentPeer (const ComponentPeer&);
  15552. const ComponentPeer& operator= (const ComponentPeer&);
  15553. };
  15554. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  15555. /********* End of inlined file: juce_ComponentPeer.h *********/
  15556. class LookAndFeel;
  15557. /**
  15558. The base class for all JUCE user-interface objects.
  15559. */
  15560. class JUCE_API Component : public MouseListener,
  15561. protected MessageListener
  15562. {
  15563. public:
  15564. /** Creates a component.
  15565. To get it to actually appear, you'll also need to:
  15566. - Either add it to a parent component or use the addToDesktop() method to
  15567. make it a desktop window
  15568. - Set its size and position to something sensible
  15569. - Use setVisible() to make it visible
  15570. And for it to serve any useful purpose, you'll need to write a
  15571. subclass of Component or use one of the other types of component from
  15572. the library.
  15573. */
  15574. Component() throw();
  15575. /** Destructor.
  15576. Note that when a component is deleted, any child components it might
  15577. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  15578. */
  15579. virtual ~Component();
  15580. /** Creates a component, setting its name at the same time.
  15581. @see getName, setName
  15582. */
  15583. Component (const String& componentName) throw();
  15584. /** Returns the name of this component.
  15585. @see setName
  15586. */
  15587. const String& getName() const throw() { return componentName_; }
  15588. /** Sets the name of this component.
  15589. When the name changes, all registered ComponentListeners will receive a
  15590. ComponentListener::componentNameChanged() callback.
  15591. @see getName
  15592. */
  15593. virtual void setName (const String& newName);
  15594. /** Checks whether this Component object has been deleted.
  15595. This will check whether this object is still a valid component, or whether
  15596. it's been deleted.
  15597. It's safe to call this on null or dangling pointers, but note that there is a
  15598. small risk if another new (but different) component has been created at the
  15599. same memory address which this one occupied, this methods can return a
  15600. false positive.
  15601. */
  15602. bool isValidComponent() const throw();
  15603. /** Makes the component visible or invisible.
  15604. This method will show or hide the component.
  15605. Note that components default to being non-visible when first created.
  15606. Also note that visible components won't be seen unless all their parent components
  15607. are also visible.
  15608. This method will call visibilityChanged() and also componentVisibilityChanged()
  15609. for any component listeners that are interested in this component.
  15610. @param shouldBeVisible whether to show or hide the component
  15611. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  15612. */
  15613. virtual void setVisible (bool shouldBeVisible);
  15614. /** Tests whether the component is visible or not.
  15615. this doesn't necessarily tell you whether this comp is actually on the screen
  15616. because this depends on whether all the parent components are also visible - use
  15617. isShowing() to find this out.
  15618. @see isShowing, setVisible
  15619. */
  15620. bool isVisible() const throw() { return flags.visibleFlag; }
  15621. /** Called when this component's visiblility changes.
  15622. @see setVisible, isVisible
  15623. */
  15624. virtual void visibilityChanged();
  15625. /** Tests whether this component and all its parents are visible.
  15626. @returns true only if this component and all its parents are visible.
  15627. @see isVisible
  15628. */
  15629. bool isShowing() const throw();
  15630. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  15631. To do this, this function will cunningly:
  15632. - take a snapshot of the component as it currently looks
  15633. - call setVisible(false) on the component
  15634. - replace it with a special component that will continue drawing the
  15635. snapshot, animating it and gradually making it more transparent
  15636. - when it's gone, the special component will also be deleted
  15637. As soon as this method returns, the component can be safely removed and deleted
  15638. leaving the proxy to do the fade-out, so it's even ok to call this in a
  15639. component's destructor.
  15640. Passing non-zero x and y values will cause the ghostly component image to
  15641. also whizz off by this distance while fading out. If the scale factor is
  15642. not 1.0, it will also zoom from the component's current size to this new size.
  15643. One thing to be careful about is that the parent component must be able to cope
  15644. with this unknown component type being added to it.
  15645. */
  15646. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  15647. const int deltaXToMove = 0,
  15648. const int deltaYToMove = 0,
  15649. const float scaleFactorAtEnd = 1.0f);
  15650. /** Makes this component appear as a window on the desktop.
  15651. Note that before calling this, you should make sure that the component's opacity is
  15652. set correctly using setOpaque(). If the component is non-opaque, the windowing
  15653. system will try to create a special transparent window for it, which will generally take
  15654. a lot more CPU to operate (and might not even be possible on some platforms).
  15655. If the component is inside a parent component at the time this method is called, it
  15656. will be first be removed from that parent. Likewise if a component on the desktop
  15657. is subsequently added to another component, it'll be removed from the desktop.
  15658. @param windowStyleFlags a combination of the flags specified in the
  15659. ComponentPeer::StyleFlags enum, which define the
  15660. window's characteristics.
  15661. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  15662. in which the juce component should place itself. On Windows,
  15663. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  15664. supported on all platforms, and best left as 0 unless you know
  15665. what you're doing
  15666. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  15667. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  15668. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  15669. */
  15670. virtual void addToDesktop (int windowStyleFlags,
  15671. void* nativeWindowToAttachTo = 0);
  15672. /** If the component is currently showing on the desktop, this will hide it.
  15673. You can also use setVisible() to hide a desktop window temporarily, but
  15674. removeFromDesktop() will free any system resources that are being used up.
  15675. @see addToDesktop, isOnDesktop
  15676. */
  15677. void removeFromDesktop();
  15678. /** Returns true if this component is currently showing on the desktop.
  15679. @see addToDesktop, removeFromDesktop
  15680. */
  15681. bool isOnDesktop() const throw();
  15682. /** Returns the heavyweight window that contains this component.
  15683. If this component is itself on the desktop, this will return the window
  15684. object that it is using. Otherwise, it will return the window of
  15685. its top-level parent component.
  15686. This may return 0 if there isn't a desktop component.
  15687. @see addToDesktop, isOnDesktop
  15688. */
  15689. ComponentPeer* getPeer() const throw();
  15690. /** For components on the desktop, this is called if the system wants to close the window.
  15691. This is a signal that either the user or the system wants the window to close. The
  15692. default implementation of this method will trigger an assertion to warn you that your
  15693. component should do something about it, but you can override this to ignore the event
  15694. if you want.
  15695. */
  15696. virtual void userTriedToCloseWindow();
  15697. /** Called for a desktop component which has just been minimised or un-minimised.
  15698. This will only be called for components on the desktop.
  15699. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  15700. */
  15701. virtual void minimisationStateChanged (bool isNowMinimised);
  15702. /** Brings the component to the front of its siblings.
  15703. If some of the component's siblings have had their 'always-on-top' flag set,
  15704. then they will still be kept in front of this one (unless of course this
  15705. one is also 'always-on-top').
  15706. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  15707. to the component (see grabKeyboardFocus() for more details)
  15708. @see toBack, toBehind, setAlwaysOnTop
  15709. */
  15710. void toFront (const bool shouldAlsoGainFocus);
  15711. /** Changes this component's z-order to be at the back of all its siblings.
  15712. If the component is set to be 'always-on-top', it will only be moved to the
  15713. back of the other other 'always-on-top' components.
  15714. @see toFront, toBehind, setAlwaysOnTop
  15715. */
  15716. void toBack();
  15717. /** Changes this component's z-order so that it's just behind another component.
  15718. @see toFront, toBack
  15719. */
  15720. void toBehind (Component* const other);
  15721. /** Sets whether the component should always be kept at the front of its siblings.
  15722. @see isAlwaysOnTop
  15723. */
  15724. void setAlwaysOnTop (const bool shouldStayOnTop);
  15725. /** Returns true if this component is set to always stay in front of its siblings.
  15726. @see setAlwaysOnTop
  15727. */
  15728. bool isAlwaysOnTop() const throw();
  15729. /** Returns the x co-ordinate of the component's left edge.
  15730. This is a distance in pixels from the left edge of the component's parent.
  15731. @see getScreenX
  15732. */
  15733. inline int getX() const throw() { return bounds_.getX(); }
  15734. /** Returns the y co-ordinate of the top of this component.
  15735. This is a distance in pixels from the top edge of the component's parent.
  15736. @see getScreenY
  15737. */
  15738. inline int getY() const throw() { return bounds_.getY(); }
  15739. /** Returns the component's width in pixels. */
  15740. inline int getWidth() const throw() { return bounds_.getWidth(); }
  15741. /** Returns the component's height in pixels. */
  15742. inline int getHeight() const throw() { return bounds_.getHeight(); }
  15743. /** Returns the x co-ordinate of the component's right-hand edge.
  15744. This is a distance in pixels from the left edge of the component's parent.
  15745. */
  15746. int getRight() const throw() { return bounds_.getRight(); }
  15747. /** Returns the y co-ordinate of the bottom edge of this component.
  15748. This is a distance in pixels from the top edge of the component's parent.
  15749. */
  15750. int getBottom() const throw() { return bounds_.getBottom(); }
  15751. /** Returns this component's bounding box.
  15752. The rectangle returned is relative to the top-left of the component's parent.
  15753. */
  15754. const Rectangle& getBounds() const throw() { return bounds_; }
  15755. /** Returns the region of this component that's not obscured by other, opaque components.
  15756. The RectangleList that is returned represents the area of this component
  15757. which isn't covered by opaque child components.
  15758. If includeSiblings is true, it will also take into account any siblings
  15759. that may be overlapping the component.
  15760. */
  15761. void getVisibleArea (RectangleList& result,
  15762. const bool includeSiblings) const;
  15763. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  15764. @see getX, relativePositionToGlobal
  15765. */
  15766. int getScreenX() const throw();
  15767. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  15768. @see getY, relativePositionToGlobal
  15769. */
  15770. int getScreenY() const throw();
  15771. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  15772. @see globalPositionToRelative, relativePositionToOtherComponent
  15773. */
  15774. void relativePositionToGlobal (int& x, int& y) const throw();
  15775. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  15776. @see relativePositionToGlobal, relativePositionToOtherComponent
  15777. */
  15778. void globalPositionToRelative (int& x, int& y) const throw();
  15779. /** Converts a position relative to this component's top-left into a position
  15780. relative to another component's top-left.
  15781. @see relativePositionToGlobal, globalPositionToRelative
  15782. */
  15783. void relativePositionToOtherComponent (const Component* const targetComponent,
  15784. int& x, int& y) const throw();
  15785. /** Moves the component to a new position.
  15786. Changes the component's top-left position (without changing its size).
  15787. The position is relative to the top-left of the component's parent.
  15788. If the component actually moves, this method will make a synchronous call to moved().
  15789. @see setBounds, ComponentListener::componentMovedOrResized
  15790. */
  15791. void setTopLeftPosition (const int x, const int y);
  15792. /** Moves the component to a new position.
  15793. Changes the position of the component's top-right corner (keeping it the same size).
  15794. The position is relative to the top-left of the component's parent.
  15795. If the component actually moves, this method will make a synchronous call to moved().
  15796. */
  15797. void setTopRightPosition (const int x, const int y);
  15798. /** Changes the size of the component.
  15799. A synchronous call to resized() will be occur if the size actually changes.
  15800. */
  15801. void setSize (const int newWidth, const int newHeight);
  15802. /** Changes the component's position and size.
  15803. The co-ordinates are relative to the top-left of the component's parent, or relative
  15804. to the origin of the screen is the component is on the desktop.
  15805. If this method changes the component's top-left position, it will make a synchronous
  15806. call to moved(). If it changes the size, it will also make a call to resized().
  15807. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  15808. */
  15809. void setBounds (int x, int y, int width, int height);
  15810. /** Changes the component's position and size.
  15811. @see setBounds
  15812. */
  15813. void setBounds (const Rectangle& newBounds);
  15814. /** Changes the component's position and size in terms of fractions of its parent's size.
  15815. The values are factors of the parent's size, so for example
  15816. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  15817. width and height of the parent, with its top-left position 20% of
  15818. the way across and down the parent.
  15819. */
  15820. void setBoundsRelative (const float proportionalX, const float proportionalY,
  15821. const float proportionalWidth, const float proportionalHeight);
  15822. /** Changes the component's position and size based on the amount of space to leave around it.
  15823. This will position the component within its parent, leaving the specified number of
  15824. pixels around each edge.
  15825. */
  15826. void setBoundsInset (const BorderSize& borders);
  15827. /** Positions the component within a given rectangle, keeping its proportions
  15828. unchanged.
  15829. If onlyReduceInSize is false, the component will be resized to fill as much of the
  15830. rectangle as possible without changing its aspect ratio (the component's
  15831. current size is used to determine its aspect ratio, so a zero-size component
  15832. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  15833. too big to fit inside the rectangle.
  15834. It will then be positioned within the rectangle according to the justification flags
  15835. specified.
  15836. */
  15837. void setBoundsToFit (int x, int y, int width, int height,
  15838. const Justification& justification,
  15839. const bool onlyReduceInSize);
  15840. /** Changes the position of the component's centre.
  15841. Leaves the component's size unchanged, but sets the position of its centre
  15842. relative to its parent's top-left.
  15843. */
  15844. void setCentrePosition (const int x, const int y);
  15845. /** Changes the position of the component's centre.
  15846. Leaves the position unchanged, but positions its centre relative to its
  15847. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  15848. its parent.
  15849. */
  15850. void setCentreRelative (const float x, const float y);
  15851. /** Changes the component's size and centres it within its parent.
  15852. After changing the size, the component will be moved so that it's
  15853. centred within its parent.
  15854. */
  15855. void centreWithSize (const int width, const int height);
  15856. /** Returns a proportion of the component's width.
  15857. This is a handy equivalent of (getWidth() * proportion).
  15858. */
  15859. int proportionOfWidth (const float proportion) const throw();
  15860. /** Returns a proportion of the component's height.
  15861. This is a handy equivalent of (getHeight() * proportion).
  15862. */
  15863. int proportionOfHeight (const float proportion) const throw();
  15864. /** Returns the width of the component's parent.
  15865. If the component has no parent (i.e. if it's on the desktop), this will return
  15866. the width of the screen.
  15867. */
  15868. int getParentWidth() const throw();
  15869. /** Returns the height of the component's parent.
  15870. If the component has no parent (i.e. if it's on the desktop), this will return
  15871. the height of the screen.
  15872. */
  15873. int getParentHeight() const throw();
  15874. /** Returns the screen co-ordinates of the monitor that contains this component.
  15875. If there's only one monitor, this will return its size - if there are multiple
  15876. monitors, it will return the area of the monitor that contains the component's
  15877. centre.
  15878. */
  15879. const Rectangle getParentMonitorArea() const throw();
  15880. /** Returns the number of child components that this component contains.
  15881. @see getChildComponent, getIndexOfChildComponent
  15882. */
  15883. int getNumChildComponents() const throw();
  15884. /** Returns one of this component's child components, by it index.
  15885. The component with index 0 is at the back of the z-order, the one at the
  15886. front will have index (getNumChildComponents() - 1).
  15887. If the index is out-of-range, this will return a null pointer.
  15888. @see getNumChildComponents, getIndexOfChildComponent
  15889. */
  15890. Component* getChildComponent (const int index) const throw();
  15891. /** Returns the index of this component in the list of child components.
  15892. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  15893. values are further towards the front.
  15894. Returns -1 if the component passed-in is not a child of this component.
  15895. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  15896. */
  15897. int getIndexOfChildComponent (const Component* const child) const throw();
  15898. /** Adds a child component to this one.
  15899. @param child the new component to add. If the component passed-in is already
  15900. the child of another component, it'll first be removed from that.
  15901. @param zOrder The index in the child-list at which this component should be inserted.
  15902. A value of -1 will insert it in front of the others, 0 is the back.
  15903. @see removeChildComponent, addAndMakeVisible, getChild,
  15904. ComponentListener::componentChildrenChanged
  15905. */
  15906. void addChildComponent (Component* const child,
  15907. int zOrder = -1);
  15908. /** Adds a child component to this one, and also makes the child visible if it isn't.
  15909. Quite a useful function, this is just the same as calling addChildComponent()
  15910. followed by setVisible (true) on the child.
  15911. */
  15912. void addAndMakeVisible (Component* const child,
  15913. int zOrder = -1);
  15914. /** Removes one of this component's child-components.
  15915. If the child passed-in isn't actually a child of this component (either because
  15916. it's invalid or is the child of a different parent), then nothing is done.
  15917. Note that removing a child will not delete it!
  15918. @see addChildComponent, ComponentListener::componentChildrenChanged
  15919. */
  15920. void removeChildComponent (Component* const childToRemove);
  15921. /** Removes one of this component's child-components by index.
  15922. This will return a pointer to the component that was removed, or null if
  15923. the index was out-of-range.
  15924. Note that removing a child will not delete it!
  15925. @see addChildComponent, ComponentListener::componentChildrenChanged
  15926. */
  15927. Component* removeChildComponent (const int childIndexToRemove);
  15928. /** Removes all this component's children.
  15929. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  15930. */
  15931. void removeAllChildren();
  15932. /** Removes all this component's children, and deletes them.
  15933. @see removeAllChildren
  15934. */
  15935. void deleteAllChildren();
  15936. /** Returns the component which this component is inside.
  15937. If this is the highest-level component or hasn't yet been added to
  15938. a parent, this will return null.
  15939. */
  15940. Component* getParentComponent() const throw() { return parentComponent_; }
  15941. /** Searches the parent components for a component of a specified class.
  15942. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  15943. component that can be dynamically cast to a MyComp, or will return 0 if none
  15944. of the parents are suitable.
  15945. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  15946. */
  15947. template <class TargetClass>
  15948. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  15949. {
  15950. (void) dummyParameter;
  15951. Component* p = parentComponent_;
  15952. while (p != 0)
  15953. {
  15954. TargetClass* target = dynamic_cast <TargetClass*> (p);
  15955. if (target != 0)
  15956. return target;
  15957. p = p->parentComponent_;
  15958. }
  15959. return 0;
  15960. }
  15961. /** Returns the highest-level component which contains this one or its parents.
  15962. This will search upwards in the parent-hierarchy from this component, until it
  15963. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  15964. not yet added to a parent), and will return that.
  15965. */
  15966. Component* getTopLevelComponent() const throw();
  15967. /** Checks whether a component is anywhere inside this component or its children.
  15968. This will recursively check through this components children to see if the
  15969. given component is anywhere inside.
  15970. */
  15971. bool isParentOf (const Component* possibleChild) const throw();
  15972. /** Called to indicate that the component's parents have changed.
  15973. When a component is added or removed from its parent, this method will
  15974. be called on all of its children (recursively - so all children of its
  15975. children will also be called as well).
  15976. Subclasses can override this if they need to react to this in some way.
  15977. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  15978. */
  15979. virtual void parentHierarchyChanged();
  15980. /** Subclasses can use this callback to be told when children are added or removed.
  15981. @see parentHierarchyChanged
  15982. */
  15983. virtual void childrenChanged();
  15984. /** Tests whether a given point inside the component.
  15985. Overriding this method allows you to create components which only intercept
  15986. mouse-clicks within a user-defined area.
  15987. This is called to find out whether a particular x, y co-ordinate is
  15988. considered to be inside the component or not, and is used by methods such
  15989. as contains() and getComponentAt() to work out which component
  15990. the mouse is clicked on.
  15991. Components with custom shapes will probably want to override it to perform
  15992. some more complex hit-testing.
  15993. The default implementation of this method returns either true or false,
  15994. depending on the value that was set by calling setInterceptsMouseClicks() (true
  15995. is the default return value).
  15996. Note that the hit-test region is not related to the opacity with which
  15997. areas of a component are painted.
  15998. Applications should never call hitTest() directly - instead use the
  15999. contains() method, because this will also test for occlusion by the
  16000. component's parent.
  16001. Note that for components on the desktop, this method will be ignored, because it's
  16002. not always possible to implement this behaviour on all platforms.
  16003. @param x the x co-ordinate to test, relative to the left hand edge of this
  16004. component. This value is guaranteed to be greater than or equal to
  16005. zero, and less than the component's width
  16006. @param y the y co-ordinate to test, relative to the top edge of this
  16007. component. This value is guaranteed to be greater than or equal to
  16008. zero, and less than the component's height
  16009. @returns true if the click is considered to be inside the component
  16010. @see setInterceptsMouseClicks, contains
  16011. */
  16012. virtual bool hitTest (int x, int y);
  16013. /** Changes the default return value for the hitTest() method.
  16014. Setting this to false is an easy way to make a component pass its mouse-clicks
  16015. through to the components behind it.
  16016. When a component is created, the default setting for this is true.
  16017. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  16018. return false (or true for child components if allowClicksOnChildComponents
  16019. is true)
  16020. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  16021. components can be clicked on as normal but clicks on this component pass
  16022. straight through; if this is false and allowClicksOnThisComponent
  16023. is false, then neither this component nor any child components can
  16024. be clicked on
  16025. @see hitTest, getInterceptsMouseClicks
  16026. */
  16027. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  16028. const bool allowClicksOnChildComponents) throw();
  16029. /** Retrieves the current state of the mouse-click interception flags.
  16030. On return, the two parameters are set to the state used in the last call to
  16031. setInterceptsMouseClicks().
  16032. @see setInterceptsMouseClicks
  16033. */
  16034. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  16035. bool& allowsClicksOnChildComponents) const throw();
  16036. /** Returns true if a given point lies within this component or one of its children.
  16037. Never override this method! Use hitTest to create custom hit regions.
  16038. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16039. @param y the y co-ordinate to test, relative to this component's top edge.
  16040. @returns true if the point is within the component's hit-test area, but only if
  16041. that part of the component isn't clipped by its parent component. Note
  16042. that this won't take into account any overlapping sibling components
  16043. which might be in the way - for that, see reallyContains()
  16044. @see hitTest, reallyContains, getComponentAt
  16045. */
  16046. virtual bool contains (int x, int y);
  16047. /** Returns true if a given point lies in this component, taking any overlapping
  16048. siblings into account.
  16049. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16050. @param y the y co-ordinate to test, relative to this component's top edge.
  16051. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  16052. component, this determines the value that will
  16053. be returned.
  16054. @see contains, getComponentAt
  16055. */
  16056. bool reallyContains (int x, int y,
  16057. const bool returnTrueIfWithinAChild);
  16058. /** Returns the component at a certain point within this one.
  16059. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16060. @param y the y co-ordinate to test, relative to this component's top edge.
  16061. @returns the component that is at this position - which may be 0, this component,
  16062. or one of its children. Note that overlapping siblings that might actually
  16063. be in the way are not taken into account by this method - to account for these,
  16064. instead call getComponentAt on the top-level parent of this component.
  16065. @see hitTest, contains, reallyContains
  16066. */
  16067. Component* getComponentAt (const int x, const int y);
  16068. /** Marks the whole component as needing to be redrawn.
  16069. Calling this will not do any repainting immediately, but will mark the component
  16070. as 'dirty'. At some point in the near future the operating system will send a paint
  16071. message, which will redraw all the dirty regions of all components.
  16072. There's no guarantee about how soon after calling repaint() the redraw will actually
  16073. happen, and other queued events may be delivered before a redraw is done.
  16074. If the setBufferedToImage() method has been used to cause this component
  16075. to use a buffer, the repaint() call will invalidate the component's buffer.
  16076. To redraw just a subsection of the component rather than the whole thing,
  16077. use the repaint (int, int, int, int) method.
  16078. @see paint
  16079. */
  16080. void repaint() throw();
  16081. /** Marks a subsection of this component as needing to be redrawn.
  16082. Calling this will not do any repainting immediately, but will mark the given region
  16083. of the component as 'dirty'. At some point in the near future the operating system
  16084. will send a paint message, which will redraw all the dirty regions of all components.
  16085. There's no guarantee about how soon after calling repaint() the redraw will actually
  16086. happen, and other queued events may be delivered before a redraw is done.
  16087. The region that is passed in will be clipped to keep it within the bounds of this
  16088. component.
  16089. @see repaint()
  16090. */
  16091. void repaint (const int x, const int y,
  16092. const int width, const int height) throw();
  16093. /** Makes the component use an internal buffer to optimise its redrawing.
  16094. Setting this flag to true will cause the component to allocate an
  16095. internal buffer into which it paints itself, so that when asked to
  16096. redraw itself, it can use this buffer rather than actually calling the
  16097. paint() method.
  16098. The buffer is kept until the repaint() method is called directly on
  16099. this component (or until it is resized), when the image is invalidated
  16100. and then redrawn the next time the component is painted.
  16101. Note that only the drawing that happens within the component's paint()
  16102. method is drawn into the buffer, it's child components are not buffered, and
  16103. nor is the paintOverChildren() method.
  16104. @see repaint, paint, createComponentSnapshot
  16105. */
  16106. void setBufferedToImage (const bool shouldBeBuffered) throw();
  16107. /** Generates a snapshot of part of this component.
  16108. This will return a new Image, the size of the rectangle specified,
  16109. containing a snapshot of the specified area of the component and all
  16110. its children.
  16111. The image may or may not have an alpha-channel, depending on whether the
  16112. image is opaque or not.
  16113. If the clipImageToComponentBounds parameter is true and the area is greater than
  16114. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16115. then parts of the component beyond its bounds can be drawn.
  16116. The caller is responsible for deleting the image that is returned.
  16117. @see paintEntireComponent
  16118. */
  16119. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16120. const bool clipImageToComponentBounds = true);
  16121. /** Draws this component and all its subcomponents onto the specified graphics
  16122. context.
  16123. You should very rarely have to use this method, it's simply there in case you need
  16124. to draw a component with a custom graphics context for some reason, e.g. for
  16125. creating a snapshot of the component.
  16126. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16127. on its children in order to render the entire tree.
  16128. The graphics context may be left in an undefined state after this method returns,
  16129. so you may need to reset it if you're going to use it again.
  16130. */
  16131. void paintEntireComponent (Graphics& context);
  16132. /** Adds an effect filter to alter the component's appearance.
  16133. When a component has an effect filter set, then this is applied to the
  16134. results of its paint() method. There are a few preset effects, such as
  16135. a drop-shadow or glow, but they can be user-defined as well.
  16136. The effect that is passed in will not be deleted by the component - the
  16137. caller must take care of deleting it.
  16138. To remove an effect from a component, pass a null pointer in as the parameter.
  16139. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16140. */
  16141. void setComponentEffect (ImageEffectFilter* const newEffect);
  16142. /** Returns the current component effect.
  16143. @see setComponentEffect
  16144. */
  16145. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16146. /** Finds the appropriate look-and-feel to use for this component.
  16147. If the component hasn't had a look-and-feel explicitly set, this will
  16148. return the parent's look-and-feel, or just the default one if there's no
  16149. parent.
  16150. @see setLookAndFeel, lookAndFeelChanged
  16151. */
  16152. LookAndFeel& getLookAndFeel() const throw();
  16153. /** Sets the look and feel to use for this component.
  16154. This will also change the look and feel for any child components that haven't
  16155. had their look set explicitly.
  16156. The object passed in will not be deleted by the component, so it's the caller's
  16157. responsibility to manage it. It may be used at any time until this component
  16158. has been deleted.
  16159. Calling this method will also invoke the sendLookAndFeelChange() method.
  16160. @see getLookAndFeel, lookAndFeelChanged
  16161. */
  16162. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16163. /** Called to let the component react to a change in the look-and-feel setting.
  16164. When the look-and-feel is changed for a component, this will be called in
  16165. all its child components, recursively.
  16166. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16167. an application uses a LookAndFeel class that might have changed internally.
  16168. @see sendLookAndFeelChange, getLookAndFeel
  16169. */
  16170. virtual void lookAndFeelChanged();
  16171. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16172. This will recurse through the children and their children, calling lookAndFeelChanged()
  16173. on them all.
  16174. @see lookAndFeelChanged
  16175. */
  16176. void sendLookAndFeelChange();
  16177. /** Indicates whether any parts of the component might be transparent.
  16178. Components that always paint all of their contents with solid colour and
  16179. thus completely cover any components behind them should use this method
  16180. to tell the repaint system that they are opaque.
  16181. This information is used to optimise drawing, because it means that
  16182. objects underneath opaque windows don't need to be painted.
  16183. By default, components are considered transparent, unless this is used to
  16184. make it otherwise.
  16185. @see isOpaque, getVisibleArea
  16186. */
  16187. void setOpaque (const bool shouldBeOpaque) throw();
  16188. /** Returns true if no parts of this component are transparent.
  16189. @returns the value that was set by setOpaque, (the default being false)
  16190. @see setOpaque
  16191. */
  16192. bool isOpaque() const throw();
  16193. /** Indicates whether the component should be brought to the front when clicked.
  16194. Setting this flag to true will cause the component to be brought to the front
  16195. when the mouse is clicked somewhere inside it or its child components.
  16196. Note that a top-level desktop window might still be brought to the front by the
  16197. operating system when it's clicked, depending on how the OS works.
  16198. By default this is set to false.
  16199. @see setMouseClickGrabsKeyboardFocus
  16200. */
  16201. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16202. /** Indicates whether the component should be brought to the front when clicked-on.
  16203. @see setBroughtToFrontOnMouseClick
  16204. */
  16205. bool isBroughtToFrontOnMouseClick() const throw();
  16206. // Keyboard focus methods
  16207. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16208. By default components aren't actually interested in gaining the
  16209. focus, but this method can be used to turn this on.
  16210. See the grabKeyboardFocus() method for details about the way a component
  16211. is chosen to receive the focus.
  16212. @see grabKeyboardFocus, getWantsKeyboardFocus
  16213. */
  16214. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16215. /** Returns true if the component is interested in getting keyboard focus.
  16216. This returns the flag set by setWantsKeyboardFocus(). The default
  16217. setting is false.
  16218. @see setWantsKeyboardFocus
  16219. */
  16220. bool getWantsKeyboardFocus() const throw();
  16221. /** Chooses whether a click on this component automatically grabs the focus.
  16222. By default this is set to true, but you might want a component which can
  16223. be focused, but where you don't want the user to be able to affect it directly
  16224. by clicking.
  16225. */
  16226. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16227. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16228. See setMouseClickGrabsKeyboardFocus() for more info.
  16229. */
  16230. bool getMouseClickGrabsKeyboardFocus() const throw();
  16231. /** Tries to give keyboard focus to this component.
  16232. When the user clicks on a component or its grabKeyboardFocus()
  16233. method is called, the following procedure is used to work out which
  16234. component should get it:
  16235. - if the component that was clicked on actually wants focus (as indicated
  16236. by calling getWantsKeyboardFocus), it gets it.
  16237. - if the component itself doesn't want focus, it will try to pass it
  16238. on to whichever of its children is the default component, as determined by
  16239. KeyboardFocusTraverser::getDefaultComponent()
  16240. - if none of its children want focus at all, it will pass it up to its
  16241. parent instead, unless it's a top-level component without a parent,
  16242. in which case it just takes the focus itself.
  16243. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16244. getCurrentlyFocusedComponent, focusGained, focusLost,
  16245. keyPressed, keyStateChanged
  16246. */
  16247. void grabKeyboardFocus();
  16248. /** Returns true if this component currently has the keyboard focus.
  16249. @param trueIfChildIsFocused if this is true, then the method returns true if
  16250. either this component or any of its children (recursively)
  16251. have the focus. If false, the method only returns true if
  16252. this component has the focus.
  16253. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16254. focusGained, focusLost
  16255. */
  16256. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16257. /** Returns the component that currently has the keyboard focus.
  16258. @returns the focused component, or null if nothing is focused.
  16259. */
  16260. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16261. /** Tries to move the keyboard focus to one of this component's siblings.
  16262. This will try to move focus to either the next or previous component. (This
  16263. is the method that is used when shifting focus by pressing the tab key).
  16264. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16265. @param moveToNext if true, the focus will move forwards; if false, it will
  16266. move backwards
  16267. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16268. */
  16269. void moveKeyboardFocusToSibling (const bool moveToNext);
  16270. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16271. which focus should be passed from this component.
  16272. The default implementation of this method will return a default
  16273. KeyboardFocusTraverser if this component is a focus container (as determined
  16274. by the setFocusContainer() method). If the component isn't a focus
  16275. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16276. If you overrride this to return a custom KeyboardFocusTraverser, then
  16277. this component and all its sub-components will use the new object to
  16278. make their focusing decisions.
  16279. The method should return a new object, which the caller is required to
  16280. delete when no longer needed.
  16281. */
  16282. virtual KeyboardFocusTraverser* createFocusTraverser();
  16283. /** Returns the focus order of this component, if one has been specified.
  16284. By default components don't have a focus order - in that case, this
  16285. will return 0. Lower numbers indicate that the component will be
  16286. earlier in the focus traversal order.
  16287. To change the order, call setExplicitFocusOrder().
  16288. The focus order may be used by the KeyboardFocusTraverser class as part of
  16289. its algorithm for deciding the order in which components should be traversed.
  16290. See the KeyboardFocusTraverser class for more details on this.
  16291. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16292. */
  16293. int getExplicitFocusOrder() const throw();
  16294. /** Sets the index used in determining the order in which focusable components
  16295. should be traversed.
  16296. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16297. that traversal should use other factors, like the component's position.
  16298. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16299. */
  16300. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16301. /** Indicates whether this component is a parent for components that can have
  16302. their focus traversed.
  16303. This flag is used by the default implementation of the createFocusTraverser()
  16304. method, which uses the flag to find the first parent component (of the currently
  16305. focused one) which wants to be a focus container.
  16306. So using this method to set the flag to 'true' causes this component to
  16307. act as the top level within which focus is passed around.
  16308. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  16309. */
  16310. void setFocusContainer (const bool isFocusContainer) throw();
  16311. /** Returns true if this component has been marked as a focus container.
  16312. See setFocusContainer() for more details.
  16313. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  16314. */
  16315. bool isFocusContainer() const throw();
  16316. /** Returns true if the component (and all its parents) are enabled.
  16317. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  16318. what difference this makes to the component depends on the type. E.g. buttons
  16319. and sliders will choose to draw themselves differently, etc.
  16320. Note that if one of this component's parents is disabled, this will always
  16321. return false, even if this component itself is enabled.
  16322. @see setEnabled, enablementChanged
  16323. */
  16324. bool isEnabled() const throw();
  16325. /** Enables or disables this component.
  16326. Disabling a component will also cause all of its child components to become
  16327. disabled.
  16328. Similarly, enabling a component which is inside a disabled parent
  16329. component won't make any difference until the parent is re-enabled.
  16330. @see isEnabled, enablementChanged
  16331. */
  16332. void setEnabled (const bool shouldBeEnabled);
  16333. /** Callback to indicate that this component has been enabled or disabled.
  16334. This can be triggered by one of the component's parent components
  16335. being enabled or disabled, as well as changes to the component itself.
  16336. The default implementation of this method does nothing; your class may
  16337. wish to repaint itself or something when this happens.
  16338. @see setEnabled, isEnabled
  16339. */
  16340. virtual void enablementChanged();
  16341. /** Changes the mouse cursor shape to use when the mouse is over this component.
  16342. Note that the cursor set by this method can be overridden by the getMouseCursor
  16343. method.
  16344. @see MouseCursor
  16345. */
  16346. void setMouseCursor (const MouseCursor& cursorType) throw();
  16347. /** Returns the mouse cursor shape to use when the mouse is over this component.
  16348. The default implementation will return the cursor that was set by setCursor()
  16349. but can be overridden for more specialised purposes, e.g. returning different
  16350. cursors depending on the mouse position.
  16351. @see MouseCursor
  16352. */
  16353. virtual const MouseCursor getMouseCursor();
  16354. /** Forces the current mouse cursor to be updated.
  16355. If you're overriding the getMouseCursor() method to control which cursor is
  16356. displayed, then this will only be checked each time the user moves the mouse. So
  16357. if you want to force the system to check that the cursor being displayed is
  16358. up-to-date (even if the mouse is just sitting there), call this method.
  16359. This isn't needed if you're only using setMouseCursor().
  16360. */
  16361. void updateMouseCursor() const throw();
  16362. /** Components can override this method to draw their content.
  16363. The paint() method gets called when a region of a component needs redrawing,
  16364. either because the component's repaint() method has been called, or because
  16365. something has happened on the screen that means a section of a window needs
  16366. to be redrawn.
  16367. Any child components will draw themselves over whatever this method draws. If
  16368. you need to paint over the top of your child components, you can also implement
  16369. the paintOverChildren() method to do this.
  16370. If you want to cause a component to redraw itself, this is done asynchronously -
  16371. calling the repaint() method marks a region of the component as "dirty", and the
  16372. paint() method will automatically be called sometime later, by the message thread,
  16373. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  16374. you never redraw something synchronously.
  16375. You should never need to call this method directly - to take a snapshot of the
  16376. component you could use createComponentSnapshot() or paintEntireComponent().
  16377. @param g the graphics context that must be used to do the drawing operations.
  16378. @see repaint, paintOverChildren, Graphics
  16379. */
  16380. virtual void paint (Graphics& g);
  16381. /** Components can override this method to draw over the top of their children.
  16382. For most drawing operations, it's better to use the normal paint() method,
  16383. but if you need to overlay something on top of the children, this can be
  16384. used.
  16385. @see paint, Graphics
  16386. */
  16387. virtual void paintOverChildren (Graphics& g);
  16388. /** Called when the mouse moves inside this component.
  16389. If the mouse button isn't pressed and the mouse moves over a component,
  16390. this will be called to let the component react to this.
  16391. A component will always get a mouseEnter callback before a mouseMove.
  16392. @param e details about the position and status of the mouse event
  16393. @see mouseEnter, mouseExit, mouseDrag, contains
  16394. */
  16395. virtual void mouseMove (const MouseEvent& e);
  16396. /** Called when the mouse first enters this component.
  16397. If the mouse button isn't pressed and the mouse moves into a component,
  16398. this will be called to let the component react to this.
  16399. When the mouse button is pressed and held down while being moved in
  16400. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  16401. mouseDrag messages are sent to the component that the mouse was originally
  16402. clicked on, until the button is released.
  16403. If you're writing a component that needs to repaint itself when the mouse
  16404. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16405. method.
  16406. @param e details about the position and status of the mouse event
  16407. @see mouseExit, mouseDrag, mouseMove, contains
  16408. */
  16409. virtual void mouseEnter (const MouseEvent& e);
  16410. /** Called when the mouse moves out of this component.
  16411. This will be called when the mouse moves off the edge of this
  16412. component.
  16413. If the mouse button was pressed, and it was then dragged off the
  16414. edge of the component and released, then this callback will happen
  16415. when the button is released, after the mouseUp callback.
  16416. If you're writing a component that needs to repaint itself when the mouse
  16417. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16418. method.
  16419. @param e details about the position and status of the mouse event
  16420. @see mouseEnter, mouseDrag, mouseMove, contains
  16421. */
  16422. virtual void mouseExit (const MouseEvent& e);
  16423. /** Called when a mouse button is pressed while it's over this component.
  16424. The MouseEvent object passed in contains lots of methods for finding out
  16425. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16426. were held down at the time.
  16427. Once a button is held down, the mouseDrag method will be called when the
  16428. mouse moves, until the button is released.
  16429. @param e details about the position and status of the mouse event
  16430. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  16431. */
  16432. virtual void mouseDown (const MouseEvent& e);
  16433. /** Called when the mouse is moved while a button is held down.
  16434. When a mouse button is pressed inside a component, that component
  16435. receives mouseDrag callbacks each time the mouse moves, even if the
  16436. mouse strays outside the component's bounds.
  16437. If you want to be able to drag things off the edge of a component
  16438. and have the component scroll when you get to the edges, the
  16439. beginDragAutoRepeat() method might be useful.
  16440. @param e details about the position and status of the mouse event
  16441. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  16442. */
  16443. virtual void mouseDrag (const MouseEvent& e);
  16444. /** Called when a mouse button is released.
  16445. A mouseUp callback is sent to the component in which a button was pressed
  16446. even if the mouse is actually over a different component when the
  16447. button is released.
  16448. The MouseEvent object passed in contains lots of methods for finding out
  16449. which buttons were down just before they were released.
  16450. @param e details about the position and status of the mouse event
  16451. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  16452. */
  16453. virtual void mouseUp (const MouseEvent& e);
  16454. /** Called when a mouse button has been double-clicked in this component.
  16455. The MouseEvent object passed in contains lots of methods for finding out
  16456. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16457. were held down at the time.
  16458. For altering the time limit used to detect double-clicks,
  16459. see MouseEvent::setDoubleClickTimeout.
  16460. @param e details about the position and status of the mouse event
  16461. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  16462. MouseEvent::getDoubleClickTimeout
  16463. */
  16464. virtual void mouseDoubleClick (const MouseEvent& e);
  16465. /** Called when the mouse-wheel is moved.
  16466. This callback is sent to the component that the mouse is over when the
  16467. wheel is moved.
  16468. If not overridden, the component will forward this message to its parent, so
  16469. that parent components can collect mouse-wheel messages that happen to
  16470. child components which aren't interested in them.
  16471. @param e details about the position and status of the mouse event
  16472. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  16473. value means the wheel has been pushed to the right, negative means it
  16474. was pushed to the left
  16475. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  16476. value means the wheel has been pushed upwards, negative means it
  16477. was pushed downwards
  16478. */
  16479. virtual void mouseWheelMove (const MouseEvent& e,
  16480. float wheelIncrementX,
  16481. float wheelIncrementY);
  16482. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  16483. next mouse-drag operation.
  16484. This allows you to make sure that mouseDrag() events sent continuously, even
  16485. when the mouse isn't moving. This can be useful for things like auto-scrolling
  16486. components when the mouse is near an edge.
  16487. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  16488. minimum interval between consecutive mouse drag callbacks. The callbacks
  16489. will continue until the mouse is released, and then the interval will be reset,
  16490. so you need to make sure it's called every time you begin a drag event. If it
  16491. is called when the mouse isn't actually being pressed, it will apply to the next
  16492. mouse-drag operation that happens.
  16493. Passing an interval of 0 or less will cancel the auto-repeat.
  16494. @see mouseDrag
  16495. */
  16496. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  16497. /** Causes automatic repaints when the mouse enters or exits this component.
  16498. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  16499. on the component, it will trigger a repaint.
  16500. This is handy for things like buttons that need to draw themselves differently when
  16501. the mouse moves over them, and it avoids having to override all the different mouse
  16502. callbacks and call repaint().
  16503. @see mouseEnter, mouseExit, mouseDown, mouseUp
  16504. */
  16505. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  16506. /** Registers a listener to be told when mouse events occur in this component.
  16507. If you need to get informed about mouse events in a component but can't or
  16508. don't want to override its methods, you can attach any number of listeners
  16509. to the component, and these will get told about the events in addition to
  16510. the component's own callbacks being called.
  16511. Note that a MouseListener can also be attached to more than one component.
  16512. @param newListener the listener to register
  16513. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  16514. for events that happen to any child component
  16515. within this component, including deeply-nested
  16516. child components. If false, it will only be
  16517. told about events that this component handles.
  16518. @see MouseListener, removeMouseListener
  16519. */
  16520. void addMouseListener (MouseListener* const newListener,
  16521. const bool wantsEventsForAllNestedChildComponents) throw();
  16522. /** Deregisters a mouse listener.
  16523. @see addMouseListener, MouseListener
  16524. */
  16525. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  16526. /** Adds a listener that wants to hear about keypresses that this component receives.
  16527. The listeners that are registered with a component are called by its keyPressed() or
  16528. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  16529. If you add an object as a key listener, be careful to remove it when the object
  16530. is deleted, or the component will be left with a dangling pointer.
  16531. @see keyPressed, keyStateChanged, removeKeyListener
  16532. */
  16533. void addKeyListener (KeyListener* const newListener) throw();
  16534. /** Removes a previously-registered key listener.
  16535. @see addKeyListener
  16536. */
  16537. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  16538. /** Called when a key is pressed.
  16539. When a key is pressed, the component that has the keyboard focus will have this
  16540. method called. Remember that a component will only be given the focus if its
  16541. setWantsKeyboardFocus() method has been used to enable this.
  16542. If your implementation returns true, the event will be consumed and not passed
  16543. on to any other listeners. If it returns false, the key will be passed to any
  16544. KeyListeners that have been registered with this component. As soon as one of these
  16545. returns true, the process will stop, but if they all return false, the event will
  16546. be passed upwards to this component's parent, and so on.
  16547. The default implementation of this method does nothing and returns false.
  16548. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  16549. */
  16550. virtual bool keyPressed (const KeyPress& key);
  16551. /** Called when a key is pressed or released.
  16552. Whenever a key on the keyboard is pressed or released (including modifier keys
  16553. like shift and ctrl), this method will be called on the component that currently
  16554. has the keyboard focus. Remember that a component will only be given the focus if
  16555. its setWantsKeyboardFocus() method has been used to enable this.
  16556. If your implementation returns true, the event will be consumed and not passed
  16557. on to any other listeners. If it returns false, then any KeyListeners that have
  16558. been registered with this component will have their keyStateChanged methods called.
  16559. As soon as one of these returns true, the process will stop, but if they all return
  16560. false, the event will be passed upwards to this component's parent, and so on.
  16561. The default implementation of this method does nothing and returns false.
  16562. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  16563. method.
  16564. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  16565. */
  16566. virtual bool keyStateChanged();
  16567. /** Called when a modifier key is pressed or released.
  16568. Whenever the shift, control, alt or command keys are pressed or released,
  16569. this method will be called on the component that currently has the keyboard focus.
  16570. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  16571. method has been used to enable this.
  16572. The default implementation of this method actually calls its parent's modifierKeysChanged
  16573. method, so that focused components which aren't interested in this will give their
  16574. parents a chance to act on the event instead.
  16575. @see keyStateChanged, ModifierKeys
  16576. */
  16577. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  16578. /** Enumeration used by the focusChanged() and focusLost() methods. */
  16579. enum FocusChangeType
  16580. {
  16581. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  16582. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  16583. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  16584. };
  16585. /** Called to indicate that this component has just acquired the keyboard focus.
  16586. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16587. */
  16588. virtual void focusGained (FocusChangeType cause);
  16589. /** Called to indicate that this component has just lost the keyboard focus.
  16590. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16591. */
  16592. virtual void focusLost (FocusChangeType cause);
  16593. /** Called to indicate that one of this component's children has been focused or unfocused.
  16594. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  16595. changed. It happens when focus moves from one of this component's children (at any depth)
  16596. to a component that isn't contained in this one, (or vice-versa).
  16597. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16598. */
  16599. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  16600. /** Returns true if the mouse is currently over this component.
  16601. If the mouse isn't over the component, this will return false, even if the
  16602. mouse is currently being dragged - so you can use this in your mouseDrag
  16603. method to find out whether it's really over the component or not.
  16604. Note that when the mouse button is being held down, then the only component
  16605. for which this method will return true is the one that was originally
  16606. clicked on.
  16607. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  16608. */
  16609. bool isMouseOver() const throw();
  16610. /** Returns true if the mouse button is currently held down in this component.
  16611. Note that this is a test to see whether the mouse is being pressed in this
  16612. component, so it'll return false if called on component A when the mouse
  16613. is actually being dragged in component B.
  16614. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  16615. */
  16616. bool isMouseButtonDown() const throw();
  16617. /** True if the mouse is over this component, or if it's being dragged in this component.
  16618. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  16619. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  16620. */
  16621. bool isMouseOverOrDragging() const throw();
  16622. /** Returns true if a mouse button is currently down.
  16623. Unlike isMouseButtonDown, this will test the current state of the
  16624. buttons without regard to which component (if any) it has been
  16625. pressed in.
  16626. @see isMouseButtonDown, ModifierKeys
  16627. */
  16628. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  16629. /** Returns the mouse's current position, relative to this component.
  16630. The co-ordinates are relative to the component's top-left corner.
  16631. */
  16632. void getMouseXYRelative (int& x, int& y) const throw();
  16633. /** Returns the component that's currently underneath the mouse.
  16634. @returns the component or 0 if there isn't one.
  16635. @see contains, getComponentAt
  16636. */
  16637. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  16638. /** Allows the mouse to move beyond the edges of the screen.
  16639. Calling this method when the mouse button is currently pressed inside this component
  16640. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  16641. the edges of the screen.
  16642. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  16643. can be used for things like custom slider controls or dragging objects around, where
  16644. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  16645. The unbounded mode is automatically turned off when the mouse button is released, or
  16646. it can be turned off explicitly by calling this method again.
  16647. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  16648. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  16649. hidden; if true, it will only be hidden when it
  16650. is moved beyond the edge of the screen
  16651. */
  16652. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  16653. bool keepCursorVisibleUntilOffscreen = false) throw();
  16654. /** Called when this component's size has been changed.
  16655. A component can implement this method to do things such as laying out its
  16656. child components when its width or height changes.
  16657. The method is called synchronously as a result of the setBounds or setSize
  16658. methods, so repeatedly changing a components size will repeatedly call its
  16659. resized method (unlike things like repainting, where multiple calls to repaint
  16660. are coalesced together).
  16661. If the component is a top-level window on the desktop, its size could also
  16662. be changed by operating-system factors beyond the application's control.
  16663. @see moved, setSize
  16664. */
  16665. virtual void resized();
  16666. /** Called when this component's position has been changed.
  16667. This is called when the position relative to its parent changes, not when
  16668. its absolute position on the screen changes (so it won't be called for
  16669. all child components when a parent component is moved).
  16670. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  16671. or any of the other repositioning methods, and like resized(), it will be
  16672. called each time those methods are called.
  16673. If the component is a top-level window on the desktop, its position could also
  16674. be changed by operating-system factors beyond the application's control.
  16675. @see resized, setBounds
  16676. */
  16677. virtual void moved();
  16678. /** Called when one of this component's children is moved or resized.
  16679. If the parent wants to know about changes to its immediate children (not
  16680. to children of its children), this is the method to override.
  16681. @see moved, resized, parentSizeChanged
  16682. */
  16683. virtual void childBoundsChanged (Component* child);
  16684. /** Called when this component's immediate parent has been resized.
  16685. If the component is a top-level window, this indicates that the screen size
  16686. has changed.
  16687. @see childBoundsChanged, moved, resized
  16688. */
  16689. virtual void parentSizeChanged();
  16690. /** Called when this component has been moved to the front of its siblings.
  16691. The component may have been brought to the front by the toFront() method, or
  16692. by the operating system if it's a top-level window.
  16693. @see toFront
  16694. */
  16695. virtual void broughtToFront();
  16696. /** Adds a listener to be told about changes to the component hierarchy or position.
  16697. Component listeners get called when this component's size, position or children
  16698. change - see the ComponentListener class for more details.
  16699. @param newListener the listener to register - if this is already registered, it
  16700. will be ignored.
  16701. @see ComponentListener, removeComponentListener
  16702. */
  16703. void addComponentListener (ComponentListener* const newListener) throw();
  16704. /** Removes a component listener.
  16705. @see addComponentListener
  16706. */
  16707. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  16708. /** Dispatches a numbered message to this component.
  16709. This is a quick and cheap way of allowing simple asynchronous messages to
  16710. be sent to components. It's also safe, because if the component that you
  16711. send the message to is a null or dangling pointer, this won't cause an error.
  16712. The command ID is later delivered to the component's handleCommandMessage() method by
  16713. the application's message queue.
  16714. @see handleCommandMessage
  16715. */
  16716. void postCommandMessage (const int commandId) throw();
  16717. /** Called to handle a command that was sent by postCommandMessage().
  16718. This is called by the message thread when a command message arrives, and
  16719. the component can override this method to process it in any way it needs to.
  16720. @see postCommandMessage
  16721. */
  16722. virtual void handleCommandMessage (int commandId);
  16723. /** Runs a component modally, waiting until the loop terminates.
  16724. This method first makes the component visible, brings it to the front and
  16725. gives it the keyboard focus.
  16726. It then runs a loop, dispatching messages from the system message queue, but
  16727. blocking all mouse or keyboard messages from reaching any components other
  16728. than this one and its children.
  16729. This loop continues until the component's exitModalState() method is called (or
  16730. the component is deleted), and then this method returns, returning the value
  16731. passed into exitModalState().
  16732. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  16733. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  16734. */
  16735. int runModalLoop();
  16736. /** Puts the component into a modal state.
  16737. This makes the component modal, so that messages are blocked from reaching
  16738. any components other than this one and its children, but unlike runModalLoop(),
  16739. this method returns immediately.
  16740. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  16741. get the focus, which is usually what you'll want it to do. If not, it will leave
  16742. the focus unchanged.
  16743. @see exitModalState, runModalLoop
  16744. */
  16745. void enterModalState (const bool takeKeyboardFocus = true);
  16746. /** Ends a component's modal state.
  16747. If this component is currently modal, this will turn of its modalness, and return
  16748. a value to the runModalLoop() method that might have be running its modal loop.
  16749. @see runModalLoop, enterModalState, isCurrentlyModal
  16750. */
  16751. void exitModalState (const int returnValue);
  16752. /** Returns true if this component is the modal one.
  16753. It's possible to have nested modal components, e.g. a pop-up dialog box
  16754. that launches another pop-up, but this will only return true for
  16755. the one at the top of the stack.
  16756. @see getCurrentlyModalComponent
  16757. */
  16758. bool isCurrentlyModal() const throw();
  16759. /** Returns the component that is currently modal.
  16760. @returns the modal component, or null if no components are modal
  16761. @see runModalLoop, isCurrentlyModal
  16762. */
  16763. static Component* JUCE_CALLTYPE getCurrentlyModalComponent() throw();
  16764. /** Checks whether there's a modal component somewhere that's stopping this one
  16765. from receiving messages.
  16766. If there is a modal component, its canModalEventBeSentToComponent() method
  16767. will be called to see if it will still allow this component to receive events.
  16768. @see runModalLoop, getCurrentlyModalComponent
  16769. */
  16770. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  16771. /** When a component is modal, this callback allows it to choose which other
  16772. components can still receive events.
  16773. When a modal component is active and the user clicks on a non-modal component,
  16774. this method is called on the modal component, and if it returns true, the
  16775. event is allowed to reach its target. If it returns false, the event is blocked
  16776. and the inputAttemptWhenModal() callback is made.
  16777. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  16778. implementation just returns false in all cases.
  16779. */
  16780. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  16781. /** Called when the user tries to click on a component that is blocked by another
  16782. modal component.
  16783. When a component is modal and the user clicks on one of the other components,
  16784. the modal component will receive this callback.
  16785. The default implementation of this method will play a beep, and bring the currently
  16786. modal component to the front, but it can be overridden to do other tasks.
  16787. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  16788. */
  16789. virtual void inputAttemptWhenModal();
  16790. /** Returns one of the component's properties as a string.
  16791. @param keyName the name of the property to retrieve
  16792. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16793. properties, then it will check whether the parent component has
  16794. the key.
  16795. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16796. */
  16797. const String getComponentProperty (const String& keyName,
  16798. const bool useParentComponentIfNotFound,
  16799. const String& defaultReturnValue = String::empty) const throw();
  16800. /** Returns one of the properties as an integer.
  16801. @param keyName the name of the property to retrieve
  16802. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16803. properties, then it will check whether the parent component has
  16804. the key.
  16805. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16806. */
  16807. int getComponentPropertyInt (const String& keyName,
  16808. const bool useParentComponentIfNotFound,
  16809. const int defaultReturnValue = 0) const throw();
  16810. /** Returns one of the properties as an double.
  16811. @param keyName the name of the property to retrieve
  16812. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16813. properties, then it will check whether the parent component has
  16814. the key.
  16815. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16816. */
  16817. double getComponentPropertyDouble (const String& keyName,
  16818. const bool useParentComponentIfNotFound,
  16819. const double defaultReturnValue = 0.0) const throw();
  16820. /** Returns one of the properties as an boolean.
  16821. The result will be true if the string found for this key name can be parsed as a non-zero
  16822. integer.
  16823. @param keyName the name of the property to retrieve
  16824. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16825. properties, then it will check whether the parent component has
  16826. the key.
  16827. @param defaultReturnValue a value to return if the named property doesn't actually exist
  16828. */
  16829. bool getComponentPropertyBool (const String& keyName,
  16830. const bool useParentComponentIfNotFound,
  16831. const bool defaultReturnValue = false) const throw();
  16832. /** Returns one of the properties as an colour.
  16833. @param keyName the name of the property to retrieve
  16834. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  16835. properties, then it will check whether the parent component has
  16836. the key.
  16837. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  16838. */
  16839. const Colour getComponentPropertyColour (const String& keyName,
  16840. const bool useParentComponentIfNotFound,
  16841. const Colour& defaultReturnValue = Colours::black) const throw();
  16842. /** Sets a named property as a string.
  16843. @param keyName the name of the property to set. (This mustn't be an empty string)
  16844. @param value the new value to set it to
  16845. @see removeComponentProperty
  16846. */
  16847. void setComponentProperty (const String& keyName, const String& value) throw();
  16848. /** Sets a named property to an integer.
  16849. @param keyName the name of the property to set. (This mustn't be an empty string)
  16850. @param value the new value to set it to
  16851. @see removeComponentProperty
  16852. */
  16853. void setComponentProperty (const String& keyName, const int value) throw();
  16854. /** Sets a named property to a double.
  16855. @param keyName the name of the property to set. (This mustn't be an empty string)
  16856. @param value the new value to set it to
  16857. @see removeComponentProperty
  16858. */
  16859. void setComponentProperty (const String& keyName, const double value) throw();
  16860. /** Sets a named property to a boolean.
  16861. @param keyName the name of the property to set. (This mustn't be an empty string)
  16862. @param value the new value to set it to
  16863. @see removeComponentProperty
  16864. */
  16865. void setComponentProperty (const String& keyName, const bool value) throw();
  16866. /** Sets a named property to a colour.
  16867. @param keyName the name of the property to set. (This mustn't be an empty string)
  16868. @param newColour the new colour to set it to
  16869. @see removeComponentProperty
  16870. */
  16871. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  16872. /** Deletes a named component property.
  16873. @param keyName the name of the property to delete. (This mustn't be an empty string)
  16874. @see setComponentProperty, getComponentProperty
  16875. */
  16876. void removeComponentProperty (const String& keyName) throw();
  16877. /** Returns the complete set of properties that have been set for this component.
  16878. If no properties have been set, this will return a null pointer.
  16879. @see getComponentProperty, setComponentProperty
  16880. */
  16881. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  16882. /** Looks for a colour that has been registered with the given colour ID number.
  16883. If a colour has been set for this ID number using setColour(), then it is
  16884. returned. If none has been set, the method will try calling the component's
  16885. LookAndFeel class's findColour() method. If none has been registered with the
  16886. look-and-feel either, it will just return black.
  16887. The colour IDs for various purposes are stored as enums in the components that
  16888. they are relevent to - for an example, see Slider::ColourIds,
  16889. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  16890. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16891. */
  16892. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  16893. /** Registers a colour to be used for a particular purpose.
  16894. Changing a colour will cause a synchronous callback to the colourChanged()
  16895. method, which your component can override if it needs to do something when
  16896. colours are altered.
  16897. For more details about colour IDs, see the comments for findColour().
  16898. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  16899. */
  16900. void setColour (const int colourId, const Colour& colour);
  16901. /** If a colour has been set with setColour(), this will remove it.
  16902. This allows you to make a colour revert to its default state.
  16903. */
  16904. void removeColour (const int colourId);
  16905. /** Returns true if the specified colour ID has been explicitly set for this
  16906. component using the setColour() method.
  16907. */
  16908. bool isColourSpecified (const int colourId) const throw();
  16909. /** This looks for any colours that have been specified for this component,
  16910. and copies them to the specified target component.
  16911. */
  16912. void copyAllExplicitColoursTo (Component& target) const throw();
  16913. /** This method is called when a colour is changed by the setColour() method.
  16914. @see setColour, findColour
  16915. */
  16916. virtual void colourChanged();
  16917. /** Returns the underlying native window handle for this component.
  16918. This is platform-dependent and strictly for power-users only!
  16919. */
  16920. void* getWindowHandle() const throw();
  16921. /** When created, each component is given a number to uniquely identify it.
  16922. The number is incremented each time a new component is created, so it's a more
  16923. unique way of identifying a component than using its memory location (which
  16924. may be reused after the component is deleted, of course).
  16925. */
  16926. uint32 getComponentUID() const throw() { return componentUID; }
  16927. juce_UseDebuggingNewOperator
  16928. private:
  16929. friend class ComponentPeer;
  16930. friend class InternalDragRepeater;
  16931. static Component* currentlyFocusedComponent;
  16932. static Component* componentUnderMouse;
  16933. String componentName_;
  16934. Component* parentComponent_;
  16935. uint32 componentUID;
  16936. Rectangle bounds_;
  16937. unsigned short numDeepMouseListeners;
  16938. Array <Component*> childComponentList_;
  16939. LookAndFeel* lookAndFeel_;
  16940. MouseCursor cursor_;
  16941. ImageEffectFilter* effect_;
  16942. Image* bufferedImage_;
  16943. VoidArray* mouseListeners_;
  16944. VoidArray* keyListeners_;
  16945. VoidArray* componentListeners_;
  16946. PropertySet* propertySet_;
  16947. struct ComponentFlags
  16948. {
  16949. bool hasHeavyweightPeerFlag : 1;
  16950. bool visibleFlag : 1;
  16951. bool opaqueFlag : 1;
  16952. bool ignoresMouseClicksFlag : 1;
  16953. bool allowChildMouseClicksFlag : 1;
  16954. bool wantsFocusFlag : 1;
  16955. bool isFocusContainerFlag : 1;
  16956. bool dontFocusOnMouseClickFlag : 1;
  16957. bool alwaysOnTopFlag : 1;
  16958. bool bufferToImageFlag : 1;
  16959. bool bringToFrontOnClickFlag : 1;
  16960. bool repaintOnMouseActivityFlag : 1;
  16961. bool draggingFlag : 1;
  16962. bool mouseOverFlag : 1;
  16963. bool mouseInsideFlag : 1;
  16964. bool currentlyModalFlag : 1;
  16965. bool isDisabledFlag : 1;
  16966. bool childCompFocusedFlag : 1;
  16967. #ifdef JUCE_DEBUG
  16968. bool isInsidePaintCall : 1;
  16969. #endif
  16970. };
  16971. union
  16972. {
  16973. uint32 componentFlags_;
  16974. ComponentFlags flags;
  16975. };
  16976. void internalMouseEnter (int x, int y, const int64 time);
  16977. void internalMouseExit (int x, int y, const int64 time);
  16978. void internalMouseDown (int x, int y);
  16979. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  16980. void internalMouseDrag (int x, int y, const int64 time);
  16981. void internalMouseMove (int x, int y, const int64 time);
  16982. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  16983. void internalBroughtToFront();
  16984. void internalFocusGain (const FocusChangeType cause);
  16985. void internalFocusLoss (const FocusChangeType cause);
  16986. void internalChildFocusChange (FocusChangeType cause);
  16987. void internalModalInputAttempt();
  16988. void internalModifierKeysChanged();
  16989. void internalChildrenChanged();
  16990. void internalHierarchyChanged();
  16991. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  16992. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  16993. void repaintParent() throw();
  16994. void sendFakeMouseMove() const;
  16995. void takeKeyboardFocus (const FocusChangeType cause);
  16996. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  16997. static void giveAwayFocus();
  16998. void sendEnablementChangeMessage();
  16999. static void* runModalLoopCallback (void*);
  17000. void subtractObscuredRegions (RectangleList& result,
  17001. const int deltaX, const int deltaY,
  17002. const Rectangle& clipRect,
  17003. const Component* const compToAvoid) const throw();
  17004. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  17005. const int deltaX, const int deltaY) const throw();
  17006. // how much of the component is not off the edges of its parents
  17007. const Rectangle getUnclippedArea() const;
  17008. void sendVisibilityChangeMessage();
  17009. // This is included here just to cause a compile error if your code is still handling
  17010. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  17011. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  17012. // implement its methods instead of this Component method).
  17013. virtual void filesDropped (const StringArray&, int, int) {}
  17014. // components aren't allowed to have copy constructors, as this would mess up parent
  17015. // hierarchies. You might need to give your subclasses a private dummy constructor like
  17016. // this one to avoid compiler warnings.
  17017. Component (const Component&);
  17018. const Component& operator= (const Component&);
  17019. protected:
  17020. /** @internal */
  17021. virtual void internalRepaint (int x, int y, int w, int h);
  17022. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  17023. /** Overridden from the MessageListener parent class.
  17024. You can override this if you really need to, but be sure to pass your unwanted messages up
  17025. to this base class implementation, as the Component class needs to send itself messages
  17026. to work properly.
  17027. */
  17028. void handleMessage (const Message&);
  17029. };
  17030. #endif // __JUCE_COMPONENT_JUCEHEADER__
  17031. /********* End of inlined file: juce_Component.h *********/
  17032. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  17033. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17034. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17035. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  17036. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17037. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17038. /** A type used to hold the unique ID for an application command.
  17039. This is a numeric type, so it can be stored as an integer.
  17040. @see ApplicationCommandInfo, ApplicationCommandManager,
  17041. ApplicationCommandTarget, KeyPressMappingSet
  17042. */
  17043. typedef int CommandID;
  17044. /** A set of general-purpose application command IDs.
  17045. Because these commands are likely to be used in most apps, they're defined
  17046. here to help different apps to use the same numeric values for them.
  17047. Of course you don't have to use these, but some of them are used internally by
  17048. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  17049. @see ApplicationCommandInfo, ApplicationCommandManager,
  17050. ApplicationCommandTarget, KeyPressMappingSet
  17051. */
  17052. namespace StandardApplicationCommandIDs
  17053. {
  17054. /** This command ID should be used to send a "Quit the App" command.
  17055. This command is recognised by the JUCEApplication class, so if it is invoked
  17056. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  17057. object will catch it and call JUCEApplication::systemRequestedQuit().
  17058. */
  17059. static const CommandID quit = 0x1001;
  17060. /** The command ID that should be used to send a "Delete" command. */
  17061. static const CommandID del = 0x1002;
  17062. /** The command ID that should be used to send a "Cut" command. */
  17063. static const CommandID cut = 0x1003;
  17064. /** The command ID that should be used to send a "Copy to clipboard" command. */
  17065. static const CommandID copy = 0x1004;
  17066. /** The command ID that should be used to send a "Paste from clipboard" command. */
  17067. static const CommandID paste = 0x1005;
  17068. /** The command ID that should be used to send a "Select all" command. */
  17069. static const CommandID selectAll = 0x1006;
  17070. /** The command ID that should be used to send a "Deselect all" command. */
  17071. static const CommandID deselectAll = 0x1007;
  17072. }
  17073. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17074. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  17075. /**
  17076. Holds information describing an application command.
  17077. This object is used to pass information about a particular command, such as its
  17078. name, description and other usage flags.
  17079. When an ApplicationCommandTarget is asked to provide information about the commands
  17080. it can perform, this is the structure gets filled-in to describe each one.
  17081. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  17082. ApplicationCommandManager
  17083. */
  17084. struct JUCE_API ApplicationCommandInfo
  17085. {
  17086. ApplicationCommandInfo (const CommandID commandID) throw();
  17087. /** Sets a number of the structures values at once.
  17088. The meanings of each of the parameters is described below, in the appropriate
  17089. member variable's description.
  17090. */
  17091. void setInfo (const String& shortName,
  17092. const String& description,
  17093. const String& categoryName,
  17094. const int flags) throw();
  17095. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  17096. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  17097. is false, the bit is set.
  17098. */
  17099. void setActive (const bool isActive) throw();
  17100. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  17101. */
  17102. void setTicked (const bool isTicked) throw();
  17103. /** Handy method for adding a keypress to the defaultKeypresses array.
  17104. This is just so you can write things like:
  17105. @code
  17106. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  17107. @endcode
  17108. instead of
  17109. @code
  17110. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  17111. @endcode
  17112. */
  17113. void addDefaultKeypress (const int keyCode,
  17114. const ModifierKeys& modifiers) throw();
  17115. /** The command's unique ID number.
  17116. */
  17117. CommandID commandID;
  17118. /** A short name to describe the command.
  17119. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17120. You can use the setInfo() method to quickly set this and some of the command's
  17121. other properties.
  17122. */
  17123. String shortName;
  17124. /** A longer description of the command.
  17125. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17126. pop-up tooltip describing what the command does.
  17127. You can use the setInfo() method to quickly set this and some of the command's
  17128. other properties.
  17129. */
  17130. String description;
  17131. /** A named category that the command fits into.
  17132. You can give your commands any category you like, and these will be displayed in
  17133. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17134. commands together.
  17135. You can use the setInfo() method to quickly set this and some of the command's
  17136. other properties.
  17137. */
  17138. String categoryName;
  17139. /** A list of zero or more keypresses that should be used as the default keys for
  17140. this command.
  17141. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17142. this list to initialise the default set of key-to-command mappings.
  17143. @see addDefaultKeypress
  17144. */
  17145. Array <KeyPress> defaultKeypresses;
  17146. /** Flags describing the ways in which this command should be used.
  17147. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17148. variable.
  17149. */
  17150. enum CommandFlags
  17151. {
  17152. /** Indicates that the command can't currently be performed.
  17153. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17154. not currently permissable to perform the command. If the flag is set, then
  17155. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17156. command or show themselves as not being enabled.
  17157. @see ApplicationCommandInfo::setActive
  17158. */
  17159. isDisabled = 1 << 0,
  17160. /** Indicates that the command should have a tick next to it on a menu.
  17161. If your command is shown on a menu and this is set, it'll show a tick next to
  17162. it. Other components such as buttons may also use this flag to indicate that it
  17163. is a value that can be toggled, and is currently in the 'on' state.
  17164. @see ApplicationCommandInfo::setTicked
  17165. */
  17166. isTicked = 1 << 1,
  17167. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17168. it will call the command twice, once on key-down and again on key-up.
  17169. @see ApplicationCommandTarget::InvocationInfo
  17170. */
  17171. wantsKeyUpDownCallbacks = 1 << 2,
  17172. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17173. command in its list.
  17174. */
  17175. hiddenFromKeyEditor = 1 << 3,
  17176. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17177. command in its list, but won't allow the assigned keypress to be changed.
  17178. */
  17179. readOnlyInKeyEditor = 1 << 4,
  17180. /** If this flag is present and the command is invoked from a keypress, then any
  17181. buttons or menus that are also connected to the command will not flash to
  17182. indicate that they've been triggered.
  17183. */
  17184. dontTriggerVisualFeedback = 1 << 5
  17185. };
  17186. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17187. You can use the setInfo() method to quickly set this and some of the command's
  17188. other properties.
  17189. */
  17190. int flags;
  17191. };
  17192. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17193. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17194. /**
  17195. A command target publishes a list of command IDs that it can perform.
  17196. An ApplicationCommandManager despatches commands to targets, which must be
  17197. able to provide information about what commands they can handle.
  17198. To create a target, you'll need to inherit from this class, implementing all of
  17199. its pure virtual methods.
  17200. For info about how a target is chosen to receive a command, see
  17201. ApplicationCommandManager::getFirstCommandTarget().
  17202. @see ApplicationCommandManager, ApplicationCommandInfo
  17203. */
  17204. class JUCE_API ApplicationCommandTarget
  17205. {
  17206. public:
  17207. /** Creates a command target. */
  17208. ApplicationCommandTarget();
  17209. /** Destructor. */
  17210. virtual ~ApplicationCommandTarget();
  17211. /**
  17212. */
  17213. struct JUCE_API InvocationInfo
  17214. {
  17215. InvocationInfo (const CommandID commandID) throw();
  17216. /** The UID of the command that should be performed. */
  17217. CommandID commandID;
  17218. /** The command's flags.
  17219. See ApplicationCommandInfo for a description of these flag values.
  17220. */
  17221. int commandFlags;
  17222. /** The types of context in which the command might be called. */
  17223. enum InvocationMethod
  17224. {
  17225. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17226. fromKeyPress, /**< The command is being invoked by a key-press. */
  17227. fromMenu, /**< The command is being invoked by a menu selection. */
  17228. fromButton /**< The command is being invoked by a button click. */
  17229. };
  17230. /** The type of event that triggered this command. */
  17231. InvocationMethod invocationMethod;
  17232. /** If triggered by a keypress or menu, this will be the component that had the
  17233. keyboard focus at the time.
  17234. If triggered by a button, it may be set to that component, or it may be null.
  17235. */
  17236. Component* originatingComponent;
  17237. /** The keypress that was used to invoke it.
  17238. Note that this will be an invalid keypress if the command was invoked
  17239. by some other means than a keyboard shortcut.
  17240. */
  17241. KeyPress keyPress;
  17242. /** True if the callback is being invoked when the key is pressed,
  17243. false if the key is being released.
  17244. @see KeyPressMappingSet::addCommand()
  17245. */
  17246. bool isKeyDown;
  17247. /** If the key is being released, this indicates how long it had been held
  17248. down for.
  17249. (Only relevant if isKeyDown is false.)
  17250. */
  17251. int millisecsSinceKeyPressed;
  17252. };
  17253. /** This must return the next target to try after this one.
  17254. When a command is being sent, and the first target can't handle
  17255. that command, this method is used to determine the next target that should
  17256. be tried.
  17257. It may return 0 if it doesn't know of another target.
  17258. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17259. method to return a parent component that might want to handle it.
  17260. @see invoke
  17261. */
  17262. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17263. /** This must return a complete list of commands that this target can handle.
  17264. Your target should add all the command IDs that it handles to the array that is
  17265. passed-in.
  17266. */
  17267. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17268. /** This must provide details about one of the commands that this target can perform.
  17269. This will be called with one of the command IDs that the target provided in its
  17270. getAllCommands() methods.
  17271. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17272. suitable information about the command. (The commandID field will already have been filled-in
  17273. by the caller).
  17274. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17275. set all the fields at once.
  17276. If the command is currently inactive for some reason, this method must use
  17277. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17278. bit of the ApplicationCommandInfo::flags field).
  17279. Any default key-presses for the command should be appended to the
  17280. ApplicationCommandInfo::defaultKeypresses field.
  17281. Note that if you change something that affects the status of the commands
  17282. that would be returned by this method (e.g. something that makes some commands
  17283. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17284. to cause the manager to refresh its status.
  17285. */
  17286. virtual void getCommandInfo (const CommandID commandID,
  17287. ApplicationCommandInfo& result) = 0;
  17288. /** This must actually perform the specified command.
  17289. If this target is able to perform the command specified by the commandID field of the
  17290. InvocationInfo structure, then it should do so, and must return true.
  17291. If it can't handle this command, it should return false, which tells the caller to pass
  17292. the command on to the next target in line.
  17293. @see invoke, ApplicationCommandManager::invoke
  17294. */
  17295. virtual bool perform (const InvocationInfo& info) = 0;
  17296. /** Makes this target invoke a command.
  17297. Your code can call this method to invoke a command on this target, but normally
  17298. you'd call it indirectly via ApplicationCommandManager::invoke() or
  17299. ApplicationCommandManager::invokeDirectly().
  17300. If this target can perform the given command, it will call its perform() method to
  17301. do so. If not, then getNextCommandTarget() will be used to determine the next target
  17302. to try, and the command will be passed along to it.
  17303. @param invocationInfo this must be correctly filled-in, describing the context for
  17304. the invocation.
  17305. @param asynchronously if false, the command will be performed before this method returns.
  17306. If true, a message will be posted so that the command will be performed
  17307. later on the message thread, and this method will return immediately.
  17308. @see perform, ApplicationCommandManager::invoke
  17309. */
  17310. bool invoke (const InvocationInfo& invocationInfo,
  17311. const bool asynchronously);
  17312. /** Invokes a given command directly on this target.
  17313. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17314. structure.
  17315. */
  17316. bool invokeDirectly (const CommandID commandID,
  17317. const bool asynchronously);
  17318. /** Searches this target and all subsequent ones for the first one that can handle
  17319. the specified command.
  17320. This will use getNextCommandTarget() to determine the chain of targets to try
  17321. after this one.
  17322. */
  17323. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  17324. /** Checks whether this command can currently be performed by this target.
  17325. This will return true only if a call to getCommandInfo() doesn't set the
  17326. isDisabled flag to indicate that the command is inactive.
  17327. */
  17328. bool isCommandActive (const CommandID commandID);
  17329. /** If this object is a Component, this method will seach upwards in its current
  17330. UI hierarchy for the next parent component that implements the
  17331. ApplicationCommandTarget class.
  17332. If your target is a Component, this is a very handy method to use in your
  17333. getNextCommandTarget() implementation.
  17334. */
  17335. ApplicationCommandTarget* findFirstTargetParentComponent();
  17336. juce_UseDebuggingNewOperator
  17337. private:
  17338. // (for async invocation of commands)
  17339. class CommandTargetMessageInvoker : public MessageListener
  17340. {
  17341. public:
  17342. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  17343. ~CommandTargetMessageInvoker();
  17344. void handleMessage (const Message& message);
  17345. private:
  17346. ApplicationCommandTarget* const owner;
  17347. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  17348. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  17349. };
  17350. CommandTargetMessageInvoker* messageInvoker;
  17351. friend class CommandTargetMessageInvoker;
  17352. bool tryToInvoke (const InvocationInfo& info, const bool async);
  17353. };
  17354. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17355. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  17356. /********* Start of inlined file: juce_ActionListener.h *********/
  17357. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  17358. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  17359. /**
  17360. Receives callbacks to indicate that some kind of event has occurred.
  17361. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  17362. about something that's happened.
  17363. @see ActionListenerList, ActionBroadcaster, ChangeListener
  17364. */
  17365. class JUCE_API ActionListener
  17366. {
  17367. public:
  17368. /** Destructor. */
  17369. virtual ~ActionListener() {}
  17370. /** Overridden by your subclass to receive the callback.
  17371. @param message the string that was specified when the event was triggered
  17372. by a call to ActionListenerList::sendActionMessage()
  17373. */
  17374. virtual void actionListenerCallback (const String& message) = 0;
  17375. };
  17376. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  17377. /********* End of inlined file: juce_ActionListener.h *********/
  17378. /**
  17379. An instance of this class is used to specify initialisation and shutdown
  17380. code for the application.
  17381. An application that wants to run in the JUCE framework needs to declare a
  17382. subclass of JUCEApplication and implement its various pure virtual methods.
  17383. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  17384. to declare an instance of this class and generate a suitable platform-specific
  17385. main() function.
  17386. e.g. @code
  17387. class MyJUCEApp : public JUCEApplication
  17388. {
  17389. // NEVER put objects inside a JUCEApplication class - only use pointers to
  17390. // objects, which you must create in the initialise() method.
  17391. MyApplicationWindow* myMainWindow;
  17392. public:
  17393. MyJUCEApp()
  17394. : myMainWindow (0)
  17395. {
  17396. // never create any Juce objects in the constructor - do all your initialisation
  17397. // in the initialise() method.
  17398. }
  17399. ~MyJUCEApp()
  17400. {
  17401. // all your shutdown code must have already been done in the shutdown() method -
  17402. // nothing should happen in this destructor.
  17403. }
  17404. void initialise (const String& commandLine)
  17405. {
  17406. myMainWindow = new MyApplicationWindow();
  17407. myMainWindow->setBounds (100, 100, 400, 500);
  17408. myMainWindow->setVisible (true);
  17409. }
  17410. void shutdown()
  17411. {
  17412. delete myMainWindow;
  17413. }
  17414. const String getApplicationName()
  17415. {
  17416. return T("Super JUCE-o-matic");
  17417. }
  17418. const String getApplicationVersion()
  17419. {
  17420. return T("1.0");
  17421. }
  17422. };
  17423. // this creates wrapper code to actually launch the app properly.
  17424. START_JUCE_APPLICATION (MyJUCEApp)
  17425. @endcode
  17426. Because this object will be created before Juce has properly initialised, you must
  17427. NEVER add any member variable objects that will be automatically constructed. Likewise
  17428. don't put ANY code in the constructor that could call Juce functions. Any objects that
  17429. you want to add to the class must be pointers, which you should instantiate during the
  17430. initialise() method, and delete in the shutdown() method.
  17431. @see MessageManager, DeletedAtShutdown
  17432. */
  17433. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  17434. private ActionListener
  17435. {
  17436. protected:
  17437. /** Constructs a JUCE app object.
  17438. If subclasses implement a constructor or destructor, they shouldn't call any
  17439. JUCE code in there - put your startup/shutdown code in initialise() and
  17440. shutdown() instead.
  17441. */
  17442. JUCEApplication();
  17443. public:
  17444. /** Destructor.
  17445. If subclasses implement a constructor or destructor, they shouldn't call any
  17446. JUCE code in there - put your startup/shutdown code in initialise() and
  17447. shutdown() instead.
  17448. */
  17449. virtual ~JUCEApplication();
  17450. /** Returns the global instance of the application object being run. */
  17451. static JUCEApplication* getInstance() throw();
  17452. /** Called when the application starts.
  17453. This will be called once to let the application do whatever initialisation
  17454. it needs, create its windows, etc.
  17455. After the method returns, the normal event-dispatch loop will be run,
  17456. until the quit() method is called, at which point the shutdown()
  17457. method will be called to let the application clear up anything it needs
  17458. to delete.
  17459. If during the initialise() method, the application decides not to start-up
  17460. after all, it can just call the quit() method and the event loop won't be run.
  17461. @param commandLineParameters the line passed in does not include the
  17462. name of the executable, just the parameter list.
  17463. @see shutdown, quit
  17464. */
  17465. virtual void initialise (const String& commandLineParameters) = 0;
  17466. /** Returns true if the application hasn't yet completed its initialise() method
  17467. and entered the main event loop.
  17468. This is handy for things like splash screens to know when the app's up-and-running
  17469. properly.
  17470. */
  17471. bool isInitialising() const throw();
  17472. /* Called to allow the application to clear up before exiting.
  17473. After JUCEApplication::quit() has been called, the event-dispatch loop will
  17474. terminate, and this method will get called to allow the app to sort itself
  17475. out.
  17476. Be careful that nothing happens in this method that might rely on messages
  17477. being sent, or any kind of window activity, because the message loop is no
  17478. longer running at this point.
  17479. @see DeletedAtShutdown
  17480. */
  17481. virtual void shutdown() = 0;
  17482. /** Returns the application's name.
  17483. An application must implement this to name itself.
  17484. */
  17485. virtual const String getApplicationName() = 0;
  17486. /** Returns the application's version number.
  17487. An application can implement this to give itself a version.
  17488. (The default implementation of this just returns an empty string).
  17489. */
  17490. virtual const String getApplicationVersion();
  17491. /** Checks whether multiple instances of the app are allowed.
  17492. If you application class returns true for this, more than one instance is
  17493. permitted to run (except on the Mac where this isn't possible).
  17494. If it's false, the second instance won't start, but it you will still get a
  17495. callback to anotherInstanceStarted() to tell you about this - which
  17496. gives you a chance to react to what the user was trying to do.
  17497. */
  17498. virtual bool moreThanOneInstanceAllowed();
  17499. /** Indicates that the user has tried to start up another instance of the app.
  17500. This will get called even if moreThanOneInstanceAllowed() is false.
  17501. */
  17502. virtual void anotherInstanceStarted (const String& commandLine);
  17503. /** Called when the operating system is trying to close the application.
  17504. The default implementation of this method is to call quit(), but it may
  17505. be overloaded to ignore the request or do some other special behaviour
  17506. instead. For example, you might want to offer the user the chance to save
  17507. their changes before quitting, and give them the chance to cancel.
  17508. If you want to send a quit signal to your app, this is the correct method
  17509. to call, because it means that requests that come from the system get handled
  17510. in the same way as those from your own application code. So e.g. you'd
  17511. call this method from a "quit" item on a menu bar.
  17512. */
  17513. virtual void systemRequestedQuit();
  17514. /** If any unhandled exceptions make it through to the message dispatch loop, this
  17515. callback will be triggered, in case you want to log them or do some other
  17516. type of error-handling.
  17517. If the type of exception is derived from the std::exception class, the pointer
  17518. passed-in will be valid. If the exception is of unknown type, this pointer
  17519. will be null.
  17520. */
  17521. virtual void unhandledException (const std::exception* e,
  17522. const String& sourceFilename,
  17523. const int lineNumber);
  17524. /** Signals that the main message loop should stop and the application should terminate.
  17525. This isn't synchronous, it just posts a quit message to the main queue, and
  17526. when this message arrives, the message loop will stop, the shutdown() method
  17527. will be called, and the app will exit.
  17528. Note that this will cause an unconditional quit to happen, so if you need an
  17529. extra level before this, e.g. to give the user the chance to save their work
  17530. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  17531. method - see that method's help for more info.
  17532. @see MessageManager, DeletedAtShutdown
  17533. */
  17534. static void quit();
  17535. /** Sets the value that should be returned as the application's exit code when the
  17536. app quits.
  17537. This is the value that's returned by the main() function. Normally you'd leave this
  17538. as 0 unless you want to indicate an error code.
  17539. @see getApplicationReturnValue
  17540. */
  17541. void setApplicationReturnValue (const int newReturnValue) throw();
  17542. /** Returns the value that has been set as the application's exit code.
  17543. @see setApplicationReturnValue
  17544. */
  17545. int getApplicationReturnValue() const throw() { return appReturnValue; }
  17546. /** Returns the application's command line params.
  17547. */
  17548. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  17549. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  17550. /** @internal */
  17551. static int main (String& commandLine, JUCEApplication* const newApp);
  17552. /** @internal */
  17553. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  17554. /** @internal */
  17555. static void sendUnhandledException (const std::exception* const e,
  17556. const char* const sourceFile,
  17557. const int lineNumber);
  17558. /** @internal */
  17559. ApplicationCommandTarget* getNextCommandTarget();
  17560. /** @internal */
  17561. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  17562. /** @internal */
  17563. void getAllCommands (Array <CommandID>& commands);
  17564. /** @internal */
  17565. bool perform (const InvocationInfo& info);
  17566. /** @internal */
  17567. void actionListenerCallback (const String& message);
  17568. private:
  17569. String commandLineParameters;
  17570. int appReturnValue;
  17571. bool stillInitialising;
  17572. static int shutdownAppAndClearUp();
  17573. };
  17574. #endif // __JUCE_APPLICATION_JUCEHEADER__
  17575. /********* End of inlined file: juce_Application.h *********/
  17576. #endif
  17577. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17578. #endif
  17579. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17580. #endif
  17581. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17582. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  17583. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17584. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17585. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  17586. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  17587. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  17588. /**
  17589. Has a callback method that is triggered asynchronously.
  17590. This object allows an asynchronous callback function to be triggered, for
  17591. tasks such as coalescing multiple updates into a single callback later on.
  17592. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  17593. message thread calling handleAsyncUpdate() as soon as it can.
  17594. */
  17595. class JUCE_API AsyncUpdater
  17596. {
  17597. public:
  17598. /** Creates an AsyncUpdater object. */
  17599. AsyncUpdater() throw();
  17600. /** Destructor.
  17601. If there are any pending callbacks when the object is deleted, these are lost.
  17602. */
  17603. virtual ~AsyncUpdater();
  17604. /** Causes the callback to be triggered at a later time.
  17605. This method returns immediately, having made sure that a callback
  17606. to the handleAsyncUpdate() method will occur as soon as possible.
  17607. If an update callback is already pending but hasn't happened yet, calls
  17608. to this method will be ignored.
  17609. It's thread-safe to call this method from any number of threads without
  17610. needing to worry about locking.
  17611. */
  17612. void triggerAsyncUpdate() throw();
  17613. /** This will stop any pending updates from happening.
  17614. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  17615. callback happens, this will cancel the handleAsyncUpdate() callback.
  17616. */
  17617. void cancelPendingUpdate() throw();
  17618. /** If an update has been triggered and is pending, this will invoke it
  17619. synchronously.
  17620. Use this as a kind of "flush" operation - if an update is pending, the
  17621. handleAsyncUpdate() method will be called immediately; if no update is
  17622. pending, then nothing will be done.
  17623. */
  17624. void handleUpdateNowIfNeeded();
  17625. /** Called back to do whatever your class needs to do.
  17626. This method is called by the message thread at the next convenient time
  17627. after the triggerAsyncUpdate() method has been called.
  17628. */
  17629. virtual void handleAsyncUpdate() = 0;
  17630. private:
  17631. class AsyncUpdaterInternal : public MessageListener
  17632. {
  17633. public:
  17634. AsyncUpdaterInternal() throw() {}
  17635. ~AsyncUpdaterInternal() {}
  17636. void handleMessage (const Message&);
  17637. AsyncUpdater* owner;
  17638. private:
  17639. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  17640. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  17641. };
  17642. AsyncUpdaterInternal internalAsyncHandler;
  17643. bool asyncMessagePending;
  17644. };
  17645. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  17646. /********* End of inlined file: juce_AsyncUpdater.h *********/
  17647. /********* Start of inlined file: juce_Desktop.h *********/
  17648. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  17649. #define __JUCE_DESKTOP_JUCEHEADER__
  17650. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  17651. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17652. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17653. /**
  17654. Classes derived from this will be automatically deleted when the application exits.
  17655. After JUCEApplication::shutdown() has been called, any objects derived from
  17656. DeletedAtShutdown which are still in existence will be deleted in the reverse
  17657. order to that in which they were created.
  17658. So if you've got a singleton and don't want to have to explicitly delete it, just
  17659. inherit from this and it'll be taken care of.
  17660. */
  17661. class JUCE_API DeletedAtShutdown
  17662. {
  17663. protected:
  17664. /** Creates a DeletedAtShutdown object. */
  17665. DeletedAtShutdown() throw();
  17666. /** Destructor.
  17667. It's ok to delete these objects explicitly - it's only the ones left
  17668. dangling at the end that will be deleted automatically.
  17669. */
  17670. virtual ~DeletedAtShutdown();
  17671. public:
  17672. /** Deletes all extant objects.
  17673. This shouldn't be used by applications, as it's called automatically
  17674. in the shutdown code of the JUCEApplication class.
  17675. */
  17676. static void deleteAll();
  17677. private:
  17678. DeletedAtShutdown (const DeletedAtShutdown&);
  17679. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  17680. };
  17681. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17682. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  17683. /********* Start of inlined file: juce_Timer.h *********/
  17684. #ifndef __JUCE_TIMER_JUCEHEADER__
  17685. #define __JUCE_TIMER_JUCEHEADER__
  17686. class InternalTimerThread;
  17687. /**
  17688. Repeatedly calls a user-defined method at a specified time interval.
  17689. A Timer's timerCallback() method will be repeatedly called at a given
  17690. interval. Initially when a Timer object is created, they will do nothing
  17691. until the startTimer() method is called, then the message thread will
  17692. start calling it back until stopTimer() is called.
  17693. The time interval isn't guaranteed to be precise to any more than maybe
  17694. 10-20ms, and the intervals may end up being much longer than requested if the
  17695. system is busy. Because it's the message thread that is doing the callbacks,
  17696. any messages that take a significant amount of time to process will block
  17697. all the timers for that period.
  17698. If you need to have a single callback that is shared by multiple timers with
  17699. different frequencies, then the MultiTimer class allows you to do that - its
  17700. structure is very similar to the Timer class, but contains multiple timers
  17701. internally, each one identified by an ID number.
  17702. @see MultiTimer
  17703. */
  17704. class JUCE_API Timer
  17705. {
  17706. protected:
  17707. /** Creates a Timer.
  17708. When created, the timer is stopped, so use startTimer() to get it going.
  17709. */
  17710. Timer() throw();
  17711. /** Creates a copy of another timer.
  17712. Note that this timer won't be started, even if the one you're copying
  17713. is running.
  17714. */
  17715. Timer (const Timer& other) throw();
  17716. public:
  17717. /** Destructor. */
  17718. virtual ~Timer();
  17719. /** The user-defined callback routine that actually gets called periodically.
  17720. It's perfectly ok to call startTimer() or stopTimer() from within this
  17721. callback to change the subsequent intervals.
  17722. */
  17723. virtual void timerCallback() = 0;
  17724. /** Starts the timer and sets the length of interval required.
  17725. If the timer is already started, this will reset it, so the
  17726. time between calling this method and the next timer callback
  17727. will not be less than the interval length passed in.
  17728. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  17729. rounded up to 1)
  17730. */
  17731. void startTimer (const int intervalInMilliseconds) throw();
  17732. /** Stops the timer.
  17733. No more callbacks will be made after this method returns.
  17734. If this is called from a different thread, any callbacks that may
  17735. be currently executing may be allowed to finish before the method
  17736. returns.
  17737. */
  17738. void stopTimer() throw();
  17739. /** Checks if the timer has been started.
  17740. @returns true if the timer is running.
  17741. */
  17742. bool isTimerRunning() const throw() { return periodMs > 0; }
  17743. /** Returns the timer's interval.
  17744. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  17745. */
  17746. int getTimerInterval() const throw() { return periodMs; }
  17747. private:
  17748. friend class InternalTimerThread;
  17749. int countdownMs, periodMs;
  17750. Timer* previous;
  17751. Timer* next;
  17752. const Timer& operator= (const Timer&);
  17753. };
  17754. #endif // __JUCE_TIMER_JUCEHEADER__
  17755. /********* End of inlined file: juce_Timer.h *********/
  17756. /**
  17757. Classes can implement this interface and register themselves with the Desktop class
  17758. to receive callbacks when the currently focused component changes.
  17759. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  17760. */
  17761. class JUCE_API FocusChangeListener
  17762. {
  17763. public:
  17764. /** Destructor. */
  17765. virtual ~FocusChangeListener() {}
  17766. /** Callback to indicate that the currently focused component has changed. */
  17767. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  17768. };
  17769. /**
  17770. Describes and controls aspects of the computer's desktop.
  17771. */
  17772. class JUCE_API Desktop : private DeletedAtShutdown,
  17773. private Timer,
  17774. private AsyncUpdater
  17775. {
  17776. public:
  17777. /** There's only one dektop object, and this method will return it.
  17778. */
  17779. static Desktop& JUCE_CALLTYPE getInstance() throw();
  17780. /** Returns a list of the positions of all the monitors available.
  17781. The first rectangle in the list will be the main monitor area.
  17782. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17783. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17784. */
  17785. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  17786. /** Returns the position and size of the main monitor.
  17787. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17788. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17789. */
  17790. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  17791. /** Returns the position and size of the monitor which contains this co-ordinate.
  17792. If none of the monitors contains the point, this will just return the
  17793. main monitor.
  17794. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  17795. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  17796. */
  17797. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  17798. /** Returns the mouse position.
  17799. The co-ordinates are relative to the top-left of the main monitor.
  17800. */
  17801. static void getMousePosition (int& x, int& y) throw();
  17802. /** Makes the mouse pointer jump to a given location.
  17803. The co-ordinates are relative to the top-left of the main monitor.
  17804. */
  17805. static void setMousePosition (int x, int y) throw();
  17806. /** Returns the last position at which a mouse button was pressed.
  17807. */
  17808. static void getLastMouseDownPosition (int& x, int& y) throw();
  17809. /** Returns the number of times the mouse button has been clicked since the
  17810. app started.
  17811. Each mouse-down event increments this number by 1.
  17812. */
  17813. static int getMouseButtonClickCounter() throw();
  17814. /** This lets you prevent the screensaver from becoming active.
  17815. Handy if you're running some sort of presentation app where having a screensaver
  17816. appear would be annoying.
  17817. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  17818. won't enable a screensaver unless the user has actually set one up).
  17819. The disablement will only happen while the Juce application is the foreground
  17820. process - if another task is running in front of it, then the screensaver will
  17821. be unaffected.
  17822. @see isScreenSaverEnabled
  17823. */
  17824. static void setScreenSaverEnabled (const bool isEnabled) throw();
  17825. /** Returns true if the screensaver has not been turned off.
  17826. This will return the last value passed into setScreenSaverEnabled(). Note that
  17827. it won't tell you whether the user is actually using a screen saver, just
  17828. whether this app is deliberately preventing one from running.
  17829. @see setScreenSaverEnabled
  17830. */
  17831. static bool isScreenSaverEnabled() throw();
  17832. /** Registers a MouseListener that will receive all mouse events that occur on
  17833. any component.
  17834. @see removeGlobalMouseListener
  17835. */
  17836. void addGlobalMouseListener (MouseListener* const listener) throw();
  17837. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  17838. method.
  17839. @see addGlobalMouseListener
  17840. */
  17841. void removeGlobalMouseListener (MouseListener* const listener) throw();
  17842. /** Registers a MouseListener that will receive a callback whenever the focused
  17843. component changes.
  17844. */
  17845. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  17846. /** Unregisters a listener that was added with addFocusChangeListener(). */
  17847. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  17848. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  17849. The component must already be on the desktop for this method to work. It will
  17850. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  17851. etc will be hidden.
  17852. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  17853. the component that's currently being used will be resized back to the size
  17854. and position it was in before being put into this mode.
  17855. */
  17856. void setKioskModeComponent (Component* componentToUse);
  17857. /** Returns the component that is currently being used in kiosk-mode.
  17858. This is the component that was last set by setKioskModeComponent(). If none
  17859. has been set, this returns 0.
  17860. */
  17861. Component* getKioskModeComponent() const { return kioskModeComponent; }
  17862. /** Returns the number of components that are currently active as top-level
  17863. desktop windows.
  17864. @see getComponent, Component::addToDesktop
  17865. */
  17866. int getNumComponents() const throw();
  17867. /** Returns one of the top-level desktop window components.
  17868. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  17869. index is out-of-range.
  17870. @see getNumComponents, Component::addToDesktop
  17871. */
  17872. Component* getComponent (const int index) const throw();
  17873. /** Finds the component at a given screen location.
  17874. This will drill down into top-level windows to find the child component at
  17875. the given position.
  17876. Returns 0 if the co-ordinates are inside a non-Juce window.
  17877. */
  17878. Component* findComponentAt (const int screenX,
  17879. const int screenY) const;
  17880. juce_UseDebuggingNewOperator
  17881. /** Tells this object to refresh its idea of what the screen resolution is.
  17882. (Called internally by the native code).
  17883. */
  17884. void refreshMonitorSizes() throw();
  17885. /** True if the OS supports semitransparent windows */
  17886. static bool canUseSemiTransparentWindows() throw();
  17887. private:
  17888. friend class Component;
  17889. friend class ComponentPeer;
  17890. SortedSet <void*> mouseListeners, focusListeners;
  17891. VoidArray desktopComponents;
  17892. friend class DeletedAtShutdown;
  17893. friend class TopLevelWindowManager;
  17894. Desktop() throw();
  17895. ~Desktop() throw();
  17896. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  17897. int lastMouseX, lastMouseY;
  17898. Component* kioskModeComponent;
  17899. Rectangle kioskComponentOriginalBounds;
  17900. void timerCallback();
  17901. void sendMouseMove();
  17902. void resetTimer() throw();
  17903. int getNumDisplayMonitors() const throw();
  17904. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  17905. void addDesktopComponent (Component* const c) throw();
  17906. void removeDesktopComponent (Component* const c) throw();
  17907. void componentBroughtToFront (Component* const c) throw();
  17908. void triggerFocusCallback() throw();
  17909. void handleAsyncUpdate();
  17910. Desktop (const Desktop&);
  17911. const Desktop& operator= (const Desktop&);
  17912. };
  17913. #endif // __JUCE_DESKTOP_JUCEHEADER__
  17914. /********* End of inlined file: juce_Desktop.h *********/
  17915. class KeyPressMappingSet;
  17916. class ApplicationCommandManagerListener;
  17917. /**
  17918. One of these objects holds a list of all the commands your app can perform,
  17919. and despatches these commands when needed.
  17920. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  17921. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  17922. to invoke automatically, which means you don't have to handle the result of a menu
  17923. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  17924. which can choose which events they want to handle.
  17925. This architecture also allows for nested ApplicationCommandTargets, so that for example
  17926. you could have two different objects, one inside the other, both of which can respond to
  17927. a "delete" command. Depending on which one has focus, the command will be sent to the
  17928. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  17929. method.
  17930. To set up your app to use commands, you'll need to do the following:
  17931. - Create a global ApplicationCommandManager to hold the list of all possible
  17932. commands. (This will also manage a set of key-mappings for them).
  17933. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  17934. This allows the object to provide a list of commands that it can perform, and
  17935. to handle them.
  17936. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  17937. or ApplicationCommandManager::registerCommand().
  17938. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  17939. method to access the key-mapper object, which you will need to register as a key-listener
  17940. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  17941. about setting this up.
  17942. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  17943. cause these commands to be invoked automatically.
  17944. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  17945. When a command is invoked, the ApplicationCommandManager will try to choose the best
  17946. ApplicationCommandTarget to receive the specified command. To do this it will use the
  17947. current keyboard focus to see which component might be interested, and will search the
  17948. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  17949. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  17950. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  17951. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  17952. point if the command still hasn't been performed, it will be passed to the current
  17953. JUCEApplication object (which is itself an ApplicationCommandTarget).
  17954. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  17955. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  17956. the object yourself.
  17957. @see ApplicationCommandTarget, ApplicationCommandInfo
  17958. */
  17959. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  17960. private FocusChangeListener
  17961. {
  17962. public:
  17963. /** Creates an ApplicationCommandManager.
  17964. Once created, you'll need to register all your app's commands with it, using
  17965. ApplicationCommandManager::registerAllCommandsForTarget() or
  17966. ApplicationCommandManager::registerCommand().
  17967. */
  17968. ApplicationCommandManager();
  17969. /** Destructor.
  17970. Make sure that you don't delete this if pointers to it are still being used by
  17971. objects such as PopupMenus or Buttons.
  17972. */
  17973. virtual ~ApplicationCommandManager();
  17974. /** Clears the current list of all commands.
  17975. Note that this will also clear the contents of the KeyPressMappingSet.
  17976. */
  17977. void clearCommands();
  17978. /** Adds a command to the list of registered commands.
  17979. @see registerAllCommandsForTarget
  17980. */
  17981. void registerCommand (const ApplicationCommandInfo& newCommand);
  17982. /** Adds all the commands that this target publishes to the manager's list.
  17983. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  17984. to get details about all the commands that this target can do, and will call
  17985. registerCommand() to add each one to the manger's list.
  17986. @see registerCommand
  17987. */
  17988. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  17989. /** Removes the command with a specified ID.
  17990. Note that this will also remove any key mappings that are mapped to the command.
  17991. */
  17992. void removeCommand (const CommandID commandID);
  17993. /** This should be called to tell the manager that one of its registered commands may have changed
  17994. its active status.
  17995. Because the command manager only finds out whether a command is active or inactive by querying
  17996. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  17997. allows things like buttons to update their enablement, etc.
  17998. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  17999. for any registered listeners.
  18000. */
  18001. void commandStatusChanged();
  18002. /** Returns the number of commands that have been registered.
  18003. @see registerCommand
  18004. */
  18005. int getNumCommands() const throw() { return commands.size(); }
  18006. /** Returns the details about one of the registered commands.
  18007. The index is between 0 and (getNumCommands() - 1).
  18008. */
  18009. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  18010. /** Returns the details about a given command ID.
  18011. This will search the list of registered commands for one with the given command
  18012. ID number, and return its associated info. If no matching command is found, this
  18013. will return 0.
  18014. */
  18015. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  18016. /** Returns the name field for a command.
  18017. An empty string is returned if no command with this ID has been registered.
  18018. @see getDescriptionOfCommand
  18019. */
  18020. const String getNameOfCommand (const CommandID commandID) const throw();
  18021. /** Returns the description field for a command.
  18022. An empty string is returned if no command with this ID has been registered. If the
  18023. command has no description, this will return its short name field instead.
  18024. @see getNameOfCommand
  18025. */
  18026. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  18027. /** Returns the list of categories.
  18028. This will go through all registered commands, and return a list of all the distict
  18029. categoryName values from their ApplicationCommandInfo structure.
  18030. @see getCommandsInCategory()
  18031. */
  18032. const StringArray getCommandCategories() const throw();
  18033. /** Returns a list of all the command UIDs in a particular category.
  18034. @see getCommandCategories()
  18035. */
  18036. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  18037. /** Returns the manager's internal set of key mappings.
  18038. This object can be used to edit the keypresses. To actually link this object up
  18039. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  18040. class.
  18041. @see KeyPressMappingSet
  18042. */
  18043. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  18044. /** Invokes the given command directly, sending it to the default target.
  18045. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  18046. structure.
  18047. */
  18048. bool invokeDirectly (const CommandID commandID,
  18049. const bool asynchronously);
  18050. /** Sends a command to the default target.
  18051. This will choose a target using getFirstCommandTarget(), and send the specified command
  18052. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  18053. first target can't handle the command, it will be passed on to targets further down the
  18054. chain (see ApplicationCommandTarget::invoke() for more info).
  18055. @param invocationInfo this must be correctly filled-in, describing the context for
  18056. the invocation.
  18057. @param asynchronously if false, the command will be performed before this method returns.
  18058. If true, a message will be posted so that the command will be performed
  18059. later on the message thread, and this method will return immediately.
  18060. @see ApplicationCommandTarget::invoke
  18061. */
  18062. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  18063. const bool asynchronously);
  18064. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  18065. Whenever the manager needs to know which target a command should be sent to, it calls
  18066. this method to determine the first one to try.
  18067. By default, this method will return the target that was set by calling setFirstCommandTarget().
  18068. If no target is set, it will return the result of findDefaultComponentTarget().
  18069. If you need to make sure all commands go via your own custom target, then you can
  18070. either use setFirstCommandTarget() to specify a single target, or override this method
  18071. if you need more complex logic to choose one.
  18072. It may return 0 if no targets are available.
  18073. @see getTargetForCommand, invoke, invokeDirectly
  18074. */
  18075. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  18076. /** Sets a target to be returned by getFirstCommandTarget().
  18077. If this is set to 0, then getFirstCommandTarget() will by default return the
  18078. result of findDefaultComponentTarget().
  18079. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  18080. deleting the target object.
  18081. */
  18082. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  18083. /** Tries to find the best target to use to perform a given command.
  18084. This will call getFirstCommandTarget() to find the preferred target, and will
  18085. check whether that target can handle the given command. If it can't, then it'll use
  18086. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  18087. so on until no more are available.
  18088. If no targets are found that can perform the command, this method will return 0.
  18089. If a target is found, then it will get the target to fill-in the upToDateInfo
  18090. structure with the latest info about that command, so that the caller can see
  18091. whether the command is disabled, ticked, etc.
  18092. */
  18093. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  18094. ApplicationCommandInfo& upToDateInfo);
  18095. /** Registers a listener that will be called when various events occur. */
  18096. void addListener (ApplicationCommandManagerListener* const listener) throw();
  18097. /** Deregisters a previously-added listener. */
  18098. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  18099. /** Looks for a suitable command target based on which Components have the keyboard focus.
  18100. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  18101. but is exposed here in case it's useful.
  18102. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  18103. windows, etc., and using the findTargetForComponent() method.
  18104. */
  18105. static ApplicationCommandTarget* findDefaultComponentTarget();
  18106. /** Examines this component and all its parents in turn, looking for the first one
  18107. which is a ApplicationCommandTarget.
  18108. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  18109. that class.
  18110. */
  18111. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  18112. juce_UseDebuggingNewOperator
  18113. private:
  18114. OwnedArray <ApplicationCommandInfo> commands;
  18115. SortedSet <void*> listeners;
  18116. KeyPressMappingSet* keyMappings;
  18117. ApplicationCommandTarget* firstTarget;
  18118. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  18119. void handleAsyncUpdate();
  18120. void globalFocusChanged (Component*);
  18121. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  18122. // version of this method.
  18123. virtual short getFirstCommandTarget() { return 0; }
  18124. };
  18125. /**
  18126. A listener that receives callbacks from an ApplicationCommandManager when
  18127. commands are invoked or the command list is changed.
  18128. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  18129. */
  18130. class JUCE_API ApplicationCommandManagerListener
  18131. {
  18132. public:
  18133. /** Destructor. */
  18134. virtual ~ApplicationCommandManagerListener() {}
  18135. /** Called when an app command is about to be invoked. */
  18136. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18137. /** Called when commands are registered or deregistered from the
  18138. command manager, or when commands are made active or inactive.
  18139. Note that if you're using this to watch for changes to whether a command is disabled,
  18140. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18141. whenever the status of your command might have changed.
  18142. */
  18143. virtual void applicationCommandListChanged() = 0;
  18144. };
  18145. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18146. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18147. #endif
  18148. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18149. #endif
  18150. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18151. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18152. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18153. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18154. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18155. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18156. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18157. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18158. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18159. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18160. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18161. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18162. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18163. /********* Start of inlined file: juce_ChangeListener.h *********/
  18164. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18165. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18166. /**
  18167. Receives callbacks about changes to some kind of object.
  18168. Many objects use a ChangeListenerList to keep a set of listeners which they
  18169. will inform when something changes. A subclass of ChangeListener
  18170. is used to receive these callbacks.
  18171. Note that the major difference between an ActionListener and a ChangeListener
  18172. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18173. callbacks, but ActionListeners perform one callback for every event posted.
  18174. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18175. */
  18176. class JUCE_API ChangeListener
  18177. {
  18178. public:
  18179. /** Destructor. */
  18180. virtual ~ChangeListener() {}
  18181. /** Overridden by your subclass to receive the callback.
  18182. @param objectThatHasChanged the value that was passed to the
  18183. ChangeListenerList::sendChangeMessage() method
  18184. */
  18185. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18186. };
  18187. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18188. /********* End of inlined file: juce_ChangeListener.h *********/
  18189. /**
  18190. A set of ChangeListeners.
  18191. Listeners can be added and removed from the list, and change messages can be
  18192. broadcast to all the listeners.
  18193. @see ChangeListener, ChangeBroadcaster
  18194. */
  18195. class JUCE_API ChangeListenerList : public MessageListener
  18196. {
  18197. public:
  18198. /** Creates an empty list. */
  18199. ChangeListenerList() throw();
  18200. /** Destructor. */
  18201. ~ChangeListenerList() throw();
  18202. /** Adds a listener to the list.
  18203. (Trying to add a listener that's already on the list will have no effect).
  18204. */
  18205. void addChangeListener (ChangeListener* const listener) throw();
  18206. /** Removes a listener from the list.
  18207. If the listener isn't on the list, this won't have any effect.
  18208. */
  18209. void removeChangeListener (ChangeListener* const listener) throw();
  18210. /** Removes all listeners from the list. */
  18211. void removeAllChangeListeners() throw();
  18212. /** Posts an asynchronous change message to all the listeners.
  18213. If a message has already been sent and hasn't yet been delivered, this
  18214. method won't send another - in this way it coalesces multiple frequent
  18215. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18216. with the ActionListener, which posts a new event for every call to its
  18217. sendActionMessage() method.
  18218. Only listeners which are on the list when the change event is delivered
  18219. will receive the event - and this may include listeners that weren't on
  18220. the list when the change message was sent.
  18221. @param objectThatHasChanged this pointer is passed to the
  18222. ChangeListener::changeListenerCallback() method,
  18223. and can be any value the application needs
  18224. @see sendSynchronousChangeMessage
  18225. */
  18226. void sendChangeMessage (void* objectThatHasChanged) throw();
  18227. /** This will synchronously callback all the ChangeListeners.
  18228. Use this if you need to synchronously force a call to all the
  18229. listeners' ChangeListener::changeListenerCallback() methods.
  18230. */
  18231. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18232. /** If a change message has been sent but not yet dispatched, this will
  18233. use sendSynchronousChangeMessage() to make the callback immediately.
  18234. */
  18235. void dispatchPendingMessages();
  18236. /** @internal */
  18237. void handleMessage (const Message&);
  18238. juce_UseDebuggingNewOperator
  18239. private:
  18240. SortedSet <void*> listeners;
  18241. CriticalSection lock;
  18242. void* lastChangedObject;
  18243. bool messagePending;
  18244. ChangeListenerList (const ChangeListenerList&);
  18245. const ChangeListenerList& operator= (const ChangeListenerList&);
  18246. };
  18247. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18248. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18249. /** Manages a list of ChangeListeners, and can send them messages.
  18250. To quickly add methods to your class that can add/remove change
  18251. listeners and broadcast to them, you can derive from this.
  18252. @see ChangeListenerList, ChangeListener
  18253. */
  18254. class JUCE_API ChangeBroadcaster
  18255. {
  18256. public:
  18257. /** Creates an ChangeBroadcaster. */
  18258. ChangeBroadcaster() throw();
  18259. /** Destructor. */
  18260. virtual ~ChangeBroadcaster();
  18261. /** Adds a listener to the list.
  18262. (Trying to add a listener that's already on the list will have no effect).
  18263. */
  18264. void addChangeListener (ChangeListener* const listener) throw();
  18265. /** Removes a listener from the list.
  18266. If the listener isn't on the list, this won't have any effect.
  18267. */
  18268. void removeChangeListener (ChangeListener* const listener) throw();
  18269. /** Removes all listeners from the list. */
  18270. void removeAllChangeListeners() throw();
  18271. /** Broadcasts a change message to all the registered listeners.
  18272. The message will be delivered asynchronously by the event thread, so this
  18273. method will not directly call any of the listeners. For a synchronous
  18274. message, use sendSynchronousChangeMessage().
  18275. @see ChangeListenerList::sendActionMessage
  18276. */
  18277. void sendChangeMessage (void* objectThatHasChanged) throw();
  18278. /** Sends a synchronous change message to all the registered listeners.
  18279. @see ChangeListenerList::sendSynchronousChangeMessage
  18280. */
  18281. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18282. /** If a change message has been sent but not yet dispatched, this will
  18283. use sendSynchronousChangeMessage() to make the callback immediately.
  18284. */
  18285. void dispatchPendingMessages();
  18286. private:
  18287. ChangeListenerList changeListenerList;
  18288. ChangeBroadcaster (const ChangeBroadcaster&);
  18289. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  18290. };
  18291. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18292. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  18293. /** Wrapper on a file that stores a list of key/value data pairs.
  18294. Useful for storing application settings, etc. See the PropertySet class for
  18295. the interfaces that read and write values.
  18296. Not designed for very large amounts of data, as it keeps all the values in
  18297. memory and writes them out to disk lazily when they are changed.
  18298. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  18299. with it, and these will be signalled when a value changes.
  18300. @see PropertySet
  18301. */
  18302. class JUCE_API PropertiesFile : public PropertySet,
  18303. public ChangeBroadcaster,
  18304. private Timer
  18305. {
  18306. public:
  18307. enum FileFormatOptions
  18308. {
  18309. ignoreCaseOfKeyNames = 1,
  18310. storeAsBinary = 2,
  18311. storeAsCompressedBinary = 4,
  18312. storeAsXML = 8
  18313. };
  18314. /**
  18315. Creates a PropertiesFile object.
  18316. @param file the file to use
  18317. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  18318. is changed, the object will wait for this amount
  18319. of time and then save the file. If zero, the file
  18320. will be written to disk immediately on being changed
  18321. (which might be slow, as it'll re-write synchronously
  18322. each time a value-change method is called). If it is
  18323. less than zero, the file won't be saved until
  18324. save() or saveIfNeeded() are explicitly called.
  18325. @param options a combination of the flags in the FileFormatOptions
  18326. enum, which specify the type of file to save, and other
  18327. options.
  18328. */
  18329. PropertiesFile (const File& file,
  18330. const int millisecondsBeforeSaving,
  18331. const int options) throw();
  18332. /** Destructor.
  18333. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  18334. */
  18335. ~PropertiesFile();
  18336. /** This will flush all the values to disk if they've changed since the last
  18337. time they were saved.
  18338. Returns false if it fails to write to the file for some reason (maybe because
  18339. it's read-only or the directory doesn't exist or something).
  18340. @see save
  18341. */
  18342. bool saveIfNeeded();
  18343. /** This will force a write-to-disk of the current values, regardless of whether
  18344. anything has changed since the last save.
  18345. Returns false if it fails to write to the file for some reason (maybe because
  18346. it's read-only or the directory doesn't exist or something).
  18347. @see saveIfNeeded
  18348. */
  18349. bool save();
  18350. /** Returns true if the properties have been altered since the last time they were
  18351. saved.
  18352. */
  18353. bool needsToBeSaved() const throw();
  18354. /** Returns the file that's being used. */
  18355. const File getFile() const throw();
  18356. /** Handy utility to create a properties file in whatever the standard OS-specific
  18357. location is for these things.
  18358. This uses getDefaultAppSettingsFile() to decide what file to create, then
  18359. creates a PropertiesFile object with the specified properties. See
  18360. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  18361. what the parameters do.
  18362. @see getDefaultAppSettingsFile
  18363. */
  18364. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  18365. const String& fileNameSuffix,
  18366. const String& folderName,
  18367. const bool commonToAllUsers,
  18368. const int millisecondsBeforeSaving,
  18369. const int propertiesFileOptions);
  18370. /** Handy utility to choose a file in the standard OS-dependent location for application
  18371. settings files.
  18372. So on a Mac, this will return a file called:
  18373. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  18374. On Windows it'll return something like:
  18375. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  18376. On Linux it'll return
  18377. ~/.[folderName]/[applicationName].[fileNameSuffix]
  18378. If you pass an empty string as the folder name, it'll use the app name for this (or
  18379. omit the folder name on the Mac).
  18380. If commonToAllUsers is true, then this will return the same file for all users of the
  18381. computer, regardless of the current user. If it is false, the file will be specific to
  18382. only the current user. Use this to choose whether you're saving settings that are common
  18383. or user-specific.
  18384. */
  18385. static const File getDefaultAppSettingsFile (const String& applicationName,
  18386. const String& fileNameSuffix,
  18387. const String& folderName,
  18388. const bool commonToAllUsers);
  18389. juce_UseDebuggingNewOperator
  18390. protected:
  18391. virtual void propertyChanged();
  18392. private:
  18393. File file;
  18394. int timerInterval;
  18395. const int options;
  18396. bool needsWriting;
  18397. void timerCallback();
  18398. PropertiesFile (const PropertiesFile&);
  18399. const PropertiesFile& operator= (const PropertiesFile&);
  18400. };
  18401. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  18402. /********* End of inlined file: juce_PropertiesFile.h *********/
  18403. /**
  18404. Manages a collection of properties.
  18405. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  18406. as a singleton.
  18407. It holds two different PropertiesFile objects internally, one for user-specific
  18408. settings (stored in your user directory), and one for settings that are common to
  18409. all users (stored in a folder accessible to all users).
  18410. The class manages the creation of these files on-demand, allowing access via the
  18411. getUserSettings() and getCommonSettings() methods. It also has a few handy
  18412. methods like testWriteAccess() to check that the files can be saved.
  18413. If you're using one of these as a singleton, then your app's start-up code should
  18414. first of all call setStorageParameters() to tell it the parameters to use to create
  18415. the properties files.
  18416. @see PropertiesFile
  18417. */
  18418. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  18419. {
  18420. public:
  18421. /**
  18422. Creates an ApplicationProperties object.
  18423. Before using it, you must call setStorageParameters() to give it the info
  18424. it needs to create the property files.
  18425. */
  18426. ApplicationProperties() throw();
  18427. /** Destructor.
  18428. */
  18429. ~ApplicationProperties();
  18430. juce_DeclareSingleton (ApplicationProperties, false)
  18431. /** Gives the object the information it needs to create the appropriate properties files.
  18432. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  18433. info about how these parameters are used.
  18434. */
  18435. void setStorageParameters (const String& applicationName,
  18436. const String& fileNameSuffix,
  18437. const String& folderName,
  18438. const int millisecondsBeforeSaving,
  18439. const int propertiesFileOptions) throw();
  18440. /** Tests whether the files can be successfully written to, and can show
  18441. an error message if not.
  18442. Returns true if none of the tests fail.
  18443. @param testUserSettings if true, the user settings file will be tested
  18444. @param testCommonSettings if true, the common settings file will be tested
  18445. @param showWarningDialogOnFailure if true, the method will show a helpful error
  18446. message box if either of the tests fail
  18447. */
  18448. bool testWriteAccess (const bool testUserSettings,
  18449. const bool testCommonSettings,
  18450. const bool showWarningDialogOnFailure);
  18451. /** Returns the user settings file.
  18452. The first time this is called, it will create and load the properties file.
  18453. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  18454. the common settings are used as a second-chance place to look. This is done via the
  18455. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  18456. to the fallback for the user settings.
  18457. @see getCommonSettings
  18458. */
  18459. PropertiesFile* getUserSettings() throw();
  18460. /** Returns the common settings file.
  18461. The first time this is called, it will create and load the properties file.
  18462. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  18463. read-only (e.g. because the user doesn't have permission to write
  18464. to shared files), then this will return the user settings instead,
  18465. (like getUserSettings() would do). This is handy if you'd like to
  18466. write a value to the common settings, but if that's no possible,
  18467. then you'd rather write to the user settings than none at all.
  18468. If returnUserPropsIfReadOnly is false, this method will always return
  18469. the common settings, even if any changes to them can't be saved.
  18470. @see getUserSettings
  18471. */
  18472. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  18473. /** Saves both files if they need to be saved.
  18474. @see PropertiesFile::saveIfNeeded
  18475. */
  18476. bool saveIfNeeded();
  18477. /** Flushes and closes both files if they are open.
  18478. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  18479. and closes both files. They will then be re-opened the next time getUserSettings()
  18480. or getCommonSettings() is called.
  18481. */
  18482. void closeFiles();
  18483. juce_UseDebuggingNewOperator
  18484. private:
  18485. PropertiesFile* userProps;
  18486. PropertiesFile* commonProps;
  18487. String appName, fileSuffix, folderName;
  18488. int msBeforeSaving, options;
  18489. int commonSettingsAreReadOnly;
  18490. ApplicationProperties (const ApplicationProperties&);
  18491. const ApplicationProperties& operator= (const ApplicationProperties&);
  18492. void openFiles() throw();
  18493. };
  18494. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18495. /********* End of inlined file: juce_ApplicationProperties.h *********/
  18496. #endif
  18497. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  18498. #endif
  18499. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18500. #endif
  18501. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18502. /********* Start of inlined file: juce_SystemClipboard.h *********/
  18503. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18504. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18505. /**
  18506. Handles reading/writing to the system's clipboard.
  18507. */
  18508. class JUCE_API SystemClipboard
  18509. {
  18510. public:
  18511. /** Copies a string of text onto the clipboard */
  18512. static void copyTextToClipboard (const String& text) throw();
  18513. /** Gets the current clipboard's contents.
  18514. Obviously this might have come from another app, so could contain
  18515. anything..
  18516. */
  18517. static const String getTextFromClipboard() throw();
  18518. };
  18519. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  18520. /********* End of inlined file: juce_SystemClipboard.h *********/
  18521. #endif
  18522. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18523. /********* Start of inlined file: juce_MidiBuffer.h *********/
  18524. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18525. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  18526. /********* Start of inlined file: juce_MidiMessage.h *********/
  18527. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  18528. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  18529. /**
  18530. Encapsulates a MIDI message.
  18531. @see MidiMessageSequence, MidiOutput, MidiInput
  18532. */
  18533. class JUCE_API MidiMessage
  18534. {
  18535. public:
  18536. /** Creates a 3-byte short midi message.
  18537. @param byte1 message byte 1
  18538. @param byte2 message byte 2
  18539. @param byte3 message byte 3
  18540. @param timeStamp the time to give the midi message - this value doesn't
  18541. use any particular units, so will be application-specific
  18542. */
  18543. MidiMessage (const int byte1,
  18544. const int byte2,
  18545. const int byte3,
  18546. const double timeStamp = 0) throw();
  18547. /** Creates a 2-byte short midi message.
  18548. @param byte1 message byte 1
  18549. @param byte2 message byte 2
  18550. @param timeStamp the time to give the midi message - this value doesn't
  18551. use any particular units, so will be application-specific
  18552. */
  18553. MidiMessage (const int byte1,
  18554. const int byte2,
  18555. const double timeStamp = 0) throw();
  18556. /** Creates a 1-byte short midi message.
  18557. @param byte1 message byte 1
  18558. @param timeStamp the time to give the midi message - this value doesn't
  18559. use any particular units, so will be application-specific
  18560. */
  18561. MidiMessage (const int byte1,
  18562. const double timeStamp = 0) throw();
  18563. /** Creates a midi message from a block of data. */
  18564. MidiMessage (const uint8* const data,
  18565. const int dataSize,
  18566. const double timeStamp = 0) throw();
  18567. /** Reads the next midi message from some data.
  18568. This will read as many bytes from a data stream as it needs to make a
  18569. complete message, and will return the number of bytes it used. This lets
  18570. you read a sequence of midi messages from a file or stream.
  18571. @param data the data to read from
  18572. @param size the maximum number of bytes it's allowed to read
  18573. @param numBytesUsed returns the number of bytes that were actually needed
  18574. @param lastStatusByte in a sequence of midi messages, the initial byte
  18575. can be dropped from a message if it's the same as the
  18576. first byte of the previous message, so this lets you
  18577. supply the byte to use if the first byte of the message
  18578. has in fact been dropped.
  18579. @param timeStamp the time to give the midi message - this value doesn't
  18580. use any particular units, so will be application-specific
  18581. */
  18582. MidiMessage (const uint8* data,
  18583. int size,
  18584. int& numBytesUsed,
  18585. uint8 lastStatusByte,
  18586. double timeStamp = 0) throw();
  18587. /** Creates a copy of another midi message. */
  18588. MidiMessage (const MidiMessage& other) throw();
  18589. /** Creates a copy of another midi message, with a different timestamp. */
  18590. MidiMessage (const MidiMessage& other,
  18591. const double newTimeStamp) throw();
  18592. /** Destructor. */
  18593. ~MidiMessage() throw();
  18594. /** Copies this message from another one. */
  18595. const MidiMessage& operator= (const MidiMessage& other) throw();
  18596. /** Returns a pointer to the raw midi data.
  18597. @see getRawDataSize
  18598. */
  18599. uint8* getRawData() const throw() { return data; }
  18600. /** Returns the number of bytes of data in the message.
  18601. @see getRawData
  18602. */
  18603. int getRawDataSize() const throw() { return size; }
  18604. /** Returns the timestamp associated with this message.
  18605. The units for the timestamp will be application-specific.
  18606. @see setTimeStamp, addToTimeStamp
  18607. */
  18608. double getTimeStamp() const throw() { return timeStamp; }
  18609. /** Changes the message's associated timestamp.
  18610. The units for the timestamp will be application-specific.
  18611. @see addToTimeStamp, getTimeStamp
  18612. */
  18613. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18614. /** Adds a value to the message's timestamp.
  18615. The units for the timestamp will be application-specific.
  18616. */
  18617. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18618. /** Returns the midi channel associated with the message.
  18619. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18620. if it's a sysex)
  18621. @see isForChannel, setChannel
  18622. */
  18623. int getChannel() const throw();
  18624. /** Returns true if the message applies to the given midi channel.
  18625. @param channelNumber the channel number to look for, in the range 1 to 16
  18626. @see getChannel, setChannel
  18627. */
  18628. bool isForChannel (const int channelNumber) const throw();
  18629. /** Changes the message's midi channel.
  18630. This won't do anything for non-channel messages like sysexes.
  18631. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18632. */
  18633. void setChannel (const int newChannelNumber) throw();
  18634. /** Returns true if this is a system-exclusive message.
  18635. */
  18636. bool isSysEx() const throw();
  18637. /** Returns a pointer to the sysex data inside the message.
  18638. If this event isn't a sysex event, it'll return 0.
  18639. @see getSysExDataSize
  18640. */
  18641. const uint8* getSysExData() const throw();
  18642. /** Returns the size of the sysex data.
  18643. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18644. @see getSysExData
  18645. */
  18646. int getSysExDataSize() const throw();
  18647. /** Returns true if this message is a 'key-down' event.
  18648. This will return false for a note-on event with a velocity of 0.
  18649. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18650. */
  18651. bool isNoteOn() const throw();
  18652. /** Creates a key-down message (using a floating-point velocity).
  18653. @param channel the midi channel, in the range 1 to 16
  18654. @param noteNumber the key number, 0 to 127
  18655. @param velocity in the range 0 to 1.0
  18656. @see isNoteOn
  18657. */
  18658. static const MidiMessage noteOn (const int channel,
  18659. const int noteNumber,
  18660. const float velocity) throw();
  18661. /** Creates a key-down message (using an integer velocity).
  18662. @param channel the midi channel, in the range 1 to 16
  18663. @param noteNumber the key number, 0 to 127
  18664. @param velocity in the range 0 to 127
  18665. @see isNoteOn
  18666. */
  18667. static const MidiMessage noteOn (const int channel,
  18668. const int noteNumber,
  18669. const uint8 velocity) throw();
  18670. /** Returns true if this message is a 'key-up' event.
  18671. This will also return true for a note-on event with a velocity of 0.
  18672. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18673. */
  18674. bool isNoteOff() const throw();
  18675. /** Creates a key-up message.
  18676. @param channel the midi channel, in the range 1 to 16
  18677. @param noteNumber the key number, 0 to 127
  18678. @see isNoteOff
  18679. */
  18680. static const MidiMessage noteOff (const int channel,
  18681. const int noteNumber) throw();
  18682. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18683. @see isNoteOn, isNoteOff
  18684. */
  18685. bool isNoteOnOrOff() const throw();
  18686. /** Returns the midi note number for note-on and note-off messages.
  18687. If the message isn't a note-on or off, the value returned will be
  18688. meaningless.
  18689. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18690. */
  18691. int getNoteNumber() const throw();
  18692. /** Changes the midi note number of a note-on or note-off message.
  18693. If the message isn't a note on or off, this will do nothing.
  18694. */
  18695. void setNoteNumber (const int newNoteNumber) throw();
  18696. /** Returns the velocity of a note-on or note-off message.
  18697. The value returned will be in the range 0 to 127.
  18698. If the message isn't a note-on or off event, it will return 0.
  18699. @see getFloatVelocity
  18700. */
  18701. uint8 getVelocity() const throw();
  18702. /** Returns the velocity of a note-on or note-off message.
  18703. The value returned will be in the range 0 to 1.0
  18704. If the message isn't a note-on or off event, it will return 0.
  18705. @see getVelocity, setVelocity
  18706. */
  18707. float getFloatVelocity() const throw();
  18708. /** Changes the velocity of a note-on or note-off message.
  18709. If the message isn't a note on or off, this will do nothing.
  18710. @param newVelocity the new velocity, in the range 0 to 1.0
  18711. @see getFloatVelocity, multiplyVelocity
  18712. */
  18713. void setVelocity (const float newVelocity) throw();
  18714. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  18715. If the message isn't a note on or off, this will do nothing.
  18716. @param scaleFactor the value by which to multiply the velocity
  18717. @see setVelocity
  18718. */
  18719. void multiplyVelocity (const float scaleFactor) throw();
  18720. /** Returns true if the message is a program (patch) change message.
  18721. @see getProgramChangeNumber, getGMInstrumentName
  18722. */
  18723. bool isProgramChange() const throw();
  18724. /** Returns the new program number of a program change message.
  18725. If the message isn't a program change, the value returned will be
  18726. nonsense.
  18727. @see isProgramChange, getGMInstrumentName
  18728. */
  18729. int getProgramChangeNumber() const throw();
  18730. /** Creates a program-change message.
  18731. @param channel the midi channel, in the range 1 to 16
  18732. @param programNumber the midi program number, 0 to 127
  18733. @see isProgramChange, getGMInstrumentName
  18734. */
  18735. static const MidiMessage programChange (const int channel,
  18736. const int programNumber) throw();
  18737. /** Returns true if the message is a pitch-wheel move.
  18738. @see getPitchWheelValue, pitchWheel
  18739. */
  18740. bool isPitchWheel() const throw();
  18741. /** Returns the pitch wheel position from a pitch-wheel move message.
  18742. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  18743. If called for messages which aren't pitch wheel events, the number returned will be
  18744. nonsense.
  18745. @see isPitchWheel
  18746. */
  18747. int getPitchWheelValue() const throw();
  18748. /** Creates a pitch-wheel move message.
  18749. @param channel the midi channel, in the range 1 to 16
  18750. @param position the wheel position, in the range 0 to 16383
  18751. @see isPitchWheel
  18752. */
  18753. static const MidiMessage pitchWheel (const int channel,
  18754. const int position) throw();
  18755. /** Returns true if the message is an aftertouch event.
  18756. For aftertouch events, use the getNoteNumber() method to find out the key
  18757. that it applies to, and getAftertouchValue() to find out the amount. Use
  18758. getChannel() to find out the channel.
  18759. @see getAftertouchValue, getNoteNumber
  18760. */
  18761. bool isAftertouch() const throw();
  18762. /** Returns the amount of aftertouch from an aftertouch messages.
  18763. The value returned is in the range 0 to 127, and will be nonsense for messages
  18764. other than aftertouch messages.
  18765. @see isAftertouch
  18766. */
  18767. int getAfterTouchValue() const throw();
  18768. /** Creates an aftertouch message.
  18769. @param channel the midi channel, in the range 1 to 16
  18770. @param noteNumber the key number, 0 to 127
  18771. @param aftertouchAmount the amount of aftertouch, 0 to 127
  18772. @see isAftertouch
  18773. */
  18774. static const MidiMessage aftertouchChange (const int channel,
  18775. const int noteNumber,
  18776. const int aftertouchAmount) throw();
  18777. /** Returns true if the message is a channel-pressure change event.
  18778. This is like aftertouch, but common to the whole channel rather than a specific
  18779. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  18780. to find out the channel.
  18781. @see channelPressureChange
  18782. */
  18783. bool isChannelPressure() const throw();
  18784. /** Returns the pressure from a channel pressure change message.
  18785. @returns the pressure, in the range 0 to 127
  18786. @see isChannelPressure, channelPressureChange
  18787. */
  18788. int getChannelPressureValue() const throw();
  18789. /** Creates a channel-pressure change event.
  18790. @param channel the midi channel: 1 to 16
  18791. @param pressure the pressure, 0 to 127
  18792. @see isChannelPressure
  18793. */
  18794. static const MidiMessage channelPressureChange (const int channel,
  18795. const int pressure) throw();
  18796. /** Returns true if this is a midi controller message.
  18797. @see getControllerNumber, getControllerValue, controllerEvent
  18798. */
  18799. bool isController() const throw();
  18800. /** Returns the controller number of a controller message.
  18801. The name of the controller can be looked up using the getControllerName() method.
  18802. Note that the value returned is invalid for messages that aren't controller changes.
  18803. @see isController, getControllerName, getControllerValue
  18804. */
  18805. int getControllerNumber() const throw();
  18806. /** Returns the controller value from a controller message.
  18807. A value 0 to 127 is returned to indicate the new controller position.
  18808. Note that the value returned is invalid for messages that aren't controller changes.
  18809. @see isController, getControllerNumber
  18810. */
  18811. int getControllerValue() const throw();
  18812. /** Creates a controller message.
  18813. @param channel the midi channel, in the range 1 to 16
  18814. @param controllerType the type of controller
  18815. @param value the controller value
  18816. @see isController
  18817. */
  18818. static const MidiMessage controllerEvent (const int channel,
  18819. const int controllerType,
  18820. const int value) throw();
  18821. /** Checks whether this message is an all-notes-off message.
  18822. @see allNotesOff
  18823. */
  18824. bool isAllNotesOff() const throw();
  18825. /** Checks whether this message is an all-sound-off message.
  18826. @see allSoundOff
  18827. */
  18828. bool isAllSoundOff() const throw();
  18829. /** Creates an all-notes-off message.
  18830. @param channel the midi channel, in the range 1 to 16
  18831. @see isAllNotesOff
  18832. */
  18833. static const MidiMessage allNotesOff (const int channel) throw();
  18834. /** Creates an all-sound-off message.
  18835. @param channel the midi channel, in the range 1 to 16
  18836. @see isAllSoundOff
  18837. */
  18838. static const MidiMessage allSoundOff (const int channel) throw();
  18839. /** Creates an all-controllers-off message.
  18840. @param channel the midi channel, in the range 1 to 16
  18841. */
  18842. static const MidiMessage allControllersOff (const int channel) throw();
  18843. /** Returns true if this event is a meta-event.
  18844. Meta-events are things like tempo changes, track names, etc.
  18845. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18846. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18847. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18848. */
  18849. bool isMetaEvent() const throw();
  18850. /** Returns a meta-event's type number.
  18851. If the message isn't a meta-event, this will return -1.
  18852. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  18853. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  18854. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  18855. */
  18856. int getMetaEventType() const throw();
  18857. /** Returns a pointer to the data in a meta-event.
  18858. @see isMetaEvent, getMetaEventLength
  18859. */
  18860. const uint8* getMetaEventData() const throw();
  18861. /** Returns the length of the data for a meta-event.
  18862. @see isMetaEvent, getMetaEventData
  18863. */
  18864. int getMetaEventLength() const throw();
  18865. /** Returns true if this is a 'track' meta-event. */
  18866. bool isTrackMetaEvent() const throw();
  18867. /** Returns true if this is an 'end-of-track' meta-event. */
  18868. bool isEndOfTrackMetaEvent() const throw();
  18869. /** Creates an end-of-track meta-event.
  18870. @see isEndOfTrackMetaEvent
  18871. */
  18872. static const MidiMessage endOfTrack() throw();
  18873. /** Returns true if this is an 'track name' meta-event.
  18874. You can use the getTextFromTextMetaEvent() method to get the track's name.
  18875. */
  18876. bool isTrackNameEvent() const throw();
  18877. /** Returns true if this is a 'text' meta-event.
  18878. @see getTextFromTextMetaEvent
  18879. */
  18880. bool isTextMetaEvent() const throw();
  18881. /** Returns the text from a text meta-event.
  18882. @see isTextMetaEvent
  18883. */
  18884. const String getTextFromTextMetaEvent() const throw();
  18885. /** Returns true if this is a 'tempo' meta-event.
  18886. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  18887. */
  18888. bool isTempoMetaEvent() const throw();
  18889. /** Returns the tick length from a tempo meta-event.
  18890. @param timeFormat the 16-bit time format value from the midi file's header.
  18891. @returns the tick length (in seconds).
  18892. @see isTempoMetaEvent
  18893. */
  18894. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  18895. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  18896. @see isTempoMetaEvent, getTempoMetaEventTickLength
  18897. */
  18898. double getTempoSecondsPerQuarterNote() const throw();
  18899. /** Creates a tempo meta-event.
  18900. @see isTempoMetaEvent
  18901. */
  18902. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  18903. /** Returns true if this is a 'time-signature' meta-event.
  18904. @see getTimeSignatureInfo
  18905. */
  18906. bool isTimeSignatureMetaEvent() const throw();
  18907. /** Returns the time-signature values from a time-signature meta-event.
  18908. @see isTimeSignatureMetaEvent
  18909. */
  18910. void getTimeSignatureInfo (int& numerator,
  18911. int& denominator) const throw();
  18912. /** Creates a time-signature meta-event.
  18913. @see isTimeSignatureMetaEvent
  18914. */
  18915. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  18916. const int denominator) throw();
  18917. /** Returns true if this is a 'key-signature' meta-event.
  18918. @see getKeySignatureNumberOfSharpsOrFlats
  18919. */
  18920. bool isKeySignatureMetaEvent() const throw();
  18921. /** Returns the key from a key-signature meta-event.
  18922. @see isKeySignatureMetaEvent
  18923. */
  18924. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  18925. /** Returns true if this is a 'channel' meta-event.
  18926. A channel meta-event specifies the midi channel that should be used
  18927. for subsequent meta-events.
  18928. @see getMidiChannelMetaEventChannel
  18929. */
  18930. bool isMidiChannelMetaEvent() const throw();
  18931. /** Returns the channel number from a channel meta-event.
  18932. @returns the channel, in the range 1 to 16.
  18933. @see isMidiChannelMetaEvent
  18934. */
  18935. int getMidiChannelMetaEventChannel() const throw();
  18936. /** Creates a midi channel meta-event.
  18937. @param channel the midi channel, in the range 1 to 16
  18938. @see isMidiChannelMetaEvent
  18939. */
  18940. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  18941. /** Returns true if this is an active-sense message. */
  18942. bool isActiveSense() const throw();
  18943. /** Returns true if this is a midi start event.
  18944. @see midiStart
  18945. */
  18946. bool isMidiStart() const throw();
  18947. /** Creates a midi start event. */
  18948. static const MidiMessage midiStart() throw();
  18949. /** Returns true if this is a midi continue event.
  18950. @see midiContinue
  18951. */
  18952. bool isMidiContinue() const throw();
  18953. /** Creates a midi continue event. */
  18954. static const MidiMessage midiContinue() throw();
  18955. /** Returns true if this is a midi stop event.
  18956. @see midiStop
  18957. */
  18958. bool isMidiStop() const throw();
  18959. /** Creates a midi stop event. */
  18960. static const MidiMessage midiStop() throw();
  18961. /** Returns true if this is a midi clock event.
  18962. @see midiClock, songPositionPointer
  18963. */
  18964. bool isMidiClock() const throw();
  18965. /** Creates a midi clock event. */
  18966. static const MidiMessage midiClock() throw();
  18967. /** Returns true if this is a song-position-pointer message.
  18968. @see getSongPositionPointerMidiBeat, songPositionPointer
  18969. */
  18970. bool isSongPositionPointer() const throw();
  18971. /** Returns the midi beat-number of a song-position-pointer message.
  18972. @see isSongPositionPointer, songPositionPointer
  18973. */
  18974. int getSongPositionPointerMidiBeat() const throw();
  18975. /** Creates a song-position-pointer message.
  18976. The position is a number of midi beats from the start of the song, where 1 midi
  18977. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  18978. are 4 midi beats in a quarter-note.
  18979. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  18980. */
  18981. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  18982. /** Returns true if this is a quarter-frame midi timecode message.
  18983. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  18984. */
  18985. bool isQuarterFrame() const throw();
  18986. /** Returns the sequence number of a quarter-frame midi timecode message.
  18987. This will be a value between 0 and 7.
  18988. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  18989. */
  18990. int getQuarterFrameSequenceNumber() const throw();
  18991. /** Returns the value from a quarter-frame message.
  18992. This will be the lower nybble of the message's data-byte, a value
  18993. between 0 and 15
  18994. */
  18995. int getQuarterFrameValue() const throw();
  18996. /** Creates a quarter-frame MTC message.
  18997. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  18998. @param value a value 0 to 15 for the lower nybble of the message's data byte
  18999. */
  19000. static const MidiMessage quarterFrame (const int sequenceNumber,
  19001. const int value) throw();
  19002. /** SMPTE timecode types.
  19003. Used by the getFullFrameParameters() and fullFrame() methods.
  19004. */
  19005. enum SmpteTimecodeType
  19006. {
  19007. fps24 = 0,
  19008. fps25 = 1,
  19009. fps30drop = 2,
  19010. fps30 = 3
  19011. };
  19012. /** Returns true if this is a full-frame midi timecode message.
  19013. */
  19014. bool isFullFrame() const throw();
  19015. /** Extracts the timecode information from a full-frame midi timecode message.
  19016. You should only call this on messages where you've used isFullFrame() to
  19017. check that they're the right kind.
  19018. */
  19019. void getFullFrameParameters (int& hours,
  19020. int& minutes,
  19021. int& seconds,
  19022. int& frames,
  19023. SmpteTimecodeType& timecodeType) const throw();
  19024. /** Creates a full-frame MTC message.
  19025. */
  19026. static const MidiMessage fullFrame (const int hours,
  19027. const int minutes,
  19028. const int seconds,
  19029. const int frames,
  19030. SmpteTimecodeType timecodeType);
  19031. /** Types of MMC command.
  19032. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  19033. */
  19034. enum MidiMachineControlCommand
  19035. {
  19036. mmc_stop = 1,
  19037. mmc_play = 2,
  19038. mmc_deferredplay = 3,
  19039. mmc_fastforward = 4,
  19040. mmc_rewind = 5,
  19041. mmc_recordStart = 6,
  19042. mmc_recordStop = 7,
  19043. mmc_pause = 9
  19044. };
  19045. /** Checks whether this is an MMC message.
  19046. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  19047. */
  19048. bool isMidiMachineControlMessage() const throw();
  19049. /** For an MMC message, this returns its type.
  19050. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  19051. calling this method.
  19052. */
  19053. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  19054. /** Creates an MMC message.
  19055. */
  19056. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  19057. /** Checks whether this is an MMC "goto" message.
  19058. If it is, the parameters passed-in are set to the time that the message contains.
  19059. @see midiMachineControlGoto
  19060. */
  19061. bool isMidiMachineControlGoto (int& hours,
  19062. int& minutes,
  19063. int& seconds,
  19064. int& frames) const throw();
  19065. /** Creates an MMC "goto" message.
  19066. This messages tells the device to go to a specific frame.
  19067. @see isMidiMachineControlGoto
  19068. */
  19069. static const MidiMessage midiMachineControlGoto (int hours,
  19070. int minutes,
  19071. int seconds,
  19072. int frames);
  19073. /** Creates a master-volume change message.
  19074. @param volume the volume, 0 to 1.0
  19075. */
  19076. static const MidiMessage masterVolume (const float volume) throw();
  19077. /** Creates a system-exclusive message.
  19078. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  19079. */
  19080. static const MidiMessage createSysExMessage (const uint8* sysexData,
  19081. const int dataSize) throw();
  19082. /** Reads a midi variable-length integer.
  19083. @param data the data to read the number from
  19084. @param numBytesUsed on return, this will be set to the number of bytes that were read
  19085. */
  19086. static int readVariableLengthVal (const uint8* data,
  19087. int& numBytesUsed) throw();
  19088. /** Based on the first byte of a short midi message, this uses a lookup table
  19089. to return the message length (either 1, 2, or 3 bytes).
  19090. The value passed in must be 0x80 or higher.
  19091. */
  19092. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  19093. /** Returns the name of a midi note number.
  19094. E.g "C", "D#", etc.
  19095. @param noteNumber the midi note number, 0 to 127
  19096. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  19097. they'll be flattened, e.g. "Db"
  19098. @param includeOctaveNumber if true, the octave number will be appended to the string,
  19099. e.g. "C#4"
  19100. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  19101. number that will be used for middle C's octave
  19102. @see getMidiNoteInHertz
  19103. */
  19104. static const String getMidiNoteName (int noteNumber,
  19105. bool useSharps,
  19106. bool includeOctaveNumber,
  19107. int octaveNumForMiddleC) throw();
  19108. /** Returns the frequency of a midi note number.
  19109. @see getMidiNoteName
  19110. */
  19111. static const double getMidiNoteInHertz (int noteNumber) throw();
  19112. /** Returns the standard name of a GM instrument.
  19113. @param midiInstrumentNumber the program number 0 to 127
  19114. @see getProgramChangeNumber
  19115. */
  19116. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  19117. /** Returns the name of a bank of GM instruments.
  19118. @param midiBankNumber the bank, 0 to 15
  19119. */
  19120. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19121. /** Returns the standard name of a channel 10 percussion sound.
  19122. @param midiNoteNumber the key number, 35 to 81
  19123. */
  19124. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19125. /** Returns the name of a controller type number.
  19126. @see getControllerNumber
  19127. */
  19128. static const String getControllerName (int controllerNumber) throw();
  19129. juce_UseDebuggingNewOperator
  19130. private:
  19131. double timeStamp;
  19132. uint8* data;
  19133. int message, size;
  19134. };
  19135. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19136. /********* End of inlined file: juce_MidiMessage.h *********/
  19137. /**
  19138. Holds a sequence of time-stamped midi events.
  19139. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19140. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19141. @see MidiMessage
  19142. */
  19143. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19144. {
  19145. public:
  19146. /** Creates an empty MidiBuffer. */
  19147. MidiBuffer() throw();
  19148. /** Creates a copy of another MidiBuffer. */
  19149. MidiBuffer (const MidiBuffer& other) throw();
  19150. /** Makes a copy of another MidiBuffer. */
  19151. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19152. /** Destructor */
  19153. ~MidiBuffer() throw();
  19154. /** Removes all events from the buffer. */
  19155. void clear() throw();
  19156. /** Removes all events between two times from the buffer.
  19157. All events for which (start <= event position < start + numSamples) will
  19158. be removed.
  19159. */
  19160. void clear (const int start,
  19161. const int numSamples) throw();
  19162. /** Returns true if the buffer is empty.
  19163. To actually retrieve the events, use a MidiBuffer::Iterator object
  19164. */
  19165. bool isEmpty() const throw();
  19166. /** Counts the number of events in the buffer.
  19167. This is actually quite a slow operation, as it has to iterate through all
  19168. the events, so you might prefer to call isEmpty() if that's all you need
  19169. to know.
  19170. */
  19171. int getNumEvents() const throw();
  19172. /** Adds an event to the buffer.
  19173. The sample number will be used to determine the position of the event in
  19174. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19175. ignored.
  19176. If an event is added whose sample position is the same as one or more events
  19177. already in the buffer, the new event will be placed after the existing ones.
  19178. To retrieve events, use a MidiBuffer::Iterator object
  19179. */
  19180. void addEvent (const MidiMessage& midiMessage,
  19181. const int sampleNumber) throw();
  19182. /** Adds an event to the buffer from raw midi data.
  19183. The sample number will be used to determine the position of the event in
  19184. the buffer, which is always kept sorted.
  19185. If an event is added whose sample position is the same as one or more events
  19186. already in the buffer, the new event will be placed after the existing ones.
  19187. The event data will be inspected to calculate the number of bytes in length that
  19188. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19189. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19190. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19191. add an event at all.
  19192. To retrieve events, use a MidiBuffer::Iterator object
  19193. */
  19194. void addEvent (const uint8* const rawMidiData,
  19195. const int maxBytesOfMidiData,
  19196. const int sampleNumber) throw();
  19197. /** Adds some events from another buffer to this one.
  19198. @param otherBuffer the buffer containing the events you want to add
  19199. @param startSample the lowest sample number in the source buffer for which
  19200. events should be added. Any source events whose timestamp is
  19201. less than this will be ignored
  19202. @param numSamples the valid range of samples from the source buffer for which
  19203. events should be added - i.e. events in the source buffer whose
  19204. timestamp is greater than or equal to (startSample + numSamples)
  19205. will be ignored. If this value is less than 0, all events after
  19206. startSample will be taken.
  19207. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19208. that are added to this buffer
  19209. */
  19210. void addEvents (const MidiBuffer& otherBuffer,
  19211. const int startSample,
  19212. const int numSamples,
  19213. const int sampleDeltaToAdd) throw();
  19214. /** Returns the sample number of the first event in the buffer.
  19215. If the buffer's empty, this will just return 0.
  19216. */
  19217. int getFirstEventTime() const throw();
  19218. /** Returns the sample number of the last event in the buffer.
  19219. If the buffer's empty, this will just return 0.
  19220. */
  19221. int getLastEventTime() const throw();
  19222. /**
  19223. Used to iterate through the events in a MidiBuffer.
  19224. Note that altering the buffer while an iterator is using it isn't a
  19225. safe operation.
  19226. @see MidiBuffer
  19227. */
  19228. class Iterator
  19229. {
  19230. public:
  19231. /** Creates an Iterator for this MidiBuffer. */
  19232. Iterator (const MidiBuffer& buffer) throw();
  19233. /** Destructor. */
  19234. ~Iterator() throw();
  19235. /** Repositions the iterator so that the next event retrieved will be the first
  19236. one whose sample position is at greater than or equal to the given position.
  19237. */
  19238. void setNextSamplePosition (const int samplePosition) throw();
  19239. /** Retrieves a copy of the next event from the buffer.
  19240. @param result on return, this will be the message (the MidiMessage's timestamp
  19241. is not set)
  19242. @param samplePosition on return, this will be the position of the event
  19243. @returns true if an event was found, or false if the iterator has reached
  19244. the end of the buffer
  19245. */
  19246. bool getNextEvent (MidiMessage& result,
  19247. int& samplePosition) throw();
  19248. /** Retrieves the next event from the buffer.
  19249. @param midiData on return, this pointer will be set to a block of data containing
  19250. the midi message. Note that to make it fast, this is a pointer
  19251. directly into the MidiBuffer's internal data, so is only valid
  19252. temporarily until the MidiBuffer is altered.
  19253. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19254. midi message
  19255. @param samplePosition on return, this will be the position of the event
  19256. @returns true if an event was found, or false if the iterator has reached
  19257. the end of the buffer
  19258. */
  19259. bool getNextEvent (const uint8* &midiData,
  19260. int& numBytesOfMidiData,
  19261. int& samplePosition) throw();
  19262. juce_UseDebuggingNewOperator
  19263. private:
  19264. const MidiBuffer& buffer;
  19265. const uint8* data;
  19266. Iterator (const Iterator&);
  19267. const Iterator& operator= (const Iterator&);
  19268. };
  19269. juce_UseDebuggingNewOperator
  19270. private:
  19271. friend class MidiBuffer::Iterator;
  19272. int bytesUsed;
  19273. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19274. };
  19275. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19276. /********* End of inlined file: juce_MidiBuffer.h *********/
  19277. #endif
  19278. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19279. /********* Start of inlined file: juce_MidiFile.h *********/
  19280. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19281. #define __JUCE_MIDIFILE_JUCEHEADER__
  19282. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19283. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19284. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19285. /**
  19286. A sequence of timestamped midi messages.
  19287. This allows the sequence to be manipulated, and also to be read from and
  19288. written to a standard midi file.
  19289. @see MidiMessage, MidiFile
  19290. */
  19291. class JUCE_API MidiMessageSequence
  19292. {
  19293. public:
  19294. /** Creates an empty midi sequence object. */
  19295. MidiMessageSequence();
  19296. /** Creates a copy of another sequence. */
  19297. MidiMessageSequence (const MidiMessageSequence& other);
  19298. /** Replaces this sequence with another one. */
  19299. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19300. /** Destructor. */
  19301. ~MidiMessageSequence();
  19302. /** Structure used to hold midi events in the sequence.
  19303. These structures act as 'handles' on the events as they are moved about in
  19304. the list, and make it quick to find the matching note-offs for note-on events.
  19305. @see MidiMessageSequence::getEventPointer
  19306. */
  19307. class MidiEventHolder
  19308. {
  19309. public:
  19310. /** Destructor. */
  19311. ~MidiEventHolder();
  19312. /** The message itself, whose timestamp is used to specify the event's time.
  19313. */
  19314. MidiMessage message;
  19315. /** The matching note-off event (if this is a note-on event).
  19316. If this isn't a note-on, this pointer will be null.
  19317. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19318. note-offs up-to-date after events have been moved around in the sequence
  19319. or deleted.
  19320. */
  19321. MidiEventHolder* noteOffObject;
  19322. juce_UseDebuggingNewOperator
  19323. private:
  19324. friend class MidiMessageSequence;
  19325. MidiEventHolder (const MidiMessage& message);
  19326. };
  19327. /** Clears the sequence. */
  19328. void clear();
  19329. /** Returns the number of events in the sequence. */
  19330. int getNumEvents() const;
  19331. /** Returns a pointer to one of the events. */
  19332. MidiEventHolder* getEventPointer (const int index) const;
  19333. /** Returns the time of the note-up that matches the note-on at this index.
  19334. If the event at this index isn't a note-on, it'll just return 0.
  19335. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19336. */
  19337. double getTimeOfMatchingKeyUp (const int index) const;
  19338. /** Returns the index of the note-up that matches the note-on at this index.
  19339. If the event at this index isn't a note-on, it'll just return -1.
  19340. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19341. */
  19342. int getIndexOfMatchingKeyUp (const int index) const;
  19343. /** Returns the index of an event. */
  19344. int getIndexOf (MidiEventHolder* const event) const;
  19345. /** Returns the index of the first event on or after the given timestamp.
  19346. If the time is beyond the end of the sequence, this will return the
  19347. number of events.
  19348. */
  19349. int getNextIndexAtTime (const double timeStamp) const;
  19350. /** Returns the timestamp of the first event in the sequence.
  19351. @see getEndTime
  19352. */
  19353. double getStartTime() const;
  19354. /** Returns the timestamp of the last event in the sequence.
  19355. @see getStartTime
  19356. */
  19357. double getEndTime() const;
  19358. /** Returns the timestamp of the event at a given index.
  19359. If the index is out-of-range, this will return 0.0
  19360. */
  19361. double getEventTime (const int index) const;
  19362. /** Inserts a midi message into the sequence.
  19363. The index at which the new message gets inserted will depend on its timestamp,
  19364. because the sequence is kept sorted.
  19365. Remember to call updateMatchedPairs() after adding note-on events.
  19366. @param newMessage the new message to add (an internal copy will be made)
  19367. @param timeAdjustment an optional value to add to the timestamp of the message
  19368. that will be inserted
  19369. @see updateMatchedPairs
  19370. */
  19371. void addEvent (const MidiMessage& newMessage,
  19372. double timeAdjustment = 0);
  19373. /** Deletes one of the events in the sequence.
  19374. Remember to call updateMatchedPairs() after removing events.
  19375. @param index the index of the event to delete
  19376. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19377. if the event you're removing is a note-on
  19378. */
  19379. void deleteEvent (const int index,
  19380. const bool deleteMatchingNoteUp);
  19381. /** Merges another sequence into this one.
  19382. Remember to call updateMatchedPairs() after using this method.
  19383. @param other the sequence to add from
  19384. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19385. as they are read from the other sequence
  19386. @param firstAllowableDestTime events will not be added if their time is earlier
  19387. than this time. (This is after their time has been adjusted
  19388. by the timeAdjustmentDelta)
  19389. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19390. or greater than this time. (This is after their time has
  19391. been adjusted by the timeAdjustmentDelta)
  19392. */
  19393. void addSequence (const MidiMessageSequence& other,
  19394. double timeAdjustmentDelta,
  19395. double firstAllowableDestTime,
  19396. double endOfAllowableDestTimes);
  19397. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19398. Call this after moving messages about or deleting/adding messages, and it
  19399. will scan the list and make sure all the note-offs in the MidiEventHolder
  19400. structures are pointing at the correct ones.
  19401. */
  19402. void updateMatchedPairs();
  19403. /** Copies all the messages for a particular midi channel to another sequence.
  19404. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19405. @param destSequence the sequence that the chosen events should be copied to
  19406. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19407. channel) will also be copied across.
  19408. @see extractSysExMessages
  19409. */
  19410. void extractMidiChannelMessages (const int channelNumberToExtract,
  19411. MidiMessageSequence& destSequence,
  19412. const bool alsoIncludeMetaEvents) const;
  19413. /** Copies all midi sys-ex messages to another sequence.
  19414. @param destSequence this is the sequence to which any sys-exes in this sequence
  19415. will be added
  19416. @see extractMidiChannelMessages
  19417. */
  19418. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19419. /** Removes any messages in this sequence that have a specific midi channel.
  19420. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19421. */
  19422. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19423. /** Removes any sys-ex messages from this sequence.
  19424. */
  19425. void deleteSysExMessages();
  19426. /** Adds an offset to the timestamps of all events in the sequence.
  19427. @param deltaTime the amount to add to each timestamp.
  19428. */
  19429. void addTimeToMessages (const double deltaTime);
  19430. /** Scans through the sequence to determine the state of any midi controllers at
  19431. a given time.
  19432. This will create a sequence of midi controller changes that can be
  19433. used to set all midi controllers to the state they would be in at the
  19434. specified time within this sequence.
  19435. As well as controllers, it will also recreate the midi program number
  19436. and pitch bend position.
  19437. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19438. for other channels will be ignored.
  19439. @param time the time at which you want to find out the state - there are
  19440. no explicit units for this time measurement, it's the same units
  19441. as used for the timestamps of the messages
  19442. @param resultMessages an array to which midi controller-change messages will be added. This
  19443. will be the minimum number of controller changes to recreate the
  19444. state at the required time.
  19445. */
  19446. void createControllerUpdatesForTime (const int channelNumber,
  19447. const double time,
  19448. OwnedArray<MidiMessage>& resultMessages);
  19449. juce_UseDebuggingNewOperator
  19450. /** @internal */
  19451. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19452. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19453. private:
  19454. friend class MidiComparator;
  19455. friend class MidiFile;
  19456. OwnedArray <MidiEventHolder> list;
  19457. void sort();
  19458. };
  19459. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19460. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19461. /**
  19462. Reads/writes standard midi format files.
  19463. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19464. can then get the individual midi tracks from it using the getTrack() method.
  19465. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19466. to it using the addTrack() method, and then call its writeTo() method to stream
  19467. it out.
  19468. @see MidiMessageSequence
  19469. */
  19470. class JUCE_API MidiFile
  19471. {
  19472. public:
  19473. /** Creates an empty MidiFile object.
  19474. */
  19475. MidiFile() throw();
  19476. /** Destructor. */
  19477. ~MidiFile() throw();
  19478. /** Returns the number of tracks in the file.
  19479. @see getTrack, addTrack
  19480. */
  19481. int getNumTracks() const throw();
  19482. /** Returns a pointer to one of the tracks in the file.
  19483. @returns a pointer to the track, or 0 if the index is out-of-range
  19484. @see getNumTracks, addTrack
  19485. */
  19486. const MidiMessageSequence* getTrack (const int index) const throw();
  19487. /** Adds a midi track to the file.
  19488. This will make its own internal copy of the sequence that is passed-in.
  19489. @see getNumTracks, getTrack
  19490. */
  19491. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19492. /** Removes all midi tracks from the file.
  19493. @see getNumTracks
  19494. */
  19495. void clear() throw();
  19496. /** Returns the raw time format code that will be written to a stream.
  19497. After reading a midi file, this method will return the time-format that
  19498. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19499. or setSmpteTimeFormat() methods.
  19500. If the value returned is positive, it indicates the number of midi ticks
  19501. per quarter-note - see setTicksPerQuarterNote().
  19502. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19503. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19504. */
  19505. short getTimeFormat() const throw();
  19506. /** Sets the time format to use when this file is written to a stream.
  19507. If this is called, the file will be written as bars/beats using the
  19508. specified resolution, rather than SMPTE absolute times, as would be
  19509. used if setSmpteTimeFormat() had been called instead.
  19510. @param ticksPerQuarterNote e.g. 96, 960
  19511. @see setSmpteTimeFormat
  19512. */
  19513. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19514. /** Sets the time format to use when this file is written to a stream.
  19515. If this is called, the file will be written using absolute times, rather
  19516. than bars/beats as would be the case if setTicksPerBeat() had been called
  19517. instead.
  19518. @param framesPerSecond must be 24, 25, 29 or 30
  19519. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19520. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19521. timing, setSmpteTimeFormat (25, 40)
  19522. @see setTicksPerBeat
  19523. */
  19524. void setSmpteTimeFormat (const int framesPerSecond,
  19525. const int subframeResolution) throw();
  19526. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19527. Useful for finding the positions of all the tempo changes in a file.
  19528. @param tempoChangeEvents a list to which all the events will be added
  19529. */
  19530. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19531. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19532. Useful for finding the positions of all the tempo changes in a file.
  19533. @param timeSigEvents a list to which all the events will be added
  19534. */
  19535. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19536. /** Returns the latest timestamp in any of the tracks.
  19537. (Useful for finding the length of the file).
  19538. */
  19539. double getLastTimestamp() const;
  19540. /** Reads a midi file format stream.
  19541. After calling this, you can get the tracks that were read from the file by using the
  19542. getNumTracks() and getTrack() methods.
  19543. The timestamps of the midi events in the tracks will represent their positions in
  19544. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19545. method.
  19546. @returns true if the stream was read successfully
  19547. */
  19548. bool readFrom (InputStream& sourceStream);
  19549. /** Writes the midi tracks as a standard midi file.
  19550. @returns true if the operation succeeded.
  19551. */
  19552. bool writeTo (OutputStream& destStream);
  19553. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19554. This will use the midi time format and tempo/time signature info in the
  19555. tracks to convert all the timestamps to absolute values in seconds.
  19556. */
  19557. void convertTimestampTicksToSeconds();
  19558. juce_UseDebuggingNewOperator
  19559. /** @internal */
  19560. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19561. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19562. private:
  19563. MidiMessageSequence* tracks [128];
  19564. short numTracks, timeFormat;
  19565. MidiFile (const MidiFile&);
  19566. const MidiFile& operator= (const MidiFile&);
  19567. void readNextTrack (const char* data, int size);
  19568. void writeTrack (OutputStream& mainOut, const int trackNum);
  19569. };
  19570. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19571. /********* End of inlined file: juce_MidiFile.h *********/
  19572. #endif
  19573. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19574. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  19575. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19576. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19577. class MidiKeyboardState;
  19578. /**
  19579. Receives events from a MidiKeyboardState object.
  19580. @see MidiKeyboardState
  19581. */
  19582. class JUCE_API MidiKeyboardStateListener
  19583. {
  19584. public:
  19585. MidiKeyboardStateListener() throw() {}
  19586. virtual ~MidiKeyboardStateListener() {}
  19587. /** Called when one of the MidiKeyboardState's keys is pressed.
  19588. This will be called synchronously when the state is either processing a
  19589. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19590. when a note is being played with its MidiKeyboardState::noteOn() method.
  19591. Note that this callback could happen from an audio callback thread, so be
  19592. careful not to block, and avoid any UI activity in the callback.
  19593. */
  19594. virtual void handleNoteOn (MidiKeyboardState* source,
  19595. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19596. /** Called when one of the MidiKeyboardState's keys is released.
  19597. This will be called synchronously when the state is either processing a
  19598. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19599. when a note is being played with its MidiKeyboardState::noteOff() method.
  19600. Note that this callback could happen from an audio callback thread, so be
  19601. careful not to block, and avoid any UI activity in the callback.
  19602. */
  19603. virtual void handleNoteOff (MidiKeyboardState* source,
  19604. int midiChannel, int midiNoteNumber) = 0;
  19605. };
  19606. /**
  19607. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19608. This object can parse a stream of midi events, using them to update its idea
  19609. of which keys are pressed for each individiual midi channel.
  19610. When keys go up or down, it can broadcast these events to listener objects.
  19611. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19612. methods, and midi messages for these events will be merged into the
  19613. midi stream that gets processed by processNextMidiBuffer().
  19614. */
  19615. class JUCE_API MidiKeyboardState
  19616. {
  19617. public:
  19618. MidiKeyboardState();
  19619. ~MidiKeyboardState();
  19620. /** Resets the state of the object.
  19621. All internal data for all the channels is reset, but no events are sent as a
  19622. result.
  19623. If you want to release any keys that are currently down, and to send out note-up
  19624. midi messages for this, use the allNotesOff() method instead.
  19625. */
  19626. void reset();
  19627. /** Returns true if the given midi key is currently held down for the given midi channel.
  19628. The channel number must be between 1 and 16. If you want to see if any notes are
  19629. on for a range of channels, use the isNoteOnForChannels() method.
  19630. */
  19631. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19632. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19633. The channel mask has a bit set for each midi channel you want to test for - bit
  19634. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19635. If a note is on for at least one of the specified channels, this returns true.
  19636. */
  19637. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19638. /** Turns a specified note on.
  19639. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19640. next call to processNextMidiBuffer().
  19641. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19642. gone down.
  19643. */
  19644. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19645. /** Turns a specified note off.
  19646. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  19647. next call to processNextMidiBuffer().
  19648. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19649. gone up.
  19650. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19651. */
  19652. void noteOff (const int midiChannel, const int midiNoteNumber);
  19653. /** This will turn off any currently-down notes for the given midi channel.
  19654. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19655. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19656. and events being added to the midi stream.
  19657. */
  19658. void allNotesOff (const int midiChannel);
  19659. /** Looks at a key-up/down event and uses it to update the state of this object.
  19660. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19661. instead.
  19662. */
  19663. void processNextMidiEvent (const MidiMessage& message);
  19664. /** Scans a midi stream for up/down events and adds its own events to it.
  19665. This will look for any up/down events and use them to update the internal state,
  19666. synchronously making suitable callbacks to the listeners.
  19667. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19668. and noteOff() calls will be added into the buffer.
  19669. Only the section of the buffer whose timestamps are between startSample and
  19670. (startSample + numSamples) will be affected, and any events added will be placed
  19671. between these times.
  19672. If you're going to use this method, you'll need to keep calling it regularly for
  19673. it to work satisfactorily.
  19674. To process a single midi event at a time, use the processNextMidiEvent() method
  19675. instead.
  19676. */
  19677. void processNextMidiBuffer (MidiBuffer& buffer,
  19678. const int startSample,
  19679. const int numSamples,
  19680. const bool injectIndirectEvents);
  19681. /** Registers a listener for callbacks when keys go up or down.
  19682. @see removeListener
  19683. */
  19684. void addListener (MidiKeyboardStateListener* const listener) throw();
  19685. /** Deregisters a listener.
  19686. @see addListener
  19687. */
  19688. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19689. juce_UseDebuggingNewOperator
  19690. private:
  19691. CriticalSection lock;
  19692. uint16 noteStates [128];
  19693. MidiBuffer eventsToAdd;
  19694. VoidArray listeners;
  19695. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  19696. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  19697. MidiKeyboardState (const MidiKeyboardState&);
  19698. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  19699. };
  19700. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19701. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  19702. #endif
  19703. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  19704. #endif
  19705. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19706. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  19707. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19708. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19709. /********* Start of inlined file: juce_MidiInput.h *********/
  19710. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  19711. #define __JUCE_MIDIINPUT_JUCEHEADER__
  19712. class MidiInput;
  19713. /**
  19714. Receives midi messages from a midi input device.
  19715. This class is overridden to handle incoming midi messages. See the MidiInput
  19716. class for more details.
  19717. @see MidiInput
  19718. */
  19719. class JUCE_API MidiInputCallback
  19720. {
  19721. public:
  19722. /** Destructor. */
  19723. virtual ~MidiInputCallback() {}
  19724. /** Receives an incoming message.
  19725. A MidiInput object will call this method when a midi event arrives. It'll be
  19726. called on a high-priority system thread, so avoid doing anything time-consuming
  19727. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  19728. for queueing incoming messages for use later.
  19729. @param source the MidiInput object that generated the message
  19730. @param message the incoming message. The message's timestamp is set to a value
  19731. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  19732. time when the message arrived.
  19733. */
  19734. virtual void handleIncomingMidiMessage (MidiInput* source,
  19735. const MidiMessage& message) = 0;
  19736. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  19737. If a long sysex message is broken up into multiple packets, this callback is made
  19738. for each packet that arrives until the message is finished, at which point
  19739. the normal handleIncomingMidiMessage() callback will be made with the entire
  19740. message.
  19741. The message passed in will contain the start of a sysex, but won't be finished
  19742. with the terminating 0xf7 byte.
  19743. */
  19744. virtual void handlePartialSysexMessage (MidiInput* source,
  19745. const uint8* messageData,
  19746. const int numBytesSoFar,
  19747. const double timestamp)
  19748. {
  19749. // (this bit is just to avoid compiler warnings about unused variables)
  19750. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  19751. }
  19752. };
  19753. /**
  19754. Represents a midi input device.
  19755. To create one of these, use the static getDevices() method to find out what inputs are
  19756. available, and then use the openDevice() method to try to open one.
  19757. @see MidiOutput
  19758. */
  19759. class JUCE_API MidiInput
  19760. {
  19761. public:
  19762. /** Returns a list of the available midi input devices.
  19763. You can open one of the devices by passing its index into the
  19764. openDevice() method.
  19765. @see getDefaultDeviceIndex, openDevice
  19766. */
  19767. static const StringArray getDevices();
  19768. /** Returns the index of the default midi input device to use.
  19769. This refers to the index in the list returned by getDevices().
  19770. */
  19771. static int getDefaultDeviceIndex();
  19772. /** Tries to open one of the midi input devices.
  19773. This will return a MidiInput object if it manages to open it. You can then
  19774. call start() and stop() on this device, and delete it when no longer needed.
  19775. If the device can't be opened, this will return a null pointer.
  19776. @param deviceIndex the index of a device from the list returned by getDevices()
  19777. @param callback the object that will receive the midi messages from this device.
  19778. @see MidiInputCallback, getDevices
  19779. */
  19780. static MidiInput* openDevice (int deviceIndex,
  19781. MidiInputCallback* callback);
  19782. #if JUCE_LINUX || DOXYGEN
  19783. /** LINUX ONLY - This will try to create a new midi input device.
  19784. This will attempt to create a new midi input device with the specified name,
  19785. for other apps to connect to.
  19786. Returns 0 if a device can't be created.
  19787. @param deviceName the name to use for the new device
  19788. @param callback the object that will receive the midi messages from this device.
  19789. */
  19790. static MidiInput* createNewDevice (const String& deviceName,
  19791. MidiInputCallback* callback);
  19792. #endif
  19793. /** Destructor. */
  19794. virtual ~MidiInput();
  19795. /** Returns the name of this device.
  19796. */
  19797. virtual const String getName() const throw() { return name; }
  19798. /** Allows you to set a custom name for the device, in case you don't like the name
  19799. it was given when created.
  19800. */
  19801. virtual void setName (const String& newName) throw() { name = newName; }
  19802. /** Starts the device running.
  19803. After calling this, the device will start sending midi messages to the
  19804. MidiInputCallback object that was specified when the openDevice() method
  19805. was called.
  19806. @see stop
  19807. */
  19808. virtual void start();
  19809. /** Stops the device running.
  19810. @see start
  19811. */
  19812. virtual void stop();
  19813. juce_UseDebuggingNewOperator
  19814. protected:
  19815. String name;
  19816. void* internal;
  19817. MidiInput (const String& name);
  19818. MidiInput (const MidiInput&);
  19819. };
  19820. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  19821. /********* End of inlined file: juce_MidiInput.h *********/
  19822. /**
  19823. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  19824. processing by a block-based audio callback.
  19825. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  19826. so it can easily use a midi input or keyboard component as its source.
  19827. @see MidiMessage, MidiInput
  19828. */
  19829. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  19830. public MidiInputCallback
  19831. {
  19832. public:
  19833. /** Creates a MidiMessageCollector. */
  19834. MidiMessageCollector();
  19835. /** Destructor. */
  19836. ~MidiMessageCollector();
  19837. /** Clears any messages from the queue.
  19838. You need to call this method before starting to use the collector, so that
  19839. it knows the correct sample rate to use.
  19840. */
  19841. void reset (const double sampleRate);
  19842. /** Takes an incoming real-time message and adds it to the queue.
  19843. The message's timestamp is taken, and it will be ready for retrieval as part
  19844. of the block returned by the next call to removeNextBlockOfMessages().
  19845. This method is fully thread-safe when overlapping calls are made with
  19846. removeNextBlockOfMessages().
  19847. */
  19848. void addMessageToQueue (const MidiMessage& message);
  19849. /** Removes all the pending messages from the queue as a buffer.
  19850. This will also correct the messages' timestamps to make sure they're in
  19851. the range 0 to numSamples - 1.
  19852. This call should be made regularly by something like an audio processing
  19853. callback, because the time that it happens is used in calculating the
  19854. midi event positions.
  19855. This method is fully thread-safe when overlapping calls are made with
  19856. addMessageToQueue().
  19857. */
  19858. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  19859. const int numSamples);
  19860. /** @internal */
  19861. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  19862. /** @internal */
  19863. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  19864. /** @internal */
  19865. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  19866. juce_UseDebuggingNewOperator
  19867. private:
  19868. double lastCallbackTime;
  19869. CriticalSection midiCallbackLock;
  19870. MidiBuffer incomingMessages;
  19871. double sampleRate;
  19872. MidiMessageCollector (const MidiMessageCollector&);
  19873. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  19874. };
  19875. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  19876. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  19877. #endif
  19878. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19879. #endif
  19880. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19881. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  19882. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19883. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19884. /**
  19885. A set of routines to convert buffers of 32-bit floating point data to and from
  19886. various integer formats.
  19887. */
  19888. class JUCE_API AudioDataConverters
  19889. {
  19890. public:
  19891. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19892. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  19893. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19894. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  19895. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19896. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19897. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19898. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  19899. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19900. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  19901. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19902. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  19903. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19904. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19905. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19906. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  19907. enum DataFormat
  19908. {
  19909. int16LE,
  19910. int16BE,
  19911. int24LE,
  19912. int24BE,
  19913. int32LE,
  19914. int32BE,
  19915. float32LE,
  19916. float32BE,
  19917. };
  19918. static void convertFloatToFormat (const DataFormat destFormat,
  19919. const float* source, void* dest, int numSamples);
  19920. static void convertFormatToFloat (const DataFormat sourceFormat,
  19921. const void* source, float* dest, int numSamples);
  19922. static void interleaveSamples (const float** source, float* dest,
  19923. const int numSamples, const int numChannels);
  19924. static void deinterleaveSamples (const float* source, float** dest,
  19925. const int numSamples, const int numChannels);
  19926. };
  19927. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  19928. /********* End of inlined file: juce_AudioDataConverters.h *********/
  19929. #endif
  19930. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19931. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  19932. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19933. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  19934. class AudioFormatReader;
  19935. class AudioFormatWriter;
  19936. /**
  19937. A multi-channel buffer of 32-bit floating point audio samples.
  19938. */
  19939. class JUCE_API AudioSampleBuffer
  19940. {
  19941. public:
  19942. /** Creates a buffer with a specified number of channels and samples.
  19943. The contents of the buffer will initially be undefined, so use clear() to
  19944. set all the samples to zero.
  19945. The buffer will allocate its memory internally, and this will be released
  19946. when the buffer is deleted.
  19947. */
  19948. AudioSampleBuffer (const int numChannels,
  19949. const int numSamples) throw();
  19950. /** Creates a buffer using a pre-allocated block of memory.
  19951. Note that if the buffer is resized or its number of channels is changed, it
  19952. will re-allocate memory internally and copy the existing data to this new area,
  19953. so it will then stop directly addressing this memory.
  19954. @param dataToReferTo a pre-allocated array containing pointers to the data
  19955. for each channel that should be used by this buffer. The
  19956. buffer will only refer to this memory, it won't try to delete
  19957. it when the buffer is deleted or resized.
  19958. @param numChannels the number of channels to use - this must correspond to the
  19959. number of elements in the array passed in
  19960. @param numSamples the number of samples to use - this must correspond to the
  19961. size of the arrays passed in
  19962. */
  19963. AudioSampleBuffer (float** dataToReferTo,
  19964. const int numChannels,
  19965. const int numSamples) throw();
  19966. /** Copies another buffer.
  19967. This buffer will make its own copy of the other's data, unless the buffer was created
  19968. using an external data buffer, in which case boths buffers will just point to the same
  19969. shared block of data.
  19970. */
  19971. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  19972. /** Copies another buffer onto this one.
  19973. This buffer's size will be changed to that of the other buffer.
  19974. */
  19975. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  19976. /** Destructor.
  19977. This will free any memory allocated by the buffer.
  19978. */
  19979. virtual ~AudioSampleBuffer() throw();
  19980. /** Returns the number of channels of audio data that this buffer contains.
  19981. @see getSampleData
  19982. */
  19983. int getNumChannels() const throw() { return numChannels; }
  19984. /** Returns the number of samples allocated in each of the buffer's channels.
  19985. @see getSampleData
  19986. */
  19987. int getNumSamples() const throw() { return size; }
  19988. /** Returns a pointer to a sample in one of the buffer's channels.
  19989. For speed, this doesn't check whether the channel and sample number
  19990. are legal, so be careful when using it!
  19991. */
  19992. float* getSampleData (const int channelNumber,
  19993. const int sampleOffset = 0) const throw();
  19994. /** Chages the buffer's size or number of channels.
  19995. This can expand or contract the buffer's length, and add or remove channels.
  19996. If keepExistingContent is true, it will try to preserve as much of the
  19997. old data as it can in the new buffer.
  19998. If clearExtraSpace is true, then any extra channels or space that is
  19999. allocated will be also be cleared. If false, then this space is left
  20000. uninitialised.
  20001. If avoidReallocating is true, then changing the buffer's size won't reduce the
  20002. amount of memory that is currently allocated (but it will still increase it if
  20003. the new size is bigger than the amount it currently has). If this is false, then
  20004. a new allocation will be done so that the buffer uses takes up the minimum amount
  20005. of memory that it needs.
  20006. */
  20007. void setSize (const int newNumChannels,
  20008. const int newNumSamples,
  20009. const bool keepExistingContent = false,
  20010. const bool clearExtraSpace = false,
  20011. const bool avoidReallocating = false) throw();
  20012. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  20013. There's also a constructor that lets you specify arrays like this, but this
  20014. lets you change the channels dynamically.
  20015. Note that if the buffer is resized or its number of channels is changed, it
  20016. will re-allocate memory internally and copy the existing data to this new area,
  20017. so it will then stop directly addressing this memory.
  20018. @param dataToReferTo a pre-allocated array containing pointers to the data
  20019. for each channel that should be used by this buffer. The
  20020. buffer will only refer to this memory, it won't try to delete
  20021. it when the buffer is deleted or resized.
  20022. @param numChannels the number of channels to use - this must correspond to the
  20023. number of elements in the array passed in
  20024. @param numSamples the number of samples to use - this must correspond to the
  20025. size of the arrays passed in
  20026. */
  20027. void setDataToReferTo (float** dataToReferTo,
  20028. const int numChannels,
  20029. const int numSamples) throw();
  20030. /** Clears all the samples in all channels. */
  20031. void clear() throw();
  20032. /** Clears a specified region of all the channels.
  20033. For speed, this doesn't check whether the channel and sample number
  20034. are in-range, so be careful!
  20035. */
  20036. void clear (const int startSample,
  20037. const int numSamples) throw();
  20038. /** Clears a specified region of just one channel.
  20039. For speed, this doesn't check whether the channel and sample number
  20040. are in-range, so be careful!
  20041. */
  20042. void clear (const int channel,
  20043. const int startSample,
  20044. const int numSamples) throw();
  20045. /** Applies a gain multiple to a region of one channel.
  20046. For speed, this doesn't check whether the channel and sample number
  20047. are in-range, so be careful!
  20048. */
  20049. void applyGain (const int channel,
  20050. const int startSample,
  20051. int numSamples,
  20052. const float gain) throw();
  20053. /** Applies a gain multiple to a region of all the channels.
  20054. For speed, this doesn't check whether the sample numbers
  20055. are in-range, so be careful!
  20056. */
  20057. void applyGain (const int startSample,
  20058. const int numSamples,
  20059. const float gain) throw();
  20060. /** Applies a range of gains to a region of a channel.
  20061. The gain that is applied to each sample will vary from
  20062. startGain on the first sample to endGain on the last Sample,
  20063. so it can be used to do basic fades.
  20064. For speed, this doesn't check whether the sample numbers
  20065. are in-range, so be careful!
  20066. */
  20067. void applyGainRamp (const int channel,
  20068. const int startSample,
  20069. int numSamples,
  20070. float startGain,
  20071. float endGain) throw();
  20072. /** Adds samples from another buffer to this one.
  20073. @param destChannel the channel within this buffer to add the samples to
  20074. @param destStartSample the start sample within this buffer's channel
  20075. @param source the source buffer to add from
  20076. @param sourceChannel the channel within the source buffer to read from
  20077. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20078. @param numSamples the number of samples to process
  20079. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20080. added to this buffer's samples
  20081. @see copyFrom
  20082. */
  20083. void addFrom (const int destChannel,
  20084. const int destStartSample,
  20085. const AudioSampleBuffer& source,
  20086. const int sourceChannel,
  20087. const int sourceStartSample,
  20088. int numSamples,
  20089. const float gainToApplyToSource = 1.0f) throw();
  20090. /** Adds samples from an array of floats to one of the channels.
  20091. @param destChannel the channel within this buffer to add the samples to
  20092. @param destStartSample the start sample within this buffer's channel
  20093. @param source the source data to use
  20094. @param numSamples the number of samples to process
  20095. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20096. added to this buffer's samples
  20097. @see copyFrom
  20098. */
  20099. void addFrom (const int destChannel,
  20100. const int destStartSample,
  20101. const float* source,
  20102. int numSamples,
  20103. const float gainToApplyToSource = 1.0f) throw();
  20104. /** Adds samples from an array of floats, applying a gain ramp to them.
  20105. @param destChannel the channel within this buffer to add the samples to
  20106. @param destStartSample the start sample within this buffer's channel
  20107. @param source the source data to use
  20108. @param numSamples the number of samples to process
  20109. @param startGain the gain to apply to the first sample (this is multiplied with
  20110. the source samples before they are added to this buffer)
  20111. @param endGain the gain to apply to the final sample. The gain is linearly
  20112. interpolated between the first and last samples.
  20113. */
  20114. void addFromWithRamp (const int destChannel,
  20115. const int destStartSample,
  20116. const float* source,
  20117. int numSamples,
  20118. float startGain,
  20119. float endGain) throw();
  20120. /** Copies samples from another buffer to this one.
  20121. @param destChannel the channel within this buffer to copy the samples to
  20122. @param destStartSample the start sample within this buffer's channel
  20123. @param source the source buffer to read from
  20124. @param sourceChannel the channel within the source buffer to read from
  20125. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20126. @param numSamples the number of samples to process
  20127. @see addFrom
  20128. */
  20129. void copyFrom (const int destChannel,
  20130. const int destStartSample,
  20131. const AudioSampleBuffer& source,
  20132. const int sourceChannel,
  20133. const int sourceStartSample,
  20134. int numSamples) throw();
  20135. /** Copies samples from an array of floats into one of the channels.
  20136. @param destChannel the channel within this buffer to copy the samples to
  20137. @param destStartSample the start sample within this buffer's channel
  20138. @param source the source buffer to read from
  20139. @param numSamples the number of samples to process
  20140. @see addFrom
  20141. */
  20142. void copyFrom (const int destChannel,
  20143. const int destStartSample,
  20144. const float* source,
  20145. int numSamples) throw();
  20146. /** Finds the highest and lowest sample values in a given range.
  20147. @param channel the channel to read from
  20148. @param startSample the start sample within the channel
  20149. @param numSamples the number of samples to check
  20150. @param minVal on return, the lowest value that was found
  20151. @param maxVal on return, the highest value that was found
  20152. */
  20153. void findMinMax (const int channel,
  20154. const int startSample,
  20155. int numSamples,
  20156. float& minVal,
  20157. float& maxVal) const throw();
  20158. /** Finds the highest absolute sample value within a region of a channel.
  20159. */
  20160. float getMagnitude (const int channel,
  20161. const int startSample,
  20162. const int numSamples) const throw();
  20163. /** Finds the highest absolute sample value within a region on all channels.
  20164. */
  20165. float getMagnitude (const int startSample,
  20166. const int numSamples) const throw();
  20167. /** Returns the root mean squared level for a region of a channel.
  20168. */
  20169. float getRMSLevel (const int channel,
  20170. const int startSample,
  20171. const int numSamples) const throw();
  20172. /** Fills a section of the buffer using an AudioReader as its source.
  20173. This will convert the reader's fixed- or floating-point data to
  20174. the buffer's floating-point format, and will try to intelligently
  20175. cope with mismatches between the number of channels in the reader
  20176. and the buffer.
  20177. @see writeToAudioWriter
  20178. */
  20179. void readFromAudioReader (AudioFormatReader* reader,
  20180. const int startSample,
  20181. const int numSamples,
  20182. const int readerStartSample,
  20183. const bool useReaderLeftChan,
  20184. const bool useReaderRightChan) throw();
  20185. /** Writes a section of this buffer to an audio writer.
  20186. This saves you having to mess about with channels or floating/fixed
  20187. point conversion.
  20188. @see readFromAudioReader
  20189. */
  20190. void writeToAudioWriter (AudioFormatWriter* writer,
  20191. const int startSample,
  20192. const int numSamples) const throw();
  20193. juce_UseDebuggingNewOperator
  20194. private:
  20195. int numChannels, size, allocatedBytes;
  20196. float** channels;
  20197. float* allocatedData;
  20198. };
  20199. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20200. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20201. #endif
  20202. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20203. /********* Start of inlined file: juce_IIRFilter.h *********/
  20204. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20205. #define __JUCE_IIRFILTER_JUCEHEADER__
  20206. /**
  20207. An IIR filter that can perform low, high, or band-pass filtering on an
  20208. audio signal.
  20209. @see IIRFilterAudioSource
  20210. */
  20211. class JUCE_API IIRFilter
  20212. {
  20213. public:
  20214. /** Creates a filter.
  20215. Initially the filter is inactive, so will have no effect on samples that
  20216. you process with it. Use the appropriate method to turn it into the type
  20217. of filter needed.
  20218. */
  20219. IIRFilter() throw();
  20220. /** Creates a copy of another filter. */
  20221. IIRFilter (const IIRFilter& other) throw();
  20222. /** Destructor. */
  20223. ~IIRFilter() throw();
  20224. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20225. Note that this clears the processing state, but the type of filter and
  20226. its coefficients aren't changed. To put a filter into an inactive state, use
  20227. the makeInactive() method.
  20228. */
  20229. void reset() throw();
  20230. /** Performs the filter operation on the given set of samples.
  20231. */
  20232. void processSamples (float* const samples,
  20233. const int numSamples) throw();
  20234. /** Processes a single sample, without any locking or checking.
  20235. Use this if you need fast processing of a single value, but be aware that
  20236. this isn't thread-safe in the way that processSamples() is.
  20237. */
  20238. float processSingleSampleRaw (const float sample) throw();
  20239. /** Sets the filter up to act as a low-pass filter.
  20240. */
  20241. void makeLowPass (const double sampleRate,
  20242. const double frequency) throw();
  20243. /** Sets the filter up to act as a high-pass filter.
  20244. */
  20245. void makeHighPass (const double sampleRate,
  20246. const double frequency) throw();
  20247. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20248. The gain is a scale factor that the low frequencies are multiplied by, so values
  20249. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20250. attenuate them.
  20251. */
  20252. void makeLowShelf (const double sampleRate,
  20253. const double cutOffFrequency,
  20254. const double Q,
  20255. const float gainFactor) throw();
  20256. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20257. The gain is a scale factor that the high frequencies are multiplied by, so values
  20258. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20259. attenuate them.
  20260. */
  20261. void makeHighShelf (const double sampleRate,
  20262. const double cutOffFrequency,
  20263. const double Q,
  20264. const float gainFactor) throw();
  20265. /** Sets the filter up to act as a band pass filter centred around a
  20266. frequency, with a variable Q and gain.
  20267. The gain is a scale factor that the centre frequencies are multiplied by, so
  20268. values greater than 1.0 will boost the centre frequencies, values less than
  20269. 1.0 will attenuate them.
  20270. */
  20271. void makeBandPass (const double sampleRate,
  20272. const double centreFrequency,
  20273. const double Q,
  20274. const float gainFactor) throw();
  20275. /** Clears the filter's coefficients so that it becomes inactive.
  20276. */
  20277. void makeInactive() throw();
  20278. /** Makes this filter duplicate the set-up of another one.
  20279. */
  20280. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20281. juce_UseDebuggingNewOperator
  20282. protected:
  20283. CriticalSection processLock;
  20284. void setCoefficients (double c1, double c2, double c3,
  20285. double c4, double c5, double c6) throw();
  20286. bool active;
  20287. float coefficients[6];
  20288. float x1, x2, y1, y2;
  20289. // (use the copyCoefficientsFrom() method instead of this operator)
  20290. const IIRFilter& operator= (const IIRFilter&);
  20291. };
  20292. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20293. /********* End of inlined file: juce_IIRFilter.h *********/
  20294. #endif
  20295. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20296. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20297. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20298. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20299. /**
  20300. A subclass of AudioPlayHead can supply information about the position and
  20301. status of a moving play head during audio playback.
  20302. One of these can be supplied to an AudioProcessor object so that it can find
  20303. out about the position of the audio that it is rendering.
  20304. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20305. */
  20306. class JUCE_API AudioPlayHead
  20307. {
  20308. protected:
  20309. AudioPlayHead() {}
  20310. public:
  20311. virtual ~AudioPlayHead() {}
  20312. /** Frame rate types. */
  20313. enum FrameRateType
  20314. {
  20315. fps24 = 0,
  20316. fps25 = 1,
  20317. fps2997 = 2,
  20318. fps30 = 3,
  20319. fps2997drop = 4,
  20320. fps30drop = 5,
  20321. fpsUnknown = 99
  20322. };
  20323. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20324. */
  20325. struct CurrentPositionInfo
  20326. {
  20327. /** The tempo in BPM */
  20328. double bpm;
  20329. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20330. int timeSigNumerator;
  20331. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20332. int timeSigDenominator;
  20333. /** The current play position, in seconds from the start of the edit. */
  20334. double timeInSeconds;
  20335. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20336. double editOriginTime;
  20337. /** The current play position in pulses-per-quarter-note.
  20338. This is the number of quarter notes since the edit start.
  20339. */
  20340. double ppqPosition;
  20341. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20342. This is the number of quarter notes from the start of the edit to the
  20343. start of the current bar.
  20344. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20345. it's not available, the value will be 0.
  20346. */
  20347. double ppqPositionOfLastBarStart;
  20348. /** The video frame rate, if applicable. */
  20349. FrameRateType frameRate;
  20350. /** True if the transport is currently playing. */
  20351. bool isPlaying;
  20352. /** True if the transport is currently recording.
  20353. (When isRecording is true, then isPlaying will also be true).
  20354. */
  20355. bool isRecording;
  20356. };
  20357. /** Fills-in the given structure with details about the transport's
  20358. position at the start of the current processing block.
  20359. */
  20360. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20361. };
  20362. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20363. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20364. #endif
  20365. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20366. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20367. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20368. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20369. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20370. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20371. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20372. class AudioProcessor;
  20373. /**
  20374. Base class for the component that acts as the GUI for an AudioProcessor.
  20375. Derive your editor component from this class, and create an instance of it
  20376. by overriding the AudioProcessor::createEditor() method.
  20377. @see AudioProcessor, GenericAudioProcessorEditor
  20378. */
  20379. class JUCE_API AudioProcessorEditor : public Component
  20380. {
  20381. protected:
  20382. /** Creates an editor for the specified processor.
  20383. */
  20384. AudioProcessorEditor (AudioProcessor* const owner);
  20385. public:
  20386. /** Destructor. */
  20387. ~AudioProcessorEditor();
  20388. /** Returns a pointer to the processor that this editor represents. */
  20389. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20390. private:
  20391. AudioProcessor* const owner;
  20392. };
  20393. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20394. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20395. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20396. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20397. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20398. class AudioProcessor;
  20399. /**
  20400. Base class for listeners that want to know about changes to an AudioProcessor.
  20401. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20402. @see AudioProcessor
  20403. */
  20404. class JUCE_API AudioProcessorListener
  20405. {
  20406. public:
  20407. /** Destructor. */
  20408. virtual ~AudioProcessorListener() {}
  20409. /** Receives a callback when a parameter is changed.
  20410. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20411. many audio processors will change their parameter during their audio callback.
  20412. This means that not only has your handler code got to be completely thread-safe,
  20413. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20414. this event on your message thread, use this callback to trigger an AsyncUpdater
  20415. or ChangeBroadcaster which you can respond to on the message thread.
  20416. */
  20417. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20418. int parameterIndex,
  20419. float newValue) = 0;
  20420. /** Called to indicate that something else in the plugin has changed, like its
  20421. program, number of parameters, etc.
  20422. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20423. call it during their audio callback. This means that not only has your handler code
  20424. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20425. blocking. If you need to handle this event on your message thread, use this callback
  20426. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20427. message thread.
  20428. */
  20429. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20430. /** Indicates that a parameter change gesture has started.
  20431. E.g. if the user is dragging a slider, this would be called when they first
  20432. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20433. called when they release it.
  20434. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20435. call it during their audio callback. This means that not only has your handler code
  20436. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20437. blocking. If you need to handle this event on your message thread, use this callback
  20438. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20439. message thread.
  20440. @see audioProcessorParameterChangeGestureEnd
  20441. */
  20442. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20443. int parameterIndex);
  20444. /** Indicates that a parameter change gesture has finished.
  20445. E.g. if the user is dragging a slider, this would be called when they release
  20446. the mouse button.
  20447. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20448. call it during their audio callback. This means that not only has your handler code
  20449. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20450. blocking. If you need to handle this event on your message thread, use this callback
  20451. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20452. message thread.
  20453. @see audioPluginParameterChangeGestureStart
  20454. */
  20455. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20456. int parameterIndex);
  20457. };
  20458. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20459. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20460. /**
  20461. Base class for audio processing filters or plugins.
  20462. This is intended to act as a base class of audio filter that is general enough to
  20463. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20464. It is also used by the plugin hosting code as the wrapper around an instance
  20465. of a loaded plugin.
  20466. Derive your filter class from this base class, and if you're building a plugin,
  20467. you should implement a global function called createPluginFilter() which creates
  20468. and returns a new instance of your subclass.
  20469. */
  20470. class JUCE_API AudioProcessor
  20471. {
  20472. protected:
  20473. /** Constructor.
  20474. You can also do your initialisation tasks in the initialiseFilterInfo()
  20475. call, which will be made after this object has been created.
  20476. */
  20477. AudioProcessor();
  20478. public:
  20479. /** Destructor. */
  20480. virtual ~AudioProcessor();
  20481. /** Returns the name of this processor.
  20482. */
  20483. virtual const String getName() const = 0;
  20484. /** Called before playback starts, to let the filter prepare itself.
  20485. The sample rate is the target sample rate, and will remain constant until
  20486. playback stops.
  20487. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20488. samples that will be processed for each callback, but isn't any kind
  20489. of guarantee. The actual block sizes that the host uses may be different
  20490. each time the callback happens, and may be more or less than this value.
  20491. */
  20492. virtual void prepareToPlay (double sampleRate,
  20493. int estimatedSamplesPerBlock) = 0;
  20494. /** Called after playback has stopped, to let the filter free up any resources it
  20495. no longer needs.
  20496. */
  20497. virtual void releaseResources() = 0;
  20498. /** Renders the next block.
  20499. When this method is called, the buffer contains a number of channels which is
  20500. at least as great as the maximum number of input and output channels that
  20501. this filter is using. It will be filled with the filter's input data and
  20502. should be replaced with the filter's output.
  20503. So for example if your filter has 2 input channels and 4 output channels, then
  20504. the buffer will contain 4 channels, the first two being filled with the
  20505. input data. Your filter should read these, do its processing, and replace
  20506. the contents of all 4 channels with its output.
  20507. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20508. all filled with data, and your filter should overwrite the first 2 of these
  20509. with its output. But be VERY careful not to write anything to the last 3
  20510. channels, as these might be mapped to memory that the host assumes is read-only!
  20511. Note that if you have more outputs than inputs, then only those channels that
  20512. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20513. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20514. but the last two channels may contain garbage, so you should be careful not to
  20515. let this pass through without being overwritten or cleared.
  20516. Also note that the buffer may have more channels than are strictly necessary,
  20517. but your should only read/write from the ones that your filter is supposed to
  20518. be using.
  20519. The number of samples in these buffers is NOT guaranteed to be the same for every
  20520. callback, and may be more or less than the estimated value given to prepareToPlay().
  20521. Your code must be able to cope with variable-sized blocks, or you're going to get
  20522. clicks and crashes!
  20523. If the filter is receiving a midi input, then the midiMessages array will be filled
  20524. with the midi messages for this block. Each message's timestamp will indicate the
  20525. message's time, as a number of samples from the start of the block.
  20526. Any messages left in the midi buffer when this method has finished are assumed to
  20527. be the filter's midi output. This means that your filter should be careful to
  20528. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20529. Be very careful about what you do in this callback - it's going to be called by
  20530. the audio thread, so any kind of interaction with the UI is absolutely
  20531. out of the question. If you change a parameter in here and need to tell your UI to
  20532. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20533. the UI components register as listeners, and then call sendChangeMessage() inside the
  20534. processBlock() method to send out an asynchronous message. You could also use
  20535. the AsyncUpdater class in a similar way.
  20536. */
  20537. virtual void processBlock (AudioSampleBuffer& buffer,
  20538. MidiBuffer& midiMessages) = 0;
  20539. /** Returns the current AudioPlayHead object that should be used to find
  20540. out the state and position of the playhead.
  20541. You can call this from your processBlock() method, and use the AudioPlayHead
  20542. object to get the details about the time of the start of the block currently
  20543. being processed.
  20544. If the host hasn't supplied a playhead object, this will return 0.
  20545. */
  20546. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20547. /** Returns the current sample rate.
  20548. This can be called from your processBlock() method - it's not guaranteed
  20549. to be valid at any other time, and may return 0 if it's unknown.
  20550. */
  20551. double getSampleRate() const throw() { return sampleRate; }
  20552. /** Returns the current typical block size that is being used.
  20553. This can be called from your processBlock() method - it's not guaranteed
  20554. to be valid at any other time.
  20555. Remember it's not the ONLY block size that may be used when calling
  20556. processBlock, it's just the normal one. The actual block sizes used may be
  20557. larger or smaller than this, and will vary between successive calls.
  20558. */
  20559. int getBlockSize() const throw() { return blockSize; }
  20560. /** Returns the number of input channels that the host will be sending the filter.
  20561. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20562. number of channels that your filter would prefer to have, and this method lets
  20563. you know how many the host is actually using.
  20564. Note that this method is only valid during or after the prepareToPlay()
  20565. method call. Until that point, the number of channels will be unknown.
  20566. */
  20567. int getNumInputChannels() const throw() { return numInputChannels; }
  20568. /** Returns the number of output channels that the host will be sending the filter.
  20569. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20570. number of channels that your filter would prefer to have, and this method lets
  20571. you know how many the host is actually using.
  20572. Note that this method is only valid during or after the prepareToPlay()
  20573. method call. Until that point, the number of channels will be unknown.
  20574. */
  20575. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20576. /** Returns the name of one of the input channels, as returned by the host.
  20577. The host might not supply very useful names for channels, and this might be
  20578. something like "1", "2", "left", "right", etc.
  20579. */
  20580. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20581. /** Returns the name of one of the output channels, as returned by the host.
  20582. The host might not supply very useful names for channels, and this might be
  20583. something like "1", "2", "left", "right", etc.
  20584. */
  20585. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20586. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20587. virtual bool isInputChannelStereoPair (int index) const = 0;
  20588. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20589. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20590. /** This returns the number of samples delay that the filter imposes on the audio
  20591. passing through it.
  20592. The host will call this to find the latency - the filter itself should set this value
  20593. by calling setLatencySamples() as soon as it can during its initialisation.
  20594. */
  20595. int getLatencySamples() const throw() { return latencySamples; }
  20596. /** The filter should call this to set the number of samples delay that it introduces.
  20597. The filter should call this as soon as it can during initialisation, and can call it
  20598. later if the value changes.
  20599. */
  20600. void setLatencySamples (const int newLatency);
  20601. /** Returns true if the processor wants midi messages. */
  20602. virtual bool acceptsMidi() const = 0;
  20603. /** Returns true if the processor produces midi messages. */
  20604. virtual bool producesMidi() const = 0;
  20605. /** This returns a critical section that will automatically be locked while the host
  20606. is calling the processBlock() method.
  20607. Use it from your UI or other threads to lock access to variables that are used
  20608. by the process callback, but obviously be careful not to keep it locked for
  20609. too long, because that could cause stuttering playback. If you need to do something
  20610. that'll take a long time and need the processing to stop while it happens, use the
  20611. suspendProcessing() method instead.
  20612. @see suspendProcessing
  20613. */
  20614. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20615. /** Enables and disables the processing callback.
  20616. If you need to do something time-consuming on a thread and would like to make sure
  20617. the audio processing callback doesn't happen until you've finished, use this
  20618. to disable the callback and re-enable it again afterwards.
  20619. E.g.
  20620. @code
  20621. void loadNewPatch()
  20622. {
  20623. suspendProcessing (true);
  20624. ..do something that takes ages..
  20625. suspendProcessing (false);
  20626. }
  20627. @endcode
  20628. If the host tries to make an audio callback while processing is suspended, the
  20629. filter will return an empty buffer, but won't block the audio thread like it would
  20630. do if you use the getCallbackLock() critical section to synchronise access.
  20631. If you're going to use this, your processBlock() method must call isSuspended() and
  20632. check whether it's suspended or not. If it is, then it should skip doing any real
  20633. processing, either emitting silence or passing the input through unchanged.
  20634. @see getCallbackLock
  20635. */
  20636. void suspendProcessing (const bool shouldBeSuspended);
  20637. /** Returns true if processing is currently suspended.
  20638. @see suspendProcessing
  20639. */
  20640. bool isSuspended() const throw() { return suspended; }
  20641. /** A plugin can override this to be told when it should reset any playing voices.
  20642. The default implementation does nothing, but a host may call this to tell the
  20643. plugin that it should stop any tails or sounds that have been left running.
  20644. */
  20645. virtual void reset();
  20646. /** Returns true if the processor is being run in an offline mode for rendering.
  20647. If the processor is being run live on realtime signals, this returns false.
  20648. If the mode is unknown, this will assume it's realtime and return false.
  20649. This value may be unreliable until the prepareToPlay() method has been called,
  20650. and could change each time prepareToPlay() is called.
  20651. @see setNonRealtime()
  20652. */
  20653. bool isNonRealtime() const throw() { return nonRealtime; }
  20654. /** Called by the host to tell this processor whether it's being used in a non-realime
  20655. capacity for offline rendering or bouncing.
  20656. Whatever value is passed-in will be
  20657. */
  20658. void setNonRealtime (const bool isNonRealtime) throw();
  20659. /** Creates the filter's UI.
  20660. This can return 0 if you want a UI-less filter, in which case the host may create
  20661. a generic UI that lets the user twiddle the parameters directly.
  20662. If you do want to pass back a component, the component should be created and set to
  20663. the correct size before returning it.
  20664. Remember not to do anything silly like allowing your filter to keep a pointer to
  20665. the component that gets created - it could be deleted later without any warning, which
  20666. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  20667. The correct way to handle the connection between an editor component and its
  20668. filter is to use something like a ChangeBroadcaster so that the editor can
  20669. register itself as a listener, and be told when a change occurs. This lets them
  20670. safely unregister themselves when they are deleted.
  20671. Here are a few things to bear in mind when writing an editor:
  20672. - Initially there won't be an editor, until the user opens one, or they might
  20673. not open one at all. Your filter mustn't rely on it being there.
  20674. - An editor object may be deleted and a replacement one created again at any time.
  20675. - It's safe to assume that an editor will be deleted before its filter.
  20676. */
  20677. virtual AudioProcessorEditor* createEditor() = 0;
  20678. /** Returns the active editor, if there is one.
  20679. Bear in mind this can return 0, even if an editor has previously been
  20680. opened.
  20681. */
  20682. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  20683. /** Returns the active editor, or if there isn't one, it will create one.
  20684. This may call createEditor() internally to create the component.
  20685. */
  20686. AudioProcessorEditor* createEditorIfNeeded();
  20687. /** This must return the correct value immediately after the object has been
  20688. created, and mustn't change the number of parameters later.
  20689. */
  20690. virtual int getNumParameters() = 0;
  20691. /** Returns the name of a particular parameter. */
  20692. virtual const String getParameterName (int parameterIndex) = 0;
  20693. /** Called by the host to find out the value of one of the filter's parameters.
  20694. The host will expect the value returned to be between 0 and 1.0.
  20695. This could be called quite frequently, so try to make your code efficient.
  20696. It's also likely to be called by non-UI threads, so the code in here should
  20697. be thread-aware.
  20698. */
  20699. virtual float getParameter (int parameterIndex) = 0;
  20700. /** Returns the value of a parameter as a text string. */
  20701. virtual const String getParameterText (int parameterIndex) = 0;
  20702. /** The host will call this method to change the value of one of the filter's parameters.
  20703. The host may call this at any time, including during the audio processing
  20704. callback, so the filter has to process this very fast and avoid blocking.
  20705. If you want to set the value of a parameter internally, e.g. from your
  20706. editor component, then don't call this directly - instead, use the
  20707. setParameterNotifyingHost() method, which will also send a message to
  20708. the host telling it about the change. If the message isn't sent, the host
  20709. won't be able to automate your parameters properly.
  20710. The value passed will be between 0 and 1.0.
  20711. */
  20712. virtual void setParameter (int parameterIndex,
  20713. float newValue) = 0;
  20714. /** Your filter can call this when it needs to change one of its parameters.
  20715. This could happen when the editor or some other internal operation changes
  20716. a parameter. This method will call the setParameter() method to change the
  20717. value, and will then send a message to the host telling it about the change.
  20718. Note that to make sure the host correctly handles automation, you should call
  20719. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  20720. tell the host when the user has started and stopped changing the parameter.
  20721. */
  20722. void setParameterNotifyingHost (int parameterIndex,
  20723. float newValue);
  20724. /** Returns true if the host can automate this parameter.
  20725. By default, this returns true for all parameters.
  20726. */
  20727. virtual bool isParameterAutomatable (int parameterIndex) const;
  20728. /** Should return true if this parameter is a "meta" parameter.
  20729. A meta-parameter is a parameter that changes other params. It is used
  20730. by some hosts (e.g. AudioUnit hosts).
  20731. By default this returns false.
  20732. */
  20733. virtual bool isMetaParameter (int parameterIndex) const;
  20734. /** Sends a signal to the host to tell it that the user is about to start changing this
  20735. parameter.
  20736. This allows the host to know when a parameter is actively being held by the user, and
  20737. it may use this information to help it record automation.
  20738. If you call this, it must be matched by a later call to endParameterChangeGesture().
  20739. */
  20740. void beginParameterChangeGesture (int parameterIndex);
  20741. /** Tells the host that the user has finished changing this parameter.
  20742. This allows the host to know when a parameter is actively being held by the user, and
  20743. it may use this information to help it record automation.
  20744. A call to this method must follow a call to beginParameterChangeGesture().
  20745. */
  20746. void endParameterChangeGesture (int parameterIndex);
  20747. /** The filter can call this when something (apart from a parameter value) has changed.
  20748. It sends a hint to the host that something like the program, number of parameters,
  20749. etc, has changed, and that it should update itself.
  20750. */
  20751. void updateHostDisplay();
  20752. /** Returns the number of preset programs the filter supports.
  20753. The value returned must be valid as soon as this object is created, and
  20754. must not change over its lifetime.
  20755. This value shouldn't be less than 1.
  20756. */
  20757. virtual int getNumPrograms() = 0;
  20758. /** Returns the number of the currently active program.
  20759. */
  20760. virtual int getCurrentProgram() = 0;
  20761. /** Called by the host to change the current program.
  20762. */
  20763. virtual void setCurrentProgram (int index) = 0;
  20764. /** Must return the name of a given program. */
  20765. virtual const String getProgramName (int index) = 0;
  20766. /** Called by the host to rename a program.
  20767. */
  20768. virtual void changeProgramName (int index, const String& newName) = 0;
  20769. /** The host will call this method when it wants to save the filter's internal state.
  20770. This must copy any info about the filter's state into the block of memory provided,
  20771. so that the host can store this and later restore it using setStateInformation().
  20772. Note that there's also a getCurrentProgramStateInformation() method, which only
  20773. stores the current program, not the state of the entire filter.
  20774. See also the helper function copyXmlToBinary() for storing settings as XML.
  20775. @see getCurrentProgramStateInformation
  20776. */
  20777. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  20778. /** The host will call this method if it wants to save the state of just the filter's
  20779. current program.
  20780. Unlike getStateInformation, this should only return the current program's state.
  20781. Not all hosts support this, and if you don't implement it, the base class
  20782. method just calls getStateInformation() instead. If you do implement it, be
  20783. sure to also implement getCurrentProgramStateInformation.
  20784. @see getStateInformation, setCurrentProgramStateInformation
  20785. */
  20786. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  20787. /** This must restore the filter's state from a block of data previously created
  20788. using getStateInformation().
  20789. Note that there's also a setCurrentProgramStateInformation() method, which tries
  20790. to restore just the current program, not the state of the entire filter.
  20791. See also the helper function getXmlFromBinary() for loading settings as XML.
  20792. @see setCurrentProgramStateInformation
  20793. */
  20794. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  20795. /** The host will call this method if it wants to restore the state of just the filter's
  20796. current program.
  20797. Not all hosts support this, and if you don't implement it, the base class
  20798. method just calls setStateInformation() instead. If you do implement it, be
  20799. sure to also implement getCurrentProgramStateInformation.
  20800. @see setStateInformation, getCurrentProgramStateInformation
  20801. */
  20802. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  20803. /** Adds a listener that will be called when an aspect of this processor changes. */
  20804. void addListener (AudioProcessorListener* const newListener) throw();
  20805. /** Removes a previously added listener. */
  20806. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  20807. /** Not for public use - this is called before deleting an editor component. */
  20808. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  20809. /** Not for public use - this is called to initialise the processor. */
  20810. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  20811. /** Not for public use - this is called to initialise the processor before playing. */
  20812. void setPlayConfigDetails (const int numIns, const int numOuts,
  20813. const double sampleRate,
  20814. const int blockSize) throw();
  20815. juce_UseDebuggingNewOperator
  20816. protected:
  20817. /** Helper function that just converts an xml element into a binary blob.
  20818. Use this in your filter's getStateInformation() method if you want to
  20819. store its state as xml.
  20820. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  20821. from a binary blob.
  20822. */
  20823. static void copyXmlToBinary (const XmlElement& xml,
  20824. JUCE_NAMESPACE::MemoryBlock& destData);
  20825. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  20826. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  20827. an XmlElement object that the caller must delete when no longer needed.
  20828. */
  20829. static XmlElement* getXmlFromBinary (const void* data,
  20830. const int sizeInBytes);
  20831. /** @internal */
  20832. AudioPlayHead* playHead;
  20833. /** @internal */
  20834. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  20835. private:
  20836. VoidArray listeners;
  20837. AudioProcessorEditor* activeEditor;
  20838. double sampleRate;
  20839. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  20840. bool suspended, nonRealtime;
  20841. CriticalSection callbackLock, listenerLock;
  20842. #ifdef JUCE_DEBUG
  20843. BitArray changingParams;
  20844. #endif
  20845. AudioProcessor (const AudioProcessor&);
  20846. const AudioProcessor& operator= (const AudioProcessor&);
  20847. };
  20848. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20849. /********* End of inlined file: juce_AudioProcessor.h *********/
  20850. #endif
  20851. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20852. #endif
  20853. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20854. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  20855. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20856. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  20857. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  20858. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20859. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  20860. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  20861. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20862. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  20863. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  20864. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20865. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20866. /********* Start of inlined file: juce_PluginDescription.h *********/
  20867. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20868. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20869. /**
  20870. A small class to represent some facts about a particular type of plugin.
  20871. This class is for storing and managing the details about a plugin without
  20872. actually having to load an instance of it.
  20873. A KnownPluginList contains a list of PluginDescription objects.
  20874. @see KnownPluginList
  20875. */
  20876. class JUCE_API PluginDescription
  20877. {
  20878. public:
  20879. PluginDescription() throw();
  20880. PluginDescription (const PluginDescription& other) throw();
  20881. const PluginDescription& operator= (const PluginDescription& other) throw();
  20882. ~PluginDescription() throw();
  20883. /** The name of the plugin. */
  20884. String name;
  20885. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  20886. */
  20887. String pluginFormatName;
  20888. /** A category, such as "Dynamics", "Reverbs", etc.
  20889. */
  20890. String category;
  20891. /** The manufacturer. */
  20892. String manufacturerName;
  20893. /** The version. This string doesn't have any particular format. */
  20894. String version;
  20895. /** Either the file containing the plugin module, or some other unique way
  20896. of identifying it.
  20897. E.g. for an AU, this would be an ID string that the component manager
  20898. could use to retrieve the plugin. For a VST, it's the file path.
  20899. */
  20900. String fileOrIdentifier;
  20901. /** The last time the plugin file was changed.
  20902. This is handy when scanning for new or changed plugins.
  20903. */
  20904. Time lastFileModTime;
  20905. /** A unique ID for the plugin.
  20906. Note that this might not be unique between formats, e.g. a VST and some
  20907. other format might actually have the same id.
  20908. @see createIdentifierString
  20909. */
  20910. int uid;
  20911. /** True if the plugin identifies itself as a synthesiser. */
  20912. bool isInstrument;
  20913. /** The number of inputs. */
  20914. int numInputChannels;
  20915. /** The number of outputs. */
  20916. int numOutputChannels;
  20917. /** Returns true if the two descriptions refer the the same plugin.
  20918. This isn't quite as simple as them just having the same file (because of
  20919. shell plugins).
  20920. */
  20921. bool isDuplicateOf (const PluginDescription& other) const;
  20922. /** Returns a string that can be saved and used to uniquely identify the
  20923. plugin again.
  20924. This contains less info than the XML encoding, and is independent of the
  20925. plugin's file location, so can be used to store a plugin ID for use
  20926. across different machines.
  20927. */
  20928. const String createIdentifierString() const throw();
  20929. /** Creates an XML object containing these details.
  20930. @see loadFromXml
  20931. */
  20932. XmlElement* createXml() const;
  20933. /** Reloads the info in this structure from an XML record that was previously
  20934. saved with createXML().
  20935. Returns true if the XML was a valid plugin description.
  20936. */
  20937. bool loadFromXml (const XmlElement& xml);
  20938. juce_UseDebuggingNewOperator
  20939. };
  20940. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  20941. /********* End of inlined file: juce_PluginDescription.h *********/
  20942. /**
  20943. Base class for an active instance of a plugin.
  20944. This derives from the AudioProcessor class, and adds some extra functionality
  20945. that helps when wrapping dynamically loaded plugins.
  20946. @see AudioProcessor, AudioPluginFormat
  20947. */
  20948. class JUCE_API AudioPluginInstance : public AudioProcessor
  20949. {
  20950. public:
  20951. /** Destructor.
  20952. Make sure that you delete any UI components that belong to this plugin before
  20953. deleting the plugin.
  20954. */
  20955. virtual ~AudioPluginInstance();
  20956. /** Fills-in the appropriate parts of this plugin description object.
  20957. */
  20958. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  20959. juce_UseDebuggingNewOperator
  20960. protected:
  20961. AudioPluginInstance();
  20962. AudioPluginInstance (const AudioPluginInstance&);
  20963. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  20964. };
  20965. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  20966. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  20967. class PluginDescription;
  20968. /**
  20969. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  20970. Use the static getNumFormats() and getFormat() calls to find the types
  20971. of format that are available.
  20972. */
  20973. class JUCE_API AudioPluginFormat
  20974. {
  20975. public:
  20976. /** Destructor. */
  20977. virtual ~AudioPluginFormat();
  20978. /** Returns the format name.
  20979. E.g. "VST", "AudioUnit", etc.
  20980. */
  20981. virtual const String getName() const = 0;
  20982. /** This tries to create descriptions for all the plugin types available in
  20983. a binary module file.
  20984. The file will be some kind of DLL or bundle.
  20985. Normally there will only be one type returned, but some plugins
  20986. (e.g. VST shells) can use a single DLL to create a set of different plugin
  20987. subtypes, so in that case, each subtype is returned as a separate object.
  20988. */
  20989. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  20990. const String& fileOrIdentifier) = 0;
  20991. /** Tries to recreate a type from a previously generated PluginDescription.
  20992. @see PluginDescription::createInstance
  20993. */
  20994. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  20995. /** Should do a quick check to see if this file or directory might be a plugin of
  20996. this format.
  20997. This is for searching for potential files, so it shouldn't actually try to
  20998. load the plugin or do anything time-consuming.
  20999. */
  21000. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  21001. /** Returns a readable version of the name of the plugin that this identifier refers to.
  21002. */
  21003. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  21004. /** Checks whether this plugin could possibly be loaded.
  21005. It doesn't actually need to load it, just to check whether the file or component
  21006. still exists.
  21007. */
  21008. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  21009. /** Searches a suggested set of directories for any plugins in this format.
  21010. The path might be ignored, e.g. by AUs, which are found by the OS rather
  21011. than manually.
  21012. */
  21013. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  21014. const bool recursive) = 0;
  21015. /** Returns the typical places to look for this kind of plugin.
  21016. Note that if this returns no paths, it means that the format can't be scanned-for
  21017. (i.e. it's an internal format that doesn't live in files)
  21018. */
  21019. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  21020. juce_UseDebuggingNewOperator
  21021. protected:
  21022. AudioPluginFormat() throw();
  21023. AudioPluginFormat (const AudioPluginFormat&);
  21024. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  21025. };
  21026. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21027. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  21028. /**
  21029. This maintains a list of known AudioPluginFormats.
  21030. @see AudioPluginFormat
  21031. */
  21032. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  21033. {
  21034. public:
  21035. AudioPluginFormatManager() throw();
  21036. /** Destructor. */
  21037. ~AudioPluginFormatManager() throw();
  21038. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  21039. /** Adds any formats that it knows about, e.g. VST.
  21040. */
  21041. void addDefaultFormats();
  21042. /** Returns the number of types of format that are available.
  21043. Use getFormat() to get one of them.
  21044. */
  21045. int getNumFormats() throw();
  21046. /** Returns one of the available formats.
  21047. @see getNumFormats
  21048. */
  21049. AudioPluginFormat* getFormat (const int index) throw();
  21050. /** Adds a format to the list.
  21051. The object passed in will be owned and deleted by the manager.
  21052. */
  21053. void addFormat (AudioPluginFormat* const format) throw();
  21054. /** Tries to load the type for this description, by trying all the formats
  21055. that this manager knows about.
  21056. The caller is responsible for deleting the object that is returned.
  21057. If it can't load the plugin, it returns 0 and leaves a message in the
  21058. errorMessage string.
  21059. */
  21060. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  21061. String& errorMessage) const;
  21062. /** Checks that the file or component for this plugin actually still exists.
  21063. (This won't try to load the plugin)
  21064. */
  21065. bool doesPluginStillExist (const PluginDescription& description) const;
  21066. juce_UseDebuggingNewOperator
  21067. private:
  21068. OwnedArray <AudioPluginFormat> formats;
  21069. AudioPluginFormatManager (const AudioPluginFormatManager&);
  21070. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  21071. };
  21072. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21073. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  21074. /********* Start of inlined file: juce_KnownPluginList.h *********/
  21075. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21076. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21077. /********* Start of inlined file: juce_PopupMenu.h *********/
  21078. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  21079. #define __JUCE_POPUPMENU_JUCEHEADER__
  21080. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  21081. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21082. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21083. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  21084. @see PopupMenu::addCustomItem
  21085. */
  21086. class JUCE_API PopupMenuCustomComponent : public Component
  21087. {
  21088. public:
  21089. /** Destructor. */
  21090. ~PopupMenuCustomComponent();
  21091. /** Chooses the size that this component would like to have.
  21092. Note that the size which this method returns isn't necessarily the one that
  21093. the menu will give it, as it will be stretched to fit the other items in
  21094. the menu.
  21095. */
  21096. virtual void getIdealSize (int& idealWidth,
  21097. int& idealHeight) = 0;
  21098. /** Dismisses the menu indicating that this item has been chosen.
  21099. This will cause the menu to exit from its modal state, returning
  21100. this item's id as the result.
  21101. */
  21102. void triggerMenuItem();
  21103. /** Returns true if this item should be highlighted because the mouse is
  21104. over it.
  21105. You can call this method in your paint() method to find out whether
  21106. to draw a highlight.
  21107. */
  21108. bool isItemHighlighted() const throw() { return isHighlighted; }
  21109. protected:
  21110. /** Constructor.
  21111. If isTriggeredAutomatically is true, then the menu will automatically detect
  21112. a click on this component and use that to trigger it. If it's false, then it's
  21113. up to your class to manually trigger the item if it wants to.
  21114. */
  21115. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  21116. private:
  21117. friend class MenuItemInfo;
  21118. friend class MenuItemComponent;
  21119. friend class PopupMenuWindow;
  21120. int refCount_;
  21121. bool isHighlighted, isTriggeredAutomatically;
  21122. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  21123. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  21124. };
  21125. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21126. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  21127. /** Creates and displays a popup-menu.
  21128. To show a popup-menu, you create one of these, add some items to it, then
  21129. call its show() method, which returns the id of the item the user selects.
  21130. E.g. @code
  21131. void MyWidget::mouseDown (const MouseEvent& e)
  21132. {
  21133. PopupMenu m;
  21134. m.addItem (1, "item 1");
  21135. m.addItem (2, "item 2");
  21136. const int result = m.show();
  21137. if (result == 0)
  21138. {
  21139. // user dismissed the menu without picking anything
  21140. }
  21141. else if (result == 1)
  21142. {
  21143. // user picked item 1
  21144. }
  21145. else if (result == 2)
  21146. {
  21147. // user picked item 2
  21148. }
  21149. }
  21150. @endcode
  21151. Submenus are easy too: @code
  21152. void MyWidget::mouseDown (const MouseEvent& e)
  21153. {
  21154. PopupMenu subMenu;
  21155. subMenu.addItem (1, "item 1");
  21156. subMenu.addItem (2, "item 2");
  21157. PopupMenu mainMenu;
  21158. mainMenu.addItem (3, "item 3");
  21159. mainMenu.addSubMenu ("other choices", subMenu);
  21160. const int result = m.show();
  21161. ...etc
  21162. }
  21163. @endcode
  21164. */
  21165. class JUCE_API PopupMenu
  21166. {
  21167. public:
  21168. /** Creates an empty popup menu. */
  21169. PopupMenu() throw();
  21170. /** Creates a copy of another menu. */
  21171. PopupMenu (const PopupMenu& other) throw();
  21172. /** Destructor. */
  21173. ~PopupMenu() throw();
  21174. /** Copies this menu from another one. */
  21175. const PopupMenu& operator= (const PopupMenu& other) throw();
  21176. /** Resets the menu, removing all its items. */
  21177. void clear() throw();
  21178. /** Appends a new text item for this menu to show.
  21179. @param itemResultId the number that will be returned from the show() method
  21180. if the user picks this item. The value should never be
  21181. zero, because that's used to indicate that the user didn't
  21182. select anything.
  21183. @param itemText the text to show.
  21184. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21185. picked
  21186. @param isTicked if true, the item will be shown with a tick next to it
  21187. @param iconToUse if this is non-zero, it should be an image that will be
  21188. displayed to the left of the item. This method will take its
  21189. own copy of the image passed-in, so there's no need to keep
  21190. it hanging around.
  21191. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21192. */
  21193. void addItem (const int itemResultId,
  21194. const String& itemText,
  21195. const bool isActive = true,
  21196. const bool isTicked = false,
  21197. const Image* const iconToUse = 0) throw();
  21198. /** Adds an item that represents one of the commands in a command manager object.
  21199. @param commandManager the manager to use to trigger the command and get information
  21200. about it
  21201. @param commandID the ID of the command
  21202. @param displayName if this is non-empty, then this string will be used instead of
  21203. the command's registered name
  21204. */
  21205. void addCommandItem (ApplicationCommandManager* commandManager,
  21206. const int commandID,
  21207. const String& displayName = String::empty) throw();
  21208. /** Appends a text item with a special colour.
  21209. This is the same as addItem(), but specifies a colour to use for the
  21210. text, which will override the default colours that are used by the
  21211. current look-and-feel. See addItem() for a description of the parameters.
  21212. */
  21213. void addColouredItem (const int itemResultId,
  21214. const String& itemText,
  21215. const Colour& itemTextColour,
  21216. const bool isActive = true,
  21217. const bool isTicked = false,
  21218. const Image* const iconToUse = 0) throw();
  21219. /** Appends a custom menu item.
  21220. This will add a user-defined component to use as a menu item. The component
  21221. passed in will be deleted by this menu when it's no longer needed.
  21222. @see PopupMenuCustomComponent
  21223. */
  21224. void addCustomItem (const int itemResultId,
  21225. PopupMenuCustomComponent* const customComponent) throw();
  21226. /** Appends a custom menu item that can't be used to trigger a result.
  21227. This will add a user-defined component to use as a menu item. Unlike the
  21228. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21229. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21230. delete the component when it's finished, so it's the caller's responsibility
  21231. to manage the component that is passed-in.
  21232. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21233. detection of a mouse-click on your component, and use that to trigger the
  21234. menu ID specified in itemResultId. If this is false, the menu item can't
  21235. be triggered, so itemResultId is not used.
  21236. @see PopupMenuCustomComponent
  21237. */
  21238. void addCustomItem (const int itemResultId,
  21239. Component* customComponent,
  21240. int idealWidth, int idealHeight,
  21241. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21242. /** Appends a sub-menu.
  21243. If the menu that's passed in is empty, it will appear as an inactive item.
  21244. */
  21245. void addSubMenu (const String& subMenuName,
  21246. const PopupMenu& subMenu,
  21247. const bool isActive = true,
  21248. Image* const iconToUse = 0,
  21249. const bool isTicked = false) throw();
  21250. /** Appends a separator to the menu, to help break it up into sections.
  21251. The menu class is smart enough not to display separators at the top or bottom
  21252. of the menu, and it will replace mutliple adjacent separators with a single
  21253. one, so your code can be quite free and easy about adding these, and it'll
  21254. always look ok.
  21255. */
  21256. void addSeparator() throw();
  21257. /** Adds a non-clickable text item to the menu.
  21258. This is a bold-font items which can be used as a header to separate the items
  21259. into named groups.
  21260. */
  21261. void addSectionHeader (const String& title) throw();
  21262. /** Returns the number of items that the menu currently contains.
  21263. (This doesn't count separators).
  21264. */
  21265. int getNumItems() const throw();
  21266. /** Returns true if the menu contains a command item that triggers the given command. */
  21267. bool containsCommandItem (const int commandID) const throw();
  21268. /** Returns true if the menu contains any items that can be used. */
  21269. bool containsAnyActiveItems() const throw();
  21270. /** Displays the menu and waits for the user to pick something.
  21271. This will display the menu modally, and return the ID of the item that the
  21272. user picks. If they click somewhere off the menu to get rid of it without
  21273. choosing anything, this will return 0.
  21274. The current location of the mouse will be used as the position to show the
  21275. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21276. on where this point is on the screen, the menu will appear above, below or
  21277. to the side of the point.
  21278. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21279. then when the menu first appears, it will make sure
  21280. that this item is visible. So if the menu has too many
  21281. items to fit on the screen, it will be scrolled to a
  21282. position where this item is visible.
  21283. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21284. than this if some items are too long to fit.
  21285. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21286. vertical column, the menu may be laid out as a series of
  21287. columns - this is the maximum number allowed. To use the
  21288. default value for this (probably about 7), you can pass
  21289. in zero.
  21290. @param standardItemHeight if this is non-zero, it will be used as the standard
  21291. height for menu items (apart from custom items)
  21292. @see showAt
  21293. */
  21294. int show (const int itemIdThatMustBeVisible = 0,
  21295. const int minimumWidth = 0,
  21296. const int maximumNumColumns = 0,
  21297. const int standardItemHeight = 0);
  21298. /** Displays the menu at a specific location.
  21299. This is the same as show(), but uses a specific location (in global screen
  21300. co-ordinates) rather than the current mouse position.
  21301. Note that the co-ordinates don't specify the top-left of the menu - they
  21302. indicate a point of interest, and the menu will position itself nearby to
  21303. this point, trying to keep it fully on-screen.
  21304. @see show()
  21305. */
  21306. int showAt (const int screenX,
  21307. const int screenY,
  21308. const int itemIdThatMustBeVisible = 0,
  21309. const int minimumWidth = 0,
  21310. const int maximumNumColumns = 0,
  21311. const int standardItemHeight = 0);
  21312. /** Displays the menu as if it's attached to a component such as a button.
  21313. This is similar to showAt(), but will position it next to the given component, e.g.
  21314. so that the menu's edge is aligned with that of the component. This is intended for
  21315. things like buttons that trigger a pop-up menu.
  21316. */
  21317. int showAt (Component* componentToAttachTo,
  21318. const int itemIdThatMustBeVisible = 0,
  21319. const int minimumWidth = 0,
  21320. const int maximumNumColumns = 0,
  21321. const int standardItemHeight = 0);
  21322. /** Closes any menus that are currently open.
  21323. This might be useful if you have a situation where your window is being closed
  21324. by some means other than a user action, and you'd like to make sure that menus
  21325. aren't left hanging around.
  21326. */
  21327. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21328. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21329. This can be called before show() if you need a customised menu. Be careful
  21330. not to delete the LookAndFeel object before the menu has been deleted.
  21331. */
  21332. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21333. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21334. These constants can be used either via the LookAndFeel::setColour()
  21335. method for the look and feel that is set for this menu with setLookAndFeel()
  21336. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21337. */
  21338. enum ColourIds
  21339. {
  21340. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21341. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21342. colour is specified when the item is added). */
  21343. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21344. addSectionHeader() method). */
  21345. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21346. highlighted menu item. */
  21347. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21348. highlighted item. */
  21349. };
  21350. /**
  21351. Allows you to iterate through the items in a pop-up menu, and examine
  21352. their properties.
  21353. To use this, just create one and repeatedly call its next() method. When this
  21354. returns true, all the member variables of the iterator are filled-out with
  21355. information describing the menu item. When it returns false, the end of the
  21356. list has been reached.
  21357. */
  21358. class JUCE_API MenuItemIterator
  21359. {
  21360. public:
  21361. /** Creates an iterator that will scan through the items in the specified
  21362. menu.
  21363. Be careful not to add any items to a menu while it is being iterated,
  21364. or things could get out of step.
  21365. */
  21366. MenuItemIterator (const PopupMenu& menu) throw();
  21367. /** Destructor. */
  21368. ~MenuItemIterator() throw();
  21369. /** Returns true if there is another item, and sets up all this object's
  21370. member variables to reflect that item's properties.
  21371. */
  21372. bool next() throw();
  21373. String itemName;
  21374. const PopupMenu* subMenu;
  21375. int itemId;
  21376. bool isSeparator;
  21377. bool isTicked;
  21378. bool isEnabled;
  21379. bool isCustomComponent;
  21380. bool isSectionHeader;
  21381. const Colour* customColour;
  21382. const Image* customImage;
  21383. ApplicationCommandManager* commandManager;
  21384. juce_UseDebuggingNewOperator
  21385. private:
  21386. const PopupMenu& menu;
  21387. int index;
  21388. MenuItemIterator (const MenuItemIterator&);
  21389. const MenuItemIterator& operator= (const MenuItemIterator&);
  21390. };
  21391. juce_UseDebuggingNewOperator
  21392. private:
  21393. friend class PopupMenuWindow;
  21394. friend class MenuItemIterator;
  21395. VoidArray items;
  21396. LookAndFeel* lookAndFeel;
  21397. bool separatorPending;
  21398. void addSeparatorIfPending();
  21399. int showMenu (const int x, const int y, const int w, const int h,
  21400. const int itemIdThatMustBeVisible,
  21401. const int minimumWidth,
  21402. const int maximumNumColumns,
  21403. const int standardItemHeight,
  21404. const bool alignToRectangle,
  21405. Component* const componentAttachedTo) throw();
  21406. friend class MenuBarComponent;
  21407. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21408. const int itemIdThatMustBeVisible,
  21409. const int minimumWidth,
  21410. const int maximumNumColumns,
  21411. const int standardItemHeight,
  21412. const bool alignToRectangle,
  21413. Component* menuBarComponent,
  21414. ApplicationCommandManager** managerOfChosenCommand,
  21415. Component* const componentAttachedTo) throw();
  21416. };
  21417. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21418. /********* End of inlined file: juce_PopupMenu.h *********/
  21419. /**
  21420. Manages a list of plugin types.
  21421. This can be easily edited, saved and loaded, and used to create instances of
  21422. the plugin types in it.
  21423. @see PluginListComponent
  21424. */
  21425. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21426. {
  21427. public:
  21428. /** Creates an empty list.
  21429. */
  21430. KnownPluginList();
  21431. /** Destructor. */
  21432. ~KnownPluginList();
  21433. /** Clears the list. */
  21434. void clear();
  21435. /** Returns the number of types currently in the list.
  21436. @see getType
  21437. */
  21438. int getNumTypes() const throw() { return types.size(); }
  21439. /** Returns one of the types.
  21440. @see getNumTypes
  21441. */
  21442. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21443. /** Looks for a type in the list which comes from this file.
  21444. */
  21445. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  21446. /** Looks for a type in the list which matches a plugin type ID.
  21447. The identifierString parameter must have been created by
  21448. PluginDescription::createIdentifierString().
  21449. */
  21450. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21451. /** Adds a type manually from its description. */
  21452. bool addType (const PluginDescription& type);
  21453. /** Removes a type. */
  21454. void removeType (const int index) throw();
  21455. /** Looks for all types that can be loaded from a given file, and adds them
  21456. to the list.
  21457. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21458. re-tested if it's not already in the list, or if the file's modification
  21459. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21460. false, the file will always be reloaded and tested.
  21461. Returns true if any new types were added, and all the types found in this
  21462. file (even if it was already known and hasn't been re-scanned) get returned
  21463. in the array.
  21464. */
  21465. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  21466. const bool dontRescanIfAlreadyInList,
  21467. OwnedArray <PluginDescription>& typesFound,
  21468. AudioPluginFormat& formatToUse);
  21469. /** Returns true if the specified file is already known about and if it
  21470. hasn't been modified since our entry was created.
  21471. */
  21472. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  21473. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21474. If any types are found in the files, their descriptions are returned in the array.
  21475. */
  21476. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21477. OwnedArray <PluginDescription>& typesFound);
  21478. /** Sort methods used to change the order of the plugins in the list.
  21479. */
  21480. enum SortMethod
  21481. {
  21482. defaultOrder = 0,
  21483. sortAlphabetically,
  21484. sortByCategory,
  21485. sortByManufacturer,
  21486. sortByFileSystemLocation
  21487. };
  21488. /** Adds all the plugin types to a popup menu so that the user can select one.
  21489. Depending on the sort method, it may add sub-menus for categories,
  21490. manufacturers, etc.
  21491. Use getIndexChosenByMenu() to find out the type that was chosen.
  21492. */
  21493. void addToMenu (PopupMenu& menu,
  21494. const SortMethod sortMethod) const;
  21495. /** Converts a menu item index that has been chosen into its index in this list.
  21496. Returns -1 if it's not an ID that was used.
  21497. @see addToMenu
  21498. */
  21499. int getIndexChosenByMenu (const int menuResultCode) const;
  21500. /** Sorts the list. */
  21501. void sort (const SortMethod method);
  21502. /** Creates some XML that can be used to store the state of this list.
  21503. */
  21504. XmlElement* createXml() const;
  21505. /** Recreates the state of this list from its stored XML format.
  21506. */
  21507. void recreateFromXml (const XmlElement& xml);
  21508. juce_UseDebuggingNewOperator
  21509. private:
  21510. OwnedArray <PluginDescription> types;
  21511. KnownPluginList (const KnownPluginList&);
  21512. const KnownPluginList& operator= (const KnownPluginList&);
  21513. };
  21514. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21515. /********* End of inlined file: juce_KnownPluginList.h *********/
  21516. /**
  21517. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21518. Use one of these objects if you want to wire-up a set of AudioProcessors
  21519. and play back the result.
  21520. Processors can be added to the graph as "nodes" using addNode(), and once
  21521. added, you can connect any of their input or output channels to other
  21522. nodes using addConnection().
  21523. To play back a graph through an audio device, you might want to use an
  21524. AudioProcessorPlayer object.
  21525. */
  21526. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21527. public AsyncUpdater
  21528. {
  21529. public:
  21530. /** Creates an empty graph.
  21531. */
  21532. AudioProcessorGraph();
  21533. /** Destructor.
  21534. Any processor objects that have been added to the graph will also be deleted.
  21535. */
  21536. ~AudioProcessorGraph();
  21537. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21538. To create a node, call AudioProcessorGraph::addNode().
  21539. */
  21540. class Node : public ReferenceCountedObject
  21541. {
  21542. public:
  21543. /** Destructor.
  21544. */
  21545. ~Node();
  21546. /** The ID number assigned to this node.
  21547. This is assigned by the graph that owns it, and can't be changed.
  21548. */
  21549. const uint32 id;
  21550. /** The actual processor object that this node represents.
  21551. */
  21552. AudioProcessor* const processor;
  21553. /** A set of user-definable properties that are associated with this node.
  21554. This can be used to attach values to the node for whatever purpose seems
  21555. useful. For example, you might store an x and y position if your application
  21556. is displaying the nodes on-screen.
  21557. */
  21558. PropertySet properties;
  21559. /** A convenient typedef for referring to a pointer to a node object.
  21560. */
  21561. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21562. juce_UseDebuggingNewOperator
  21563. private:
  21564. friend class AudioProcessorGraph;
  21565. bool isPrepared;
  21566. Node (const uint32 id, AudioProcessor* const processor) throw();
  21567. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21568. void unprepare();
  21569. Node (const Node&);
  21570. const Node& operator= (const Node&);
  21571. };
  21572. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21573. To create a connection, use AudioProcessorGraph::addConnection().
  21574. */
  21575. struct Connection
  21576. {
  21577. public:
  21578. /** The ID number of the node which is the input source for this connection.
  21579. @see AudioProcessorGraph::getNodeForId
  21580. */
  21581. uint32 sourceNodeId;
  21582. /** The index of the output channel of the source node from which this
  21583. connection takes its data.
  21584. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21585. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21586. index of an audio output channel in the source node.
  21587. */
  21588. int sourceChannelIndex;
  21589. /** The ID number of the node which is the destination for this connection.
  21590. @see AudioProcessorGraph::getNodeForId
  21591. */
  21592. uint32 destNodeId;
  21593. /** The index of the input channel of the destination node to which this
  21594. connection delivers its data.
  21595. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21596. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21597. index of an audio input channel in the destination node.
  21598. */
  21599. int destChannelIndex;
  21600. juce_UseDebuggingNewOperator
  21601. private:
  21602. };
  21603. /** Deletes all nodes and connections from this graph.
  21604. Any processor objects in the graph will be deleted.
  21605. */
  21606. void clear();
  21607. /** Returns the number of nodes in the graph. */
  21608. int getNumNodes() const throw() { return nodes.size(); }
  21609. /** Returns a pointer to one of the nodes in the graph.
  21610. This will return 0 if the index is out of range.
  21611. @see getNodeForId
  21612. */
  21613. Node* getNode (const int index) const throw() { return nodes [index]; }
  21614. /** Searches the graph for a node with the given ID number and returns it.
  21615. If no such node was found, this returns 0.
  21616. @see getNode
  21617. */
  21618. Node* getNodeForId (const uint32 nodeId) const throw();
  21619. /** Adds a node to the graph.
  21620. This creates a new node in the graph, for the specified processor. Once you have
  21621. added a processor to the graph, the graph owns it and will delete it later when
  21622. it is no longer needed.
  21623. The optional nodeId parameter lets you specify an ID to use for the node, but
  21624. if the value is already in use, this new node will overwrite the old one.
  21625. If this succeeds, it returns a pointer to the newly-created node.
  21626. */
  21627. Node* addNode (AudioProcessor* const newProcessor,
  21628. uint32 nodeId = 0);
  21629. /** Deletes a node within the graph which has the specified ID.
  21630. This will also delete any connections that are attached to this node.
  21631. */
  21632. bool removeNode (const uint32 nodeId);
  21633. /** Returns the number of connections in the graph. */
  21634. int getNumConnections() const throw() { return connections.size(); }
  21635. /** Returns a pointer to one of the connections in the graph. */
  21636. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21637. /** Searches for a connection between some specified channels.
  21638. If no such connection is found, this returns 0.
  21639. */
  21640. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21641. const int sourceChannelIndex,
  21642. const uint32 destNodeId,
  21643. const int destChannelIndex) const throw();
  21644. /** Returns true if there is a connection between any of the channels of
  21645. two specified nodes.
  21646. */
  21647. bool isConnected (const uint32 possibleSourceNodeId,
  21648. const uint32 possibleDestNodeId) const throw();
  21649. /** Returns true if it would be legal to connect the specified points.
  21650. */
  21651. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  21652. const uint32 destNodeId, const int destChannelIndex) const throw();
  21653. /** Attempts to connect two specified channels of two nodes.
  21654. If this isn't allowed (e.g. because you're trying to connect a midi channel
  21655. to an audio one or other such nonsense), then it'll return false.
  21656. */
  21657. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21658. const uint32 destNodeId, const int destChannelIndex);
  21659. /** Deletes the connection with the specified index.
  21660. Returns true if a connection was actually deleted.
  21661. */
  21662. void removeConnection (const int index);
  21663. /** Deletes any connection between two specified points.
  21664. Returns true if a connection was actually deleted.
  21665. */
  21666. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  21667. const uint32 destNodeId, const int destChannelIndex);
  21668. /** Removes all connections from the specified node.
  21669. */
  21670. bool disconnectNode (const uint32 nodeId);
  21671. /** Performs a sanity checks of all the connections.
  21672. This might be useful if some of the processors are doing things like changing
  21673. their channel counts, which could render some connections obsolete.
  21674. */
  21675. bool removeIllegalConnections();
  21676. /** A special number that represents the midi channel of a node.
  21677. This is used as a channel index value if you want to refer to the midi input
  21678. or output instead of an audio channel.
  21679. */
  21680. static const int midiChannelIndex;
  21681. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  21682. in order to use the audio that comes into and out of the graph itself.
  21683. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  21684. node in the graph which delivers the audio that is coming into the parent
  21685. graph. This allows you to stream the data to other nodes and process the
  21686. incoming audio.
  21687. Likewise, one of these in "output" mode can be sent data which it will add to
  21688. the sum of data being sent to the graph's output.
  21689. @see AudioProcessorGraph
  21690. */
  21691. class AudioGraphIOProcessor : public AudioPluginInstance
  21692. {
  21693. public:
  21694. /** Specifies the mode in which this processor will operate.
  21695. */
  21696. enum IODeviceType
  21697. {
  21698. audioInputNode, /**< In this mode, the processor has output channels
  21699. representing all the audio input channels that are
  21700. coming into its parent audio graph. */
  21701. audioOutputNode, /**< In this mode, the processor has input channels
  21702. representing all the audio output channels that are
  21703. going out of its parent audio graph. */
  21704. midiInputNode, /**< In this mode, the processor has a midi output which
  21705. delivers the same midi data that is arriving at its
  21706. parent graph. */
  21707. midiOutputNode /**< In this mode, the processor has a midi input and
  21708. any data sent to it will be passed out of the parent
  21709. graph. */
  21710. };
  21711. /** Returns the mode of this processor. */
  21712. IODeviceType getType() const throw() { return type; }
  21713. /** Returns the parent graph to which this processor belongs, or 0 if it
  21714. hasn't yet been added to one. */
  21715. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  21716. /** True if this is an audio or midi input. */
  21717. bool isInput() const throw();
  21718. /** True if this is an audio or midi output. */
  21719. bool isOutput() const throw();
  21720. AudioGraphIOProcessor (const IODeviceType type);
  21721. ~AudioGraphIOProcessor();
  21722. const String getName() const;
  21723. void fillInPluginDescription (PluginDescription& d) const;
  21724. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21725. void releaseResources();
  21726. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21727. const String getInputChannelName (const int channelIndex) const;
  21728. const String getOutputChannelName (const int channelIndex) const;
  21729. bool isInputChannelStereoPair (int index) const;
  21730. bool isOutputChannelStereoPair (int index) const;
  21731. bool acceptsMidi() const;
  21732. bool producesMidi() const;
  21733. AudioProcessorEditor* createEditor();
  21734. int getNumParameters();
  21735. const String getParameterName (int);
  21736. float getParameter (int);
  21737. const String getParameterText (int);
  21738. void setParameter (int, float);
  21739. int getNumPrograms();
  21740. int getCurrentProgram();
  21741. void setCurrentProgram (int);
  21742. const String getProgramName (int);
  21743. void changeProgramName (int, const String&);
  21744. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21745. void setStateInformation (const void* data, int sizeInBytes);
  21746. /** @internal */
  21747. void setParentGraph (AudioProcessorGraph* const graph) throw();
  21748. juce_UseDebuggingNewOperator
  21749. private:
  21750. const IODeviceType type;
  21751. AudioProcessorGraph* graph;
  21752. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  21753. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  21754. };
  21755. // AudioProcessor methods:
  21756. const String getName() const;
  21757. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21758. void releaseResources();
  21759. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  21760. const String getInputChannelName (const int channelIndex) const;
  21761. const String getOutputChannelName (const int channelIndex) const;
  21762. bool isInputChannelStereoPair (int index) const;
  21763. bool isOutputChannelStereoPair (int index) const;
  21764. bool acceptsMidi() const;
  21765. bool producesMidi() const;
  21766. AudioProcessorEditor* createEditor() { return 0; }
  21767. int getNumParameters() { return 0; }
  21768. const String getParameterName (int) { return String::empty; }
  21769. float getParameter (int) { return 0; }
  21770. const String getParameterText (int) { return String::empty; }
  21771. void setParameter (int, float) { }
  21772. int getNumPrograms() { return 0; }
  21773. int getCurrentProgram() { return 0; }
  21774. void setCurrentProgram (int) { }
  21775. const String getProgramName (int) { return String::empty; }
  21776. void changeProgramName (int, const String&) { }
  21777. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21778. void setStateInformation (const void* data, int sizeInBytes);
  21779. /** @internal */
  21780. void handleAsyncUpdate();
  21781. juce_UseDebuggingNewOperator
  21782. private:
  21783. ReferenceCountedArray <Node> nodes;
  21784. OwnedArray <Connection> connections;
  21785. int lastNodeId;
  21786. AudioSampleBuffer renderingBuffers;
  21787. OwnedArray <MidiBuffer> midiBuffers;
  21788. CriticalSection renderLock;
  21789. VoidArray renderingOps;
  21790. friend class AudioGraphIOProcessor;
  21791. AudioSampleBuffer* currentAudioInputBuffer;
  21792. AudioSampleBuffer currentAudioOutputBuffer;
  21793. MidiBuffer* currentMidiInputBuffer;
  21794. MidiBuffer currentMidiOutputBuffer;
  21795. void clearRenderingSequence();
  21796. void buildRenderingSequence();
  21797. bool isAnInputTo (const uint32 possibleInputId,
  21798. const uint32 possibleDestinationId,
  21799. const int recursionCheck) const throw();
  21800. AudioProcessorGraph (const AudioProcessorGraph&);
  21801. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  21802. };
  21803. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21804. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  21805. #endif
  21806. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  21807. #endif
  21808. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21809. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  21810. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21811. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  21812. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21813. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21814. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21815. class AudioIODevice;
  21816. /**
  21817. One of these is passed to an AudioIODevice object to stream the audio data
  21818. in and out.
  21819. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21820. method on its own high-priority audio thread, when it needs to send or receive
  21821. the next block of data.
  21822. @see AudioIODevice, AudioDeviceManager
  21823. */
  21824. class JUCE_API AudioIODeviceCallback
  21825. {
  21826. public:
  21827. /** Destructor. */
  21828. virtual ~AudioIODeviceCallback() {}
  21829. /** Processes a block of incoming and outgoing audio data.
  21830. The subclass's implementation should use the incoming audio for whatever
  21831. purposes it needs to, and must fill all the output channels with the next
  21832. block of output data before returning.
  21833. The channel data is arranged with the same array indices as the channel name
  21834. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21835. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21836. associated channel, so remember to check for this.
  21837. @param inputChannelData a set of arrays containing the audio data for each
  21838. incoming channel - this data is valid until the function
  21839. returns. There will be one channel of data for each input
  21840. channel that was enabled when the audio device was opened
  21841. (see AudioIODevice::open())
  21842. @param numInputChannels the number of pointers to channel data in the
  21843. inputChannelData array.
  21844. @param outputChannelData a set of arrays which need to be filled with the data
  21845. that should be sent to each outgoing channel of the device.
  21846. There will be one channel of data for each output channel
  21847. that was enabled when the audio device was opened (see
  21848. AudioIODevice::open())
  21849. The initial contents of the array is undefined, so the
  21850. callback function must fill all the channels with zeros if
  21851. its output is silence. Failing to do this could cause quite
  21852. an unpleasant noise!
  21853. @param numOutputChannels the number of pointers to channel data in the
  21854. outputChannelData array.
  21855. @param numSamples the number of samples in each channel of the input and
  21856. output arrays. The number of samples will depend on the
  21857. audio device's buffer size and will usually remain constant,
  21858. although this isn't guaranteed, so make sure your code can
  21859. cope with reasonable changes in the buffer size from one
  21860. callback to the next.
  21861. */
  21862. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21863. int numInputChannels,
  21864. float** outputChannelData,
  21865. int numOutputChannels,
  21866. int numSamples) = 0;
  21867. /** Called to indicate that the device is about to start calling back.
  21868. This will be called just before the audio callbacks begin, either when this
  21869. callback has just been added to an audio device, or after the device has been
  21870. restarted because of a sample-rate or block-size change.
  21871. You can use this opportunity to find out the sample rate and block size
  21872. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21873. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21874. @param device the audio IO device that will be used to drive the callback.
  21875. Note that if you're going to store this this pointer, it is
  21876. only valid until the next time that audioDeviceStopped is called.
  21877. */
  21878. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21879. /** Called to indicate that the device has stopped.
  21880. */
  21881. virtual void audioDeviceStopped() = 0;
  21882. };
  21883. /**
  21884. Base class for an audio device with synchronised input and output channels.
  21885. Subclasses of this are used to implement different protocols such as DirectSound,
  21886. ASIO, CoreAudio, etc.
  21887. To create one of these, you'll need to use the AudioIODeviceType class - see the
  21888. documentation for that class for more info.
  21889. For an easier way of managing audio devices and their settings, have a look at the
  21890. AudioDeviceManager class.
  21891. @see AudioIODeviceType, AudioDeviceManager
  21892. */
  21893. class JUCE_API AudioIODevice
  21894. {
  21895. public:
  21896. /** Destructor. */
  21897. virtual ~AudioIODevice();
  21898. /** Returns the device's name, (as set in the constructor). */
  21899. const String& getName() const throw() { return name; }
  21900. /** Returns the type of the device.
  21901. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  21902. */
  21903. const String& getTypeName() const throw() { return typeName; }
  21904. /** Returns the names of all the available output channels on this device.
  21905. To find out which of these are currently in use, call getActiveOutputChannels().
  21906. */
  21907. virtual const StringArray getOutputChannelNames() = 0;
  21908. /** Returns the names of all the available input channels on this device.
  21909. To find out which of these are currently in use, call getActiveInputChannels().
  21910. */
  21911. virtual const StringArray getInputChannelNames() = 0;
  21912. /** Returns the number of sample-rates this device supports.
  21913. To find out which rates are available on this device, use this method to
  21914. find out how many there are, and getSampleRate() to get the rates.
  21915. @see getSampleRate
  21916. */
  21917. virtual int getNumSampleRates() = 0;
  21918. /** Returns one of the sample-rates this device supports.
  21919. To find out which rates are available on this device, use getNumSampleRates() to
  21920. find out how many there are, and getSampleRate() to get the individual rates.
  21921. The sample rate is set by the open() method.
  21922. (Note that for DirectSound some rates might not work, depending on combinations
  21923. of i/o channels that are being opened).
  21924. @see getNumSampleRates
  21925. */
  21926. virtual double getSampleRate (int index) = 0;
  21927. /** Returns the number of sizes of buffer that are available.
  21928. @see getBufferSizeSamples, getDefaultBufferSize
  21929. */
  21930. virtual int getNumBufferSizesAvailable() = 0;
  21931. /** Returns one of the possible buffer-sizes.
  21932. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  21933. @returns a number of samples
  21934. @see getNumBufferSizesAvailable, getDefaultBufferSize
  21935. */
  21936. virtual int getBufferSizeSamples (int index) = 0;
  21937. /** Returns the default buffer-size to use.
  21938. @returns a number of samples
  21939. @see getNumBufferSizesAvailable, getBufferSizeSamples
  21940. */
  21941. virtual int getDefaultBufferSize() = 0;
  21942. /** Tries to open the device ready to play.
  21943. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  21944. input channel should be enabled
  21945. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  21946. output channel should be enabled
  21947. @param sampleRate the sample rate to try to use - to find out which rates are
  21948. available, see getNumSampleRates() and getSampleRate()
  21949. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  21950. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  21951. @returns an error description if there's a problem, or an empty string if it succeeds in
  21952. opening the device
  21953. @see close
  21954. */
  21955. virtual const String open (const BitArray& inputChannels,
  21956. const BitArray& outputChannels,
  21957. double sampleRate,
  21958. int bufferSizeSamples) = 0;
  21959. /** Closes and releases the device if it's open. */
  21960. virtual void close() = 0;
  21961. /** Returns true if the device is still open.
  21962. A device might spontaneously close itself if something goes wrong, so this checks if
  21963. it's still open.
  21964. */
  21965. virtual bool isOpen() = 0;
  21966. /** Starts the device actually playing.
  21967. This must be called after the device has been opened.
  21968. @param callback the callback to use for streaming the data.
  21969. @see AudioIODeviceCallback, open
  21970. */
  21971. virtual void start (AudioIODeviceCallback* callback) = 0;
  21972. /** Stops the device playing.
  21973. Once a device has been started, this will stop it. Any pending calls to the
  21974. callback class will be flushed before this method returns.
  21975. */
  21976. virtual void stop() = 0;
  21977. /** Returns true if the device is still calling back.
  21978. The device might mysteriously stop, so this checks whether it's
  21979. still playing.
  21980. */
  21981. virtual bool isPlaying() = 0;
  21982. /** Returns the last error that happened if anything went wrong. */
  21983. virtual const String getLastError() = 0;
  21984. /** Returns the buffer size that the device is currently using.
  21985. If the device isn't actually open, this value doesn't really mean much.
  21986. */
  21987. virtual int getCurrentBufferSizeSamples() = 0;
  21988. /** Returns the sample rate that the device is currently using.
  21989. If the device isn't actually open, this value doesn't really mean much.
  21990. */
  21991. virtual double getCurrentSampleRate() = 0;
  21992. /** Returns the device's current physical bit-depth.
  21993. If the device isn't actually open, this value doesn't really mean much.
  21994. */
  21995. virtual int getCurrentBitDepth() = 0;
  21996. /** Returns a mask showing which of the available output channels are currently
  21997. enabled.
  21998. @see getOutputChannelNames
  21999. */
  22000. virtual const BitArray getActiveOutputChannels() const = 0;
  22001. /** Returns a mask showing which of the available input channels are currently
  22002. enabled.
  22003. @see getInputChannelNames
  22004. */
  22005. virtual const BitArray getActiveInputChannels() const = 0;
  22006. /** Returns the device's output latency.
  22007. This is the delay in samples between a callback getting a block of data, and
  22008. that data actually getting played.
  22009. */
  22010. virtual int getOutputLatencyInSamples() = 0;
  22011. /** Returns the device's input latency.
  22012. This is the delay in samples between some audio actually arriving at the soundcard,
  22013. and the callback getting passed this block of data.
  22014. */
  22015. virtual int getInputLatencyInSamples() = 0;
  22016. /** True if this device can show a pop-up control panel for editing its settings.
  22017. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  22018. to display it.
  22019. */
  22020. virtual bool hasControlPanel() const;
  22021. /** Shows a device-specific control panel if there is one.
  22022. This should only be called for devices which return true from hasControlPanel().
  22023. */
  22024. virtual bool showControlPanel();
  22025. protected:
  22026. /** Creates a device, setting its name and type member variables. */
  22027. AudioIODevice (const String& deviceName,
  22028. const String& typeName);
  22029. /** @internal */
  22030. String name, typeName;
  22031. };
  22032. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22033. /********* End of inlined file: juce_AudioIODevice.h *********/
  22034. /**
  22035. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  22036. To use one of these, just make it the callback used by your AudioIODevice, and
  22037. give it a processor to use by calling setProcessor().
  22038. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  22039. input to send both streams through the processor.
  22040. @see AudioProcessor, AudioProcessorGraph
  22041. */
  22042. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  22043. public MidiInputCallback
  22044. {
  22045. public:
  22046. /**
  22047. */
  22048. AudioProcessorPlayer();
  22049. /** Destructor. */
  22050. virtual ~AudioProcessorPlayer();
  22051. /** Sets the processor that should be played.
  22052. The processor that is passed in will not be deleted or owned by this object.
  22053. To stop anything playing, pass in 0 to this method.
  22054. */
  22055. void setProcessor (AudioProcessor* const processorToPlay);
  22056. /** Returns the current audio processor that is being played.
  22057. */
  22058. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  22059. /** Returns a midi message collector that you can pass midi messages to if you
  22060. want them to be injected into the midi stream that is being sent to the
  22061. processor.
  22062. */
  22063. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  22064. /** @internal */
  22065. void audioDeviceIOCallback (const float** inputChannelData,
  22066. int totalNumInputChannels,
  22067. float** outputChannelData,
  22068. int totalNumOutputChannels,
  22069. int numSamples);
  22070. /** @internal */
  22071. void audioDeviceAboutToStart (AudioIODevice* device);
  22072. /** @internal */
  22073. void audioDeviceStopped();
  22074. /** @internal */
  22075. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  22076. juce_UseDebuggingNewOperator
  22077. private:
  22078. AudioProcessor* processor;
  22079. CriticalSection lock;
  22080. double sampleRate;
  22081. int blockSize;
  22082. bool isPrepared;
  22083. int numInputChans, numOutputChans;
  22084. float* channels [128];
  22085. AudioSampleBuffer tempBuffer;
  22086. MidiBuffer incomingMidi;
  22087. MidiMessageCollector messageCollector;
  22088. AudioProcessorPlayer (const AudioProcessorPlayer&);
  22089. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  22090. };
  22091. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22092. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  22093. #endif
  22094. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22095. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22096. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22097. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22098. /********* Start of inlined file: juce_PropertyPanel.h *********/
  22099. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  22100. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  22101. /********* Start of inlined file: juce_PropertyComponent.h *********/
  22102. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22103. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22104. class EditableProperty;
  22105. /**
  22106. A base class for a component that goes in a PropertyPanel and displays one of
  22107. an item's properties.
  22108. Subclasses of this are used to display a property in various forms, e.g. a
  22109. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  22110. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  22111. A subclass must implement the refresh() method which will be called to tell the
  22112. component to update itself, and is also responsible for calling this it when the
  22113. item that it refers to is changed.
  22114. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  22115. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  22116. */
  22117. class JUCE_API PropertyComponent : public Component
  22118. {
  22119. public:
  22120. /** Creates a PropertyComponent.
  22121. @param propertyName the name is stored as this component's name, and is
  22122. used as the name displayed next to this component in
  22123. a property panel
  22124. @param preferredHeight the height that the component should be given - some
  22125. items may need to be larger than a normal row height.
  22126. This value can also be set if a subclass changes the
  22127. preferredHeight member variable.
  22128. */
  22129. PropertyComponent (const String& propertyName,
  22130. const int preferredHeight = 25);
  22131. /** Destructor. */
  22132. ~PropertyComponent();
  22133. /** Returns this item's preferred height.
  22134. This value is specified either in the constructor or by a subclass changing the
  22135. preferredHeight member variable.
  22136. */
  22137. int getPreferredHeight() const throw() { return preferredHeight; }
  22138. /** Updates the property component if the item it refers to has changed.
  22139. A subclass must implement this method, and other objects may call it to
  22140. force it to refresh itself.
  22141. The subclass should be economical in the amount of work is done, so for
  22142. example it should check whether it really needs to do a repaint rather than
  22143. just doing one every time this method is called, as it may be called when
  22144. the value being displayed hasn't actually changed.
  22145. */
  22146. virtual void refresh() = 0;
  22147. /** The default paint method fills the background and draws a label for the
  22148. item's name.
  22149. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22150. */
  22151. void paint (Graphics& g);
  22152. /** The default resize method positions any child component to the right of this
  22153. one, based on the look and feel's default label size.
  22154. */
  22155. void resized();
  22156. /** By default, this just repaints the component. */
  22157. void enablementChanged();
  22158. juce_UseDebuggingNewOperator
  22159. protected:
  22160. /** Used by the PropertyPanel to determine how high this component needs to be.
  22161. A subclass can update this value in its constructor but shouldn't alter it later
  22162. as changes won't necessarily be picked up.
  22163. */
  22164. int preferredHeight;
  22165. };
  22166. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22167. /********* End of inlined file: juce_PropertyComponent.h *********/
  22168. /********* Start of inlined file: juce_Viewport.h *********/
  22169. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22170. #define __JUCE_VIEWPORT_JUCEHEADER__
  22171. /********* Start of inlined file: juce_ScrollBar.h *********/
  22172. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22173. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22174. /********* Start of inlined file: juce_Button.h *********/
  22175. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22176. #define __JUCE_BUTTON_JUCEHEADER__
  22177. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22178. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22179. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22180. /********* Start of inlined file: juce_TooltipClient.h *********/
  22181. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22182. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22183. /**
  22184. Components that want to use pop-up tooltips should implement this interface.
  22185. A TooltipWindow will wait for the mouse to hover over a component that
  22186. implements the TooltipClient interface, and when it finds one, it will display
  22187. the tooltip returned by its getTooltip() method.
  22188. @see TooltipWindow, SettableTooltipClient
  22189. */
  22190. class JUCE_API TooltipClient
  22191. {
  22192. public:
  22193. /** Destructor. */
  22194. virtual ~TooltipClient() {}
  22195. /** Returns the string that this object wants to show as its tooltip. */
  22196. virtual const String getTooltip() = 0;
  22197. };
  22198. /**
  22199. An implementation of TooltipClient that stores the tooltip string and a method
  22200. for changing it.
  22201. This makes it easy to add a tooltip to a custom component, by simply adding this
  22202. as a base class and calling setTooltip().
  22203. Many of the Juce widgets already use this as a base class to implement their
  22204. tooltips.
  22205. @see TooltipClient, TooltipWindow
  22206. */
  22207. class JUCE_API SettableTooltipClient : public TooltipClient
  22208. {
  22209. public:
  22210. /** Destructor. */
  22211. virtual ~SettableTooltipClient() {}
  22212. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22213. virtual const String getTooltip() { return tooltipString; }
  22214. juce_UseDebuggingNewOperator
  22215. protected:
  22216. String tooltipString;
  22217. };
  22218. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22219. /********* End of inlined file: juce_TooltipClient.h *********/
  22220. /**
  22221. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22222. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22223. object.
  22224. The TooltipWindow object will then stay invisible, waiting until the mouse
  22225. hovers for the specified length of time - it will then see if it's currently
  22226. over a component which implements the TooltipClient interface, and if so,
  22227. it will make itself visible to show the tooltip in the appropriate place.
  22228. @see TooltipClient, SettableTooltipClient
  22229. */
  22230. class JUCE_API TooltipWindow : public Component,
  22231. private Timer
  22232. {
  22233. public:
  22234. /** Creates a tooltip window.
  22235. Make sure your app only creates one instance of this class, otherwise you'll
  22236. get multiple overlaid tooltips appearing. The window will initially be invisible
  22237. and will make itself visible when it needs to display a tip.
  22238. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22239. methods.
  22240. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22241. otherwise the tooltip will be added to the given parent
  22242. component.
  22243. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22244. before a tooltip will be shown
  22245. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22246. */
  22247. TooltipWindow (Component* parentComponent = 0,
  22248. const int millisecondsBeforeTipAppears = 700);
  22249. /** Destructor. */
  22250. ~TooltipWindow();
  22251. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22252. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22253. methods.
  22254. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22255. */
  22256. enum ColourIds
  22257. {
  22258. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22259. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22260. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22261. };
  22262. juce_UseDebuggingNewOperator
  22263. private:
  22264. const int millisecondsBeforeTipAppears;
  22265. int mouseX, mouseY, mouseClicks;
  22266. unsigned int lastMouseMoveTime, lastHideTime;
  22267. Component* lastComponentUnderMouse;
  22268. bool changedCompsSinceShown;
  22269. String tip;
  22270. void paint (Graphics& g);
  22271. void mouseEnter (const MouseEvent& e);
  22272. void timerCallback();
  22273. void showFor (Component* const c);
  22274. void hide();
  22275. TooltipWindow (const TooltipWindow&);
  22276. const TooltipWindow& operator= (const TooltipWindow&);
  22277. };
  22278. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22279. /********* End of inlined file: juce_TooltipWindow.h *********/
  22280. class Button;
  22281. /**
  22282. Used to receive callbacks when a button is clicked.
  22283. @see Button::addButtonListener, Button::removeButtonListener
  22284. */
  22285. class JUCE_API ButtonListener
  22286. {
  22287. public:
  22288. /** Destructor. */
  22289. virtual ~ButtonListener() {}
  22290. /** Called when the button is clicked. */
  22291. virtual void buttonClicked (Button* button) = 0;
  22292. /** Called when the button's state changes. */
  22293. virtual void buttonStateChanged (Button*) {}
  22294. };
  22295. /**
  22296. A base class for buttons.
  22297. This contains all the logic for button behaviours such as enabling/disabling,
  22298. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22299. and radio groups, etc.
  22300. @see TextButton, DrawableButton, ToggleButton
  22301. */
  22302. class JUCE_API Button : public Component,
  22303. public SettableTooltipClient,
  22304. public ApplicationCommandManagerListener,
  22305. private KeyListener
  22306. {
  22307. protected:
  22308. /** Creates a button.
  22309. @param buttonName the text to put in the button (the component's name is also
  22310. initially set to this string, but these can be changed later
  22311. using the setName() and setButtonText() methods)
  22312. */
  22313. Button (const String& buttonName);
  22314. public:
  22315. /** Destructor. */
  22316. virtual ~Button();
  22317. /** Changes the button's text.
  22318. @see getButtonText
  22319. */
  22320. void setButtonText (const String& newText) throw();
  22321. /** Returns the text displayed in the button.
  22322. @see setButtonText
  22323. */
  22324. const String getButtonText() const throw() { return text; }
  22325. /** Returns true if the button is currently being held down by the mouse.
  22326. @see isOver
  22327. */
  22328. bool isDown() const throw();
  22329. /** Returns true if the mouse is currently over the button.
  22330. This will be also be true if the mouse is being held down.
  22331. @see isDown
  22332. */
  22333. bool isOver() const throw();
  22334. /** A button has an on/off state associated with it, and this changes that.
  22335. By default buttons are 'off' and for simple buttons that you click to perform
  22336. an action you won't change this. Toggle buttons, however will want to
  22337. change their state when turned on or off.
  22338. @param shouldBeOn whether to set the button's toggle state to be on or
  22339. off. If it's a member of a button group, this will
  22340. always try to turn it on, and to turn off any other
  22341. buttons in the group
  22342. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22343. the button will be repainted but no notification will
  22344. be sent
  22345. @see getToggleState, setRadioGroupId
  22346. */
  22347. void setToggleState (const bool shouldBeOn,
  22348. const bool sendChangeNotification);
  22349. /** Returns true if the button in 'on'.
  22350. By default buttons are 'off' and for simple buttons that you click to perform
  22351. an action you won't change this. Toggle buttons, however will want to
  22352. change their state when turned on or off.
  22353. @see setToggleState
  22354. */
  22355. bool getToggleState() const throw() { return isOn; }
  22356. /** This tells the button to automatically flip the toggle state when
  22357. the button is clicked.
  22358. If set to true, then before the clicked() callback occurs, the toggle-state
  22359. of the button is flipped.
  22360. */
  22361. void setClickingTogglesState (const bool shouldToggle) throw();
  22362. /** Returns true if this button is set to be an automatic toggle-button.
  22363. This returns the last value that was passed to setClickingTogglesState().
  22364. */
  22365. bool getClickingTogglesState() const throw();
  22366. /** Enables the button to act as a member of a mutually-exclusive group
  22367. of 'radio buttons'.
  22368. If the group ID is set to a non-zero number, then this button will
  22369. act as part of a group of buttons with the same ID, only one of
  22370. which can be 'on' at the same time. Note that when it's part of
  22371. a group, clicking a toggle-button that's 'on' won't turn it off.
  22372. To find other buttons with the same ID, this button will search through
  22373. its sibling components for ToggleButtons, so all the buttons for a
  22374. particular group must be placed inside the same parent component.
  22375. Set the group ID back to zero if you want it to act as a normal toggle
  22376. button again.
  22377. @see getRadioGroupId
  22378. */
  22379. void setRadioGroupId (const int newGroupId);
  22380. /** Returns the ID of the group to which this button belongs.
  22381. (See setRadioGroupId() for an explanation of this).
  22382. */
  22383. int getRadioGroupId() const throw() { return radioGroupId; }
  22384. /** Registers a listener to receive events when this button's state changes.
  22385. If the listener is already registered, this will not register it again.
  22386. @see removeButtonListener
  22387. */
  22388. void addButtonListener (ButtonListener* const newListener) throw();
  22389. /** Removes a previously-registered button listener
  22390. @see addButtonListener
  22391. */
  22392. void removeButtonListener (ButtonListener* const listener) throw();
  22393. /** Causes the button to act as if it's been clicked.
  22394. This will asynchronously make the button draw itself going down and up, and
  22395. will then call back the clicked() method as if mouse was clicked on it.
  22396. @see clicked
  22397. */
  22398. virtual void triggerClick();
  22399. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22400. When the button is pressed, it will use the given manager to trigger the
  22401. command ID.
  22402. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22403. before this button is. To disable the command triggering, call this method and
  22404. pass 0 for the parameters.
  22405. If generateTooltip is true, then the button's tooltip will be automatically
  22406. generated based on the name of this command and its current shortcut key.
  22407. @see addShortcut, getCommandID
  22408. */
  22409. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22410. const int commandID,
  22411. const bool generateTooltip);
  22412. /** Returns the command ID that was set by setCommandToTrigger().
  22413. */
  22414. int getCommandID() const throw() { return commandID; }
  22415. /** Assigns a shortcut key to trigger the button.
  22416. The button registers itself with its top-level parent component for keypresses.
  22417. Note that a different way of linking buttons to keypresses is by using the
  22418. setKeyPressToTrigger() method to invoke a command - the difference being that
  22419. setting a shortcut allows the button to be temporarily linked to a keypress
  22420. only while it's on-screen.
  22421. @see clearShortcuts
  22422. */
  22423. void addShortcut (const KeyPress& key);
  22424. /** Removes all key shortcuts that had been set for this button.
  22425. @see addShortcut
  22426. */
  22427. void clearShortcuts();
  22428. /** Returns true if the given keypress is a shortcut for this button.
  22429. @see addShortcut
  22430. */
  22431. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22432. /** Sets an auto-repeat speed for the button when it is held down.
  22433. (Auto-repeat is disabled by default).
  22434. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22435. triggering the next click. If this is zero, auto-repeat
  22436. is disabled
  22437. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22438. triggered
  22439. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22440. get faster, the longer the button is held down, up to the
  22441. minimum interval specified here
  22442. */
  22443. void setRepeatSpeed (const int initialDelayInMillisecs,
  22444. const int repeatDelayInMillisecs,
  22445. const int minimumDelayInMillisecs = -1) throw();
  22446. /** Sets whether the button click should happen when the mouse is pressed or released.
  22447. By default the button is only considered to have been clicked when the mouse is
  22448. released, but setting this to true will make it call the clicked() method as soon
  22449. as the button is pressed.
  22450. This is useful if the button is being used to show a pop-up menu, as it allows
  22451. the click to be used as a drag onto the menu.
  22452. */
  22453. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22454. /** Returns the number of milliseconds since the last time the button
  22455. went into the 'down' state.
  22456. */
  22457. uint32 getMillisecondsSinceButtonDown() const throw();
  22458. /** (overridden from Component to do special stuff). */
  22459. void setVisible (bool shouldBeVisible);
  22460. /** Sets the tooltip for this button.
  22461. @see TooltipClient, TooltipWindow
  22462. */
  22463. void setTooltip (const String& newTooltip);
  22464. // (implementation of the TooltipClient method)
  22465. const String getTooltip();
  22466. /** A combination of these flags are used by setConnectedEdges().
  22467. */
  22468. enum ConnectedEdgeFlags
  22469. {
  22470. ConnectedOnLeft = 1,
  22471. ConnectedOnRight = 2,
  22472. ConnectedOnTop = 4,
  22473. ConnectedOnBottom = 8
  22474. };
  22475. /** Hints about which edges of the button might be connected to adjoining buttons.
  22476. The value passed in is a bitwise combination of any of the values in the
  22477. ConnectedEdgeFlags enum.
  22478. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22479. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22480. without rounded corners on the edges that connect. It's only a hint, so the
  22481. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22482. button.
  22483. */
  22484. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22485. /** Returns the set of flags passed into setConnectedEdges(). */
  22486. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22487. /** Indicates whether the button adjoins another one on its left edge.
  22488. @see setConnectedEdges
  22489. */
  22490. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22491. /** Indicates whether the button adjoins another one on its right edge.
  22492. @see setConnectedEdges
  22493. */
  22494. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22495. /** Indicates whether the button adjoins another one on its top edge.
  22496. @see setConnectedEdges
  22497. */
  22498. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22499. /** Indicates whether the button adjoins another one on its bottom edge.
  22500. @see setConnectedEdges
  22501. */
  22502. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22503. /** Used by setState(). */
  22504. enum ButtonState
  22505. {
  22506. buttonNormal,
  22507. buttonOver,
  22508. buttonDown
  22509. };
  22510. /** Can be used to force the button into a particular state.
  22511. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22512. from happening.
  22513. The state that you set here will only last until it is automatically changed when the mouse
  22514. enters or exits the button, or the mouse-button is pressed or released.
  22515. */
  22516. void setState (const ButtonState newState);
  22517. juce_UseDebuggingNewOperator
  22518. protected:
  22519. /** This method is called when the button has been clicked.
  22520. Subclasses can override this to perform whatever they actions they need
  22521. to do.
  22522. Alternatively, a ButtonListener can be added to the button, and these listeners
  22523. will be called when the click occurs.
  22524. @see triggerClick
  22525. */
  22526. virtual void clicked();
  22527. /** This method is called when the button has been clicked.
  22528. By default it just calls clicked(), but you might want to override it to handle
  22529. things like clicking when a modifier key is pressed, etc.
  22530. @see ModifierKeys
  22531. */
  22532. virtual void clicked (const ModifierKeys& modifiers);
  22533. /** Subclasses should override this to actually paint the button's contents.
  22534. It's better to use this than the paint method, because it gives you information
  22535. about the over/down state of the button.
  22536. @param g the graphics context to use
  22537. @param isMouseOverButton true if the button is either in the 'over' or
  22538. 'down' state
  22539. @param isButtonDown true if the button should be drawn in the 'down' position
  22540. */
  22541. virtual void paintButton (Graphics& g,
  22542. bool isMouseOverButton,
  22543. bool isButtonDown) = 0;
  22544. /** Called when the button's up/down/over state changes.
  22545. Subclasses can override this if they need to do something special when the button
  22546. goes up or down.
  22547. @see isDown, isOver
  22548. */
  22549. virtual void buttonStateChanged();
  22550. /** @internal */
  22551. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22552. /** @internal */
  22553. void handleCommandMessage (int commandId);
  22554. /** @internal */
  22555. void mouseEnter (const MouseEvent& e);
  22556. /** @internal */
  22557. void mouseExit (const MouseEvent& e);
  22558. /** @internal */
  22559. void mouseDown (const MouseEvent& e);
  22560. /** @internal */
  22561. void mouseDrag (const MouseEvent& e);
  22562. /** @internal */
  22563. void mouseUp (const MouseEvent& e);
  22564. /** @internal */
  22565. bool keyPressed (const KeyPress& key);
  22566. /** @internal */
  22567. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22568. /** @internal */
  22569. bool keyStateChanged (Component* originatingComponent);
  22570. /** @internal */
  22571. void paint (Graphics& g);
  22572. /** @internal */
  22573. void parentHierarchyChanged();
  22574. /** @internal */
  22575. void focusGained (FocusChangeType cause);
  22576. /** @internal */
  22577. void focusLost (FocusChangeType cause);
  22578. /** @internal */
  22579. void enablementChanged();
  22580. /** @internal */
  22581. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22582. /** @internal */
  22583. void applicationCommandListChanged();
  22584. private:
  22585. Array <KeyPress> shortcuts;
  22586. Component* keySource;
  22587. String text;
  22588. SortedSet <void*> buttonListeners;
  22589. friend class InternalButtonRepeatTimer;
  22590. Timer* repeatTimer;
  22591. uint32 buttonPressTime, lastTimeCallbackTime;
  22592. ApplicationCommandManager* commandManagerToUse;
  22593. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22594. int radioGroupId, commandID, connectedEdgeFlags;
  22595. ButtonState buttonState;
  22596. bool isOn : 1;
  22597. bool clickTogglesState : 1;
  22598. bool needsToRelease : 1;
  22599. bool needsRepainting : 1;
  22600. bool isKeyDown : 1;
  22601. bool triggerOnMouseDown : 1;
  22602. bool generateTooltip : 1;
  22603. void repeatTimerCallback() throw();
  22604. Timer& getRepeatTimer() throw();
  22605. ButtonState updateState (const MouseEvent* const e) throw();
  22606. bool isShortcutPressed() const throw();
  22607. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22608. void flashButtonState() throw();
  22609. void sendClickMessage (const ModifierKeys& modifiers);
  22610. void sendStateMessage();
  22611. Button (const Button&);
  22612. const Button& operator= (const Button&);
  22613. };
  22614. #endif // __JUCE_BUTTON_JUCEHEADER__
  22615. /********* End of inlined file: juce_Button.h *********/
  22616. class ScrollBar;
  22617. /**
  22618. A class for receiving events from a ScrollBar.
  22619. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22620. method, and it will be called when the bar's position changes.
  22621. @see ScrollBar::addListener, ScrollBar::removeListener
  22622. */
  22623. class JUCE_API ScrollBarListener
  22624. {
  22625. public:
  22626. /** Destructor. */
  22627. virtual ~ScrollBarListener() {}
  22628. /** Called when a ScrollBar is moved.
  22629. @param scrollBarThatHasMoved the bar that has moved
  22630. @param newRangeStart the new range start of this bar
  22631. */
  22632. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22633. const double newRangeStart) = 0;
  22634. };
  22635. /**
  22636. A scrollbar component.
  22637. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22638. sets the range of values it can represent. Then you can use setCurrentRange() to
  22639. change the position and size of the scrollbar's 'thumb'.
  22640. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  22641. the user moves it, and you can use the getCurrentRangeStart() to find out where
  22642. they moved it to.
  22643. The scrollbar will adjust its own visibility according to whether its thumb size
  22644. allows it to actually be scrolled.
  22645. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  22646. instead of handling a scrollbar directly.
  22647. @see ScrollBarListener
  22648. */
  22649. class JUCE_API ScrollBar : public Component,
  22650. public AsyncUpdater,
  22651. private Timer
  22652. {
  22653. public:
  22654. /** Creates a Scrollbar.
  22655. @param isVertical whether it should be a vertical or horizontal bar
  22656. @param buttonsAreVisible whether to show the up/down or left/right buttons
  22657. */
  22658. ScrollBar (const bool isVertical,
  22659. const bool buttonsAreVisible = true);
  22660. /** Destructor. */
  22661. ~ScrollBar();
  22662. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  22663. bool isVertical() const throw() { return vertical; }
  22664. /** Changes the scrollbar's direction.
  22665. You'll also need to resize the bar appropriately - this just changes its internal
  22666. layout.
  22667. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  22668. */
  22669. void setOrientation (const bool shouldBeVertical) throw();
  22670. /** Shows or hides the scrollbar's buttons. */
  22671. void setButtonVisibility (const bool buttonsAreVisible);
  22672. /** Tells the scrollbar whether to make itself invisible when not needed.
  22673. The default behaviour is for a scrollbar to become invisible when the thumb
  22674. fills the whole of its range (i.e. when it can't be moved). Setting this
  22675. value to false forces the bar to always be visible.
  22676. */
  22677. void setAutoHide (const bool shouldHideWhenFullRange);
  22678. /** Sets the minimum and maximum values that the bar will move between.
  22679. The bar's thumb will always be constrained so that the top of the thumb
  22680. will be >= minimum, and the bottom of the thumb <= maximum.
  22681. @see setCurrentRange
  22682. */
  22683. void setRangeLimits (const double minimum,
  22684. const double maximum) throw();
  22685. /** Returns the lower value that the thumb can be set to.
  22686. This is the value set by setRangeLimits().
  22687. */
  22688. double getMinimumRangeLimit() const throw() { return minimum; }
  22689. /** Returns the upper value that the thumb can be set to.
  22690. This is the value set by setRangeLimits().
  22691. */
  22692. double getMaximumRangeLimit() const throw() { return maximum; }
  22693. /** Changes the position of the scrollbar's 'thumb'.
  22694. This sets both the position and size of the thumb - to just set the position without
  22695. changing the size, you can use setCurrentRangeStart().
  22696. If this method call actually changes the scrollbar's position, it will trigger an
  22697. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22698. are registered.
  22699. @param newStart the top (or left) of the thumb, in the range
  22700. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  22701. value is beyond these limits, it will be clipped.
  22702. @param newSize the size of the thumb, such that
  22703. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  22704. size is beyond these limits, it will be clipped.
  22705. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  22706. */
  22707. void setCurrentRange (double newStart,
  22708. double newSize) throw();
  22709. /** Moves the bar's thumb position.
  22710. This will move the thumb position without changing the thumb size. Note
  22711. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  22712. If this method call actually changes the scrollbar's position, it will trigger an
  22713. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  22714. are registered.
  22715. @see setCurrentRange
  22716. */
  22717. void setCurrentRangeStart (double newStart) throw();
  22718. /** Returns the position of the top of the thumb.
  22719. @see setCurrentRangeStart
  22720. */
  22721. double getCurrentRangeStart() const throw() { return rangeStart; }
  22722. /** Returns the current size of the thumb.
  22723. @see setCurrentRange
  22724. */
  22725. double getCurrentRangeSize() const throw() { return rangeSize; }
  22726. /** Sets the amount by which the up and down buttons will move the bar.
  22727. The value here is in terms of the total range, and is added or subtracted
  22728. from the thumb position when the user clicks an up/down (or left/right) button.
  22729. */
  22730. void setSingleStepSize (const double newSingleStepSize) throw();
  22731. /** Moves the scrollbar by a number of single-steps.
  22732. This will move the bar by a multiple of its single-step interval (as
  22733. specified using the setSingleStepSize() method).
  22734. A positive value here will move the bar down or to the right, a negative
  22735. value moves it up or to the left.
  22736. */
  22737. void moveScrollbarInSteps (const int howManySteps) throw();
  22738. /** Moves the scroll bar up or down in pages.
  22739. This will move the bar by a multiple of its current thumb size, effectively
  22740. doing a page-up or down.
  22741. A positive value here will move the bar down or to the right, a negative
  22742. value moves it up or to the left.
  22743. */
  22744. void moveScrollbarInPages (const int howManyPages) throw();
  22745. /** Scrolls to the top (or left).
  22746. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  22747. */
  22748. void scrollToTop() throw();
  22749. /** Scrolls to the bottom (or right).
  22750. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  22751. */
  22752. void scrollToBottom() throw();
  22753. /** Changes the delay before the up and down buttons autorepeat when they are held
  22754. down.
  22755. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  22756. @see Button::setRepeatSpeed
  22757. */
  22758. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  22759. const int repeatDelayInMillisecs,
  22760. const int minimumDelayInMillisecs = -1) throw();
  22761. /** A set of colour IDs to use to change the colour of various aspects of the component.
  22762. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22763. methods.
  22764. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22765. */
  22766. enum ColourIds
  22767. {
  22768. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  22769. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  22770. trackColourId = 0x1000401 /**< A base colour to use for the slot area of the bar. The look and feel will probably use variations on this colour. */
  22771. };
  22772. /** Registers a listener that will be called when the scrollbar is moved. */
  22773. void addListener (ScrollBarListener* const listener) throw();
  22774. /** Deregisters a previously-registered listener. */
  22775. void removeListener (ScrollBarListener* const listener) throw();
  22776. /** @internal */
  22777. bool keyPressed (const KeyPress& key);
  22778. /** @internal */
  22779. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22780. /** @internal */
  22781. void lookAndFeelChanged();
  22782. /** @internal */
  22783. void handleAsyncUpdate();
  22784. /** @internal */
  22785. void mouseDown (const MouseEvent& e);
  22786. /** @internal */
  22787. void mouseDrag (const MouseEvent& e);
  22788. /** @internal */
  22789. void mouseUp (const MouseEvent& e);
  22790. /** @internal */
  22791. void paint (Graphics& g);
  22792. /** @internal */
  22793. void resized();
  22794. juce_UseDebuggingNewOperator
  22795. private:
  22796. double minimum, maximum;
  22797. double rangeStart, rangeSize;
  22798. double singleStepSize, dragStartRange;
  22799. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  22800. int dragStartMousePos, lastMousePos;
  22801. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  22802. bool vertical, isDraggingThumb, alwaysVisible;
  22803. Button* upButton;
  22804. Button* downButton;
  22805. SortedSet <void*> listeners;
  22806. void updateThumbPosition() throw();
  22807. void timerCallback();
  22808. ScrollBar (const ScrollBar&);
  22809. const ScrollBar& operator= (const ScrollBar&);
  22810. };
  22811. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  22812. /********* End of inlined file: juce_ScrollBar.h *********/
  22813. /**
  22814. A Viewport is used to contain a larger child component, and allows the child
  22815. to be automatically scrolled around.
  22816. To use a Viewport, just create one and set the component that goes inside it
  22817. using the setViewedComponent() method. When the child component changes size,
  22818. the Viewport will adjust its scrollbars accordingly.
  22819. A subclass of the viewport can be created which will receive calls to its
  22820. visibleAreaChanged() method when the subcomponent changes position or size.
  22821. */
  22822. class JUCE_API Viewport : public Component,
  22823. private ComponentListener,
  22824. private ScrollBarListener
  22825. {
  22826. public:
  22827. /** Creates a Viewport.
  22828. The viewport is initially empty - use the setViewedComponent() method to
  22829. add a child component for it to manage.
  22830. */
  22831. Viewport (const String& componentName = String::empty);
  22832. /** Destructor. */
  22833. ~Viewport();
  22834. /** Sets the component that this viewport will contain and scroll around.
  22835. This will add the given component to this Viewport and position it at
  22836. (0, 0).
  22837. (Don't add or remove any child components directly using the normal
  22838. Component::addChildComponent() methods).
  22839. @param newViewedComponent the component to add to this viewport (this pointer
  22840. may be null). The component passed in will be deleted
  22841. by the Viewport when it's no longer needed
  22842. @see getViewedComponent
  22843. */
  22844. void setViewedComponent (Component* const newViewedComponent);
  22845. /** Returns the component that's currently being used inside the Viewport.
  22846. @see setViewedComponent
  22847. */
  22848. Component* getViewedComponent() const throw() { return contentComp; }
  22849. /** Changes the position of the viewed component.
  22850. The inner component will be moved so that the pixel at the top left of
  22851. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  22852. within the inner component.
  22853. This will update the scrollbars and might cause a call to visibleAreaChanged().
  22854. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  22855. */
  22856. void setViewPosition (const int xPixelsOffset,
  22857. const int yPixelsOffset);
  22858. /** Changes the view position as a proportion of the distance it can move.
  22859. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  22860. visible area in the top-left, and (1, 1) would put it as far down and
  22861. to the right as it's possible to go whilst keeping the child component
  22862. on-screen.
  22863. */
  22864. void setViewPositionProportionately (const double proportionX,
  22865. const double proportionY);
  22866. /** Returns the position within the child component of the top-left of its visible area.
  22867. @see getViewWidth, setViewPosition
  22868. */
  22869. int getViewPositionX() const throw() { return lastVX; }
  22870. /** Returns the position within the child component of the top-left of its visible area.
  22871. @see getViewHeight, setViewPosition
  22872. */
  22873. int getViewPositionY() const throw() { return lastVY; }
  22874. /** Returns the width of the visible area of the child component.
  22875. This may be less than the width of this Viewport if there's a vertical scrollbar
  22876. or if the child component is itself smaller.
  22877. */
  22878. int getViewWidth() const throw() { return lastVW; }
  22879. /** Returns the height of the visible area of the child component.
  22880. This may be less than the height of this Viewport if there's a horizontal scrollbar
  22881. or if the child component is itself smaller.
  22882. */
  22883. int getViewHeight() const throw() { return lastVH; }
  22884. /** Returns the width available within this component for the contents.
  22885. This will be the width of the viewport component minus the width of a
  22886. vertical scrollbar (if visible).
  22887. */
  22888. int getMaximumVisibleWidth() const throw();
  22889. /** Returns the height available within this component for the contents.
  22890. This will be the height of the viewport component minus the space taken up
  22891. by a horizontal scrollbar (if visible).
  22892. */
  22893. int getMaximumVisibleHeight() const throw();
  22894. /** Callback method that is called when the visible area changes.
  22895. This will be called when the visible area is moved either be scrolling or
  22896. by calls to setViewPosition(), etc.
  22897. */
  22898. virtual void visibleAreaChanged (int visibleX, int visibleY,
  22899. int visibleW, int visibleH);
  22900. /** Turns scrollbars on or off.
  22901. If set to false, the scrollbars won't ever appear. When true (the default)
  22902. they will appear only when needed.
  22903. */
  22904. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  22905. const bool showHorizontalScrollbarIfNeeded);
  22906. /** True if the vertical scrollbar is enabled.
  22907. @see setScrollBarsShown
  22908. */
  22909. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  22910. /** True if the horizontal scrollbar is enabled.
  22911. @see setScrollBarsShown
  22912. */
  22913. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  22914. /** Changes the width of the scrollbars.
  22915. If this isn't specified, the default width from the LookAndFeel class will be used.
  22916. @see LookAndFeel::getDefaultScrollbarWidth
  22917. */
  22918. void setScrollBarThickness (const int thickness);
  22919. /** Returns the thickness of the scrollbars.
  22920. @see setScrollBarThickness
  22921. */
  22922. int getScrollBarThickness() const throw();
  22923. /** Changes the distance that a single-step click on a scrollbar button
  22924. will move the viewport.
  22925. */
  22926. void setSingleStepSizes (const int stepX, const int stepY);
  22927. /** Shows or hides the buttons on any scrollbars that are used.
  22928. @see ScrollBar::setButtonVisibility
  22929. */
  22930. void setScrollBarButtonVisibility (const bool buttonsVisible);
  22931. /** Returns a pointer to the scrollbar component being used.
  22932. Handy if you need to customise the bar somehow.
  22933. */
  22934. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  22935. /** Returns a pointer to the scrollbar component being used.
  22936. Handy if you need to customise the bar somehow.
  22937. */
  22938. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  22939. juce_UseDebuggingNewOperator
  22940. /** @internal */
  22941. void resized();
  22942. /** @internal */
  22943. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  22944. /** @internal */
  22945. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22946. /** @internal */
  22947. bool keyPressed (const KeyPress& key);
  22948. /** @internal */
  22949. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  22950. /** @internal */
  22951. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  22952. private:
  22953. Component* contentComp;
  22954. int lastVX, lastVY, lastVW, lastVH;
  22955. int scrollBarThickness;
  22956. int singleStepX, singleStepY;
  22957. bool showHScrollbar, showVScrollbar;
  22958. Component* contentHolder;
  22959. ScrollBar* verticalScrollBar;
  22960. ScrollBar* horizontalScrollBar;
  22961. void updateVisibleRegion();
  22962. Viewport (const Viewport&);
  22963. const Viewport& operator= (const Viewport&);
  22964. };
  22965. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  22966. /********* End of inlined file: juce_Viewport.h *********/
  22967. /**
  22968. A panel that holds a list of PropertyComponent objects.
  22969. This panel displays a list of PropertyComponents, and allows them to be organised
  22970. into collapsible sections.
  22971. To use, simply create one of these and add your properties to it with addProperties()
  22972. or addSection().
  22973. @see PropertyComponent
  22974. */
  22975. class JUCE_API PropertyPanel : public Component
  22976. {
  22977. public:
  22978. /** Creates an empty property panel. */
  22979. PropertyPanel();
  22980. /** Destructor. */
  22981. ~PropertyPanel();
  22982. /** Deletes all property components from the panel.
  22983. */
  22984. void clear();
  22985. /** Adds a set of properties to the panel.
  22986. The components in the list will be owned by this object and will be automatically
  22987. deleted later on when no longer needed.
  22988. These properties are added without them being inside a named section. If you
  22989. want them to be kept together in a collapsible section, use addSection() instead.
  22990. */
  22991. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  22992. /** Adds a set of properties to the panel.
  22993. These properties are added at the bottom of the list, under a section heading with
  22994. a plus/minus button that allows it to be opened and closed.
  22995. The components in the list will be owned by this object and will be automatically
  22996. deleted later on when no longer needed.
  22997. To add properies without them being in a section, use addProperties().
  22998. */
  22999. void addSection (const String& sectionTitle,
  23000. const Array <PropertyComponent*>& newPropertyComponents,
  23001. const bool shouldSectionInitiallyBeOpen = true);
  23002. /** Calls the refresh() method of all PropertyComponents in the panel */
  23003. void refreshAll() const;
  23004. /** Returns a list of all the names of sections in the panel.
  23005. These are the sections that have been added with addSection().
  23006. */
  23007. const StringArray getSectionNames() const;
  23008. /** Returns true if the section at this index is currently open.
  23009. The index is from 0 up to the number of items returned by getSectionNames().
  23010. */
  23011. bool isSectionOpen (const int sectionIndex) const;
  23012. /** Opens or closes one of the sections.
  23013. The index is from 0 up to the number of items returned by getSectionNames().
  23014. */
  23015. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  23016. /** Enables or disables one of the sections.
  23017. The index is from 0 up to the number of items returned by getSectionNames().
  23018. */
  23019. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  23020. /** Saves the current state of open/closed sections so it can be restored later.
  23021. The caller is responsible for deleting the object that is returned.
  23022. To restore this state, use restoreOpennessState().
  23023. @see restoreOpennessState
  23024. */
  23025. XmlElement* getOpennessState() const;
  23026. /** Restores a previously saved arrangement of open/closed sections.
  23027. This will try to restore a snapshot of the panel's state that was created by
  23028. the getOpennessState() method. If any of the sections named in the original
  23029. XML aren't present, they will be ignored.
  23030. @see getOpennessState
  23031. */
  23032. void restoreOpennessState (const XmlElement& newState);
  23033. /** Sets a message to be displayed when there are no properties in the panel.
  23034. The default message is "nothing selected".
  23035. */
  23036. void setMessageWhenEmpty (const String& newMessage);
  23037. /** Returns the message that is displayed when there are no properties.
  23038. @see setMessageWhenEmpty
  23039. */
  23040. const String& getMessageWhenEmpty() const throw();
  23041. /** @internal */
  23042. void paint (Graphics& g);
  23043. /** @internal */
  23044. void resized();
  23045. juce_UseDebuggingNewOperator
  23046. private:
  23047. Viewport* viewport;
  23048. Component* propertyHolderComponent;
  23049. String messageWhenEmpty;
  23050. void updatePropHolderLayout() const;
  23051. void updatePropHolderLayout (const int width) const;
  23052. };
  23053. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  23054. /********* End of inlined file: juce_PropertyPanel.h *********/
  23055. /**
  23056. A type of UI component that displays the parameters of an AudioProcessor as
  23057. a simple list of sliders.
  23058. This can be used for showing an editor for a processor that doesn't supply
  23059. its own custom editor.
  23060. @see AudioProcessor
  23061. */
  23062. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  23063. {
  23064. public:
  23065. GenericAudioProcessorEditor (AudioProcessor* const owner);
  23066. ~GenericAudioProcessorEditor();
  23067. void paint (Graphics& g);
  23068. void resized();
  23069. juce_UseDebuggingNewOperator
  23070. private:
  23071. PropertyPanel* panel;
  23072. };
  23073. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23074. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  23075. #endif
  23076. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23077. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  23078. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23079. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23080. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  23081. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23082. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23083. /********* Start of inlined file: juce_AudioSource.h *********/
  23084. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23085. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  23086. /**
  23087. Used by AudioSource::getNextAudioBlock().
  23088. */
  23089. struct JUCE_API AudioSourceChannelInfo
  23090. {
  23091. /** The destination buffer to fill with audio data.
  23092. When the AudioSource::getNextAudioBlock() method is called, the active section
  23093. of this buffer should be filled with whatever output the source produces.
  23094. Only the samples specified by the startSample and numSamples members of this structure
  23095. should be affected by the call.
  23096. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  23097. method can be treated as the input if the source is performing some kind of filter operation,
  23098. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  23099. a handy way of doing this.
  23100. The number of channels in the buffer could be anything, so the AudioSource
  23101. must cope with this in whatever way is appropriate for its function.
  23102. */
  23103. AudioSampleBuffer* buffer;
  23104. /** The first sample in the buffer from which the callback is expected
  23105. to write data. */
  23106. int startSample;
  23107. /** The number of samples in the buffer which the callback is expected to
  23108. fill with data. */
  23109. int numSamples;
  23110. /** Convenient method to clear the buffer if the source is not producing any data. */
  23111. void clearActiveBufferRegion() const
  23112. {
  23113. if (buffer != 0)
  23114. buffer->clear (startSample, numSamples);
  23115. }
  23116. };
  23117. /**
  23118. Base class for objects that can produce a continuous stream of audio.
  23119. @see AudioFormatReaderSource, ResamplingAudioSource
  23120. */
  23121. class JUCE_API AudioSource
  23122. {
  23123. protected:
  23124. /** Creates an AudioSource. */
  23125. AudioSource() throw() {}
  23126. public:
  23127. /** Destructor. */
  23128. virtual ~AudioSource() {}
  23129. /** Tells the source to prepare for playing.
  23130. The source can use this opportunity to initialise anything it needs to.
  23131. Note that this method could be called more than once in succession without
  23132. a matching call to releaseResources(), so make sure your code is robust and
  23133. can handle that kind of situation.
  23134. @param samplesPerBlockExpected the number of samples that the source
  23135. will be expected to supply each time its
  23136. getNextAudioBlock() method is called. This
  23137. number may vary slightly, because it will be dependent
  23138. on audio hardware callbacks, and these aren't
  23139. guaranteed to always use a constant block size, so
  23140. the source should be able to cope with small variations.
  23141. @param sampleRate the sample rate that the output will be used at - this
  23142. is needed by sources such as tone generators.
  23143. @see releaseResources, getNextAudioBlock
  23144. */
  23145. virtual void prepareToPlay (int samplesPerBlockExpected,
  23146. double sampleRate) = 0;
  23147. /** Allows the source to release anything it no longer needs after playback has stopped.
  23148. This will be called when the source is no longer going to have its getNextAudioBlock()
  23149. method called, so it should release any spare memory, etc. that it might have
  23150. allocated during the prepareToPlay() call.
  23151. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23152. releaseResources(), and it may be called more than once in succession, so make sure your
  23153. code is robust and doesn't make any assumptions about when it will be called.
  23154. @see prepareToPlay, getNextAudioBlock
  23155. */
  23156. virtual void releaseResources() = 0;
  23157. /** Called repeatedly to fetch subsequent blocks of audio data.
  23158. After calling the prepareToPlay() method, this callback will be made each
  23159. time the audio playback hardware (or whatever other destination the audio
  23160. data is going to) needs another block of data.
  23161. It will generally be called on a high-priority system thread, or possibly even
  23162. an interrupt, so be careful not to do too much work here, as that will cause
  23163. audio glitches!
  23164. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23165. */
  23166. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23167. };
  23168. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23169. /********* End of inlined file: juce_AudioSource.h *********/
  23170. /**
  23171. A type of AudioSource which can be repositioned.
  23172. The basic AudioSource just streams continuously with no idea of a current
  23173. time or length, so the PositionableAudioSource is used for a finite stream
  23174. that has a current read position.
  23175. @see AudioSource, AudioTransportSource
  23176. */
  23177. class JUCE_API PositionableAudioSource : public AudioSource
  23178. {
  23179. protected:
  23180. /** Creates the PositionableAudioSource. */
  23181. PositionableAudioSource() throw() {}
  23182. public:
  23183. /** Destructor */
  23184. ~PositionableAudioSource() {}
  23185. /** Tells the stream to move to a new position.
  23186. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23187. should return samples from this position.
  23188. Note that this may be called on a different thread to getNextAudioBlock(),
  23189. so the subclass should make sure it's synchronised.
  23190. */
  23191. virtual void setNextReadPosition (int newPosition) = 0;
  23192. /** Returns the position from which the next block will be returned.
  23193. @see setNextReadPosition
  23194. */
  23195. virtual int getNextReadPosition() const = 0;
  23196. /** Returns the total length of the stream (in samples). */
  23197. virtual int getTotalLength() const = 0;
  23198. /** Returns true if this source is actually playing in a loop. */
  23199. virtual bool isLooping() const = 0;
  23200. };
  23201. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23202. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23203. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23204. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23205. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23206. class AudioFormat;
  23207. /**
  23208. Reads samples from an audio file stream.
  23209. A subclass that reads a specific type of audio format will be created by
  23210. an AudioFormat object.
  23211. @see AudioFormat, AudioFormatWriter
  23212. */
  23213. class JUCE_API AudioFormatReader
  23214. {
  23215. protected:
  23216. /** Creates an AudioFormatReader object.
  23217. @param sourceStream the stream to read from - this will be deleted
  23218. by this object when it is no longer needed. (Some
  23219. specialised readers might not use this parameter and
  23220. can leave it as 0).
  23221. @param formatName the description that will be returned by the getFormatName()
  23222. method
  23223. */
  23224. AudioFormatReader (InputStream* const sourceStream,
  23225. const String& formatName);
  23226. public:
  23227. /** Destructor. */
  23228. virtual ~AudioFormatReader();
  23229. /** Returns a description of what type of format this is.
  23230. E.g. "AIFF"
  23231. */
  23232. const String getFormatName() const throw() { return formatName; }
  23233. /** Reads samples from the stream.
  23234. @param destSamples an array of buffers into which the sample data for each
  23235. channel will be written.
  23236. If the format is fixed-point, each channel will be written
  23237. as an array of 32-bit signed integers using the full
  23238. range -0x80000000 to 0x7fffffff, regardless of the source's
  23239. bit-depth. If it is a floating-point format, you should cast
  23240. the resulting array to a (float**) to get the values (in the
  23241. range -1.0 to 1.0 or beyond)
  23242. If the format is stereo, then destSamples[0] is the left channel
  23243. data, and destSamples[1] is the right channel.
  23244. The array passed in should be zero-terminated, and it's ok to
  23245. pass in an array with a different number of channels than
  23246. the number in the stream, so if you pass in an array with only
  23247. one channel and the stream is stereo, the reader will
  23248. put a merged sum of the stereo channels into the single
  23249. destination channel.
  23250. @param startSample the offset into the audio stream from which the samples
  23251. should be read, as a number of samples from the start of the
  23252. stream. It's ok for this to be beyond the start or end of the
  23253. available data - any samples that can't be read will be padded
  23254. with zeros.
  23255. @param numSamples the number of samples to read. If this is greater than the
  23256. number of samples available, the result will be padded with
  23257. zeros
  23258. @returns true if the operation succeeded, false if there was an error. Note
  23259. that reading sections of data beyond the extent of the stream isn't an
  23260. error - the reader should just return zeros for these regions
  23261. @see readMaxLevels
  23262. */
  23263. virtual bool read (int** destSamples,
  23264. int64 startSample,
  23265. int numSamples) = 0;
  23266. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23267. This will read a block of samples from the stream, and measure the
  23268. highest and lowest sample levels from the channels in that section, returning
  23269. these as normalised floating-point levels.
  23270. @param startSample the offset into the audio stream to start reading from. It's
  23271. ok for this to be beyond the start or end of the stream.
  23272. @param numSamples how many samples to read
  23273. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23274. @param highestLeft on return, this is the highest absolute sample from the left channel
  23275. @param lowestRight on return, this is the lowest absolute sample from the right
  23276. channel (if there is one)
  23277. @param highestRight on return, this is the highest absolute sample from the right
  23278. channel (if there is one)
  23279. @see read
  23280. */
  23281. virtual void readMaxLevels (int64 startSample,
  23282. int64 numSamples,
  23283. float& lowestLeft,
  23284. float& highestLeft,
  23285. float& lowestRight,
  23286. float& highestRight);
  23287. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23288. This will read from the source, either forwards or backwards between two sample
  23289. positions, until it finds a sample whose magnitude lies between two specified levels.
  23290. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23291. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23292. points when you're searching for a continuous range of samples
  23293. @param startSample the first sample to look at
  23294. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23295. the search will go backwards
  23296. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23297. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23298. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23299. of this many consecutive samples, all of which lie
  23300. within the target range. When it finds such a sequence,
  23301. it returns the position of the first in-range sample
  23302. it found (i.e. the earliest one if scanning forwards, the
  23303. latest one if scanning backwards)
  23304. */
  23305. int64 searchForLevel (int64 startSample,
  23306. int64 numSamplesToSearch,
  23307. const double magnitudeRangeMinimum,
  23308. const double magnitudeRangeMaximum,
  23309. const int minimumConsecutiveSamples);
  23310. /** The sample-rate of the stream. */
  23311. double sampleRate;
  23312. /** The number of bits per sample, e.g. 16, 24, 32. */
  23313. unsigned int bitsPerSample;
  23314. /** The total number of samples in the audio stream. */
  23315. int64 lengthInSamples;
  23316. /** The total number of channels in the audio stream. */
  23317. unsigned int numChannels;
  23318. /** Indicates whether the data is floating-point or fixed. */
  23319. bool usesFloatingPointData;
  23320. /** A set of metadata values that the reader has pulled out of the stream.
  23321. Exactly what these values are depends on the format, so you can
  23322. check out the format implementation code to see what kind of stuff
  23323. they understand.
  23324. */
  23325. StringPairArray metadataValues;
  23326. /** The input stream, for use by subclasses. */
  23327. InputStream* input;
  23328. juce_UseDebuggingNewOperator
  23329. private:
  23330. String formatName;
  23331. AudioFormatReader (const AudioFormatReader&);
  23332. const AudioFormatReader& operator= (const AudioFormatReader&);
  23333. };
  23334. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23335. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23336. /**
  23337. A type of AudioSource that will read from an AudioFormatReader.
  23338. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23339. */
  23340. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23341. {
  23342. public:
  23343. /** Creates an AudioFormatReaderSource for a given reader.
  23344. @param sourceReader the reader to use as the data source
  23345. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23346. when this object is deleted; if false it will be
  23347. left up to the caller to manage its lifetime
  23348. */
  23349. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23350. const bool deleteReaderWhenThisIsDeleted);
  23351. /** Destructor. */
  23352. ~AudioFormatReaderSource();
  23353. /** Toggles loop-mode.
  23354. If set to true, it will continuously loop the input source. If false,
  23355. it will just emit silence after the source has finished.
  23356. @see isLooping
  23357. */
  23358. void setLooping (const bool shouldLoop) throw();
  23359. /** Returns whether loop-mode is turned on or not. */
  23360. bool isLooping() const { return looping; }
  23361. /** Returns the reader that's being used. */
  23362. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23363. /** Implementation of the AudioSource method. */
  23364. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23365. /** Implementation of the AudioSource method. */
  23366. void releaseResources();
  23367. /** Implementation of the AudioSource method. */
  23368. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23369. /** Implements the PositionableAudioSource method. */
  23370. void setNextReadPosition (int newPosition);
  23371. /** Implements the PositionableAudioSource method. */
  23372. int getNextReadPosition() const;
  23373. /** Implements the PositionableAudioSource method. */
  23374. int getTotalLength() const;
  23375. juce_UseDebuggingNewOperator
  23376. private:
  23377. AudioFormatReader* reader;
  23378. bool deleteReader;
  23379. int volatile nextPlayPos;
  23380. bool volatile looping;
  23381. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23382. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23383. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23384. };
  23385. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23386. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23387. #endif
  23388. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23389. #endif
  23390. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23391. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23392. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23393. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23394. /**
  23395. Wrapper class to continuously stream audio from an audio source to an
  23396. AudioIODevice.
  23397. This object acts as an AudioIODeviceCallback, so can be attached to an
  23398. output device, and will stream audio from an AudioSource.
  23399. */
  23400. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23401. {
  23402. public:
  23403. /** Creates an empty AudioSourcePlayer. */
  23404. AudioSourcePlayer();
  23405. /** Destructor.
  23406. Make sure this object isn't still being used by an AudioIODevice before
  23407. deleting it!
  23408. */
  23409. virtual ~AudioSourcePlayer();
  23410. /** Changes the current audio source to play from.
  23411. If the source passed in is already being used, this method will do nothing.
  23412. If the source is not null, its prepareToPlay() method will be called
  23413. before it starts being used for playback.
  23414. If there's another source currently playing, its releaseResources() method
  23415. will be called after it has been swapped for the new one.
  23416. @param newSource the new source to use - this will NOT be deleted
  23417. by this object when no longer needed, so it's the
  23418. caller's responsibility to manage it.
  23419. */
  23420. void setSource (AudioSource* newSource);
  23421. /** Returns the source that's playing.
  23422. May return 0 if there's no source.
  23423. */
  23424. AudioSource* getCurrentSource() const throw() { return source; }
  23425. /** Sets a gain to apply to the audio data. */
  23426. void setGain (const float newGain) throw();
  23427. /** Implementation of the AudioIODeviceCallback method. */
  23428. void audioDeviceIOCallback (const float** inputChannelData,
  23429. int totalNumInputChannels,
  23430. float** outputChannelData,
  23431. int totalNumOutputChannels,
  23432. int numSamples);
  23433. /** Implementation of the AudioIODeviceCallback method. */
  23434. void audioDeviceAboutToStart (AudioIODevice* device);
  23435. /** Implementation of the AudioIODeviceCallback method. */
  23436. void audioDeviceStopped();
  23437. juce_UseDebuggingNewOperator
  23438. private:
  23439. CriticalSection readLock;
  23440. AudioSource* source;
  23441. double sampleRate;
  23442. int bufferSize;
  23443. float* channels [128];
  23444. float* outputChans [128];
  23445. const float* inputChans [128];
  23446. AudioSampleBuffer tempBuffer;
  23447. float lastGain, gain;
  23448. AudioSourcePlayer (const AudioSourcePlayer&);
  23449. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23450. };
  23451. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23452. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23453. #endif
  23454. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23455. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23456. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23457. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23458. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23459. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23460. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23461. /**
  23462. An AudioSource which takes another source as input, and buffers it using a thread.
  23463. Create this as a wrapper around another thread, and it will read-ahead with
  23464. a background thread to smooth out playback. You can either create one of these
  23465. directly, or use it indirectly using an AudioTransportSource.
  23466. @see PositionableAudioSource, AudioTransportSource
  23467. */
  23468. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23469. {
  23470. public:
  23471. /** Creates a BufferingAudioSource.
  23472. @param source the input source to read from
  23473. @param deleteSourceWhenDeleted if true, then the input source object will
  23474. be deleted when this object is deleted
  23475. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23476. */
  23477. BufferingAudioSource (PositionableAudioSource* source,
  23478. const bool deleteSourceWhenDeleted,
  23479. int numberOfSamplesToBuffer);
  23480. /** Destructor.
  23481. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23482. flag was set in the constructor.
  23483. */
  23484. ~BufferingAudioSource();
  23485. /** Implementation of the AudioSource method. */
  23486. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23487. /** Implementation of the AudioSource method. */
  23488. void releaseResources();
  23489. /** Implementation of the AudioSource method. */
  23490. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23491. /** Implements the PositionableAudioSource method. */
  23492. void setNextReadPosition (int newPosition);
  23493. /** Implements the PositionableAudioSource method. */
  23494. int getNextReadPosition() const;
  23495. /** Implements the PositionableAudioSource method. */
  23496. int getTotalLength() const { return source->getTotalLength(); }
  23497. /** Implements the PositionableAudioSource method. */
  23498. bool isLooping() const { return source->isLooping(); }
  23499. juce_UseDebuggingNewOperator
  23500. private:
  23501. PositionableAudioSource* source;
  23502. bool deleteSourceWhenDeleted;
  23503. int numberOfSamplesToBuffer;
  23504. AudioSampleBuffer buffer;
  23505. CriticalSection bufferStartPosLock;
  23506. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23507. bool wasSourceLooping;
  23508. double volatile sampleRate;
  23509. friend class SharedBufferingAudioSourceThread;
  23510. bool readNextBufferChunk();
  23511. void readBufferSection (int start, int length, int bufferOffset);
  23512. BufferingAudioSource (const BufferingAudioSource&);
  23513. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23514. };
  23515. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23516. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23517. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23518. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23519. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23520. /**
  23521. A type of AudioSource that takes an input source and changes its sample rate.
  23522. @see AudioSource
  23523. */
  23524. class JUCE_API ResamplingAudioSource : public AudioSource
  23525. {
  23526. public:
  23527. /** Creates a ResamplingAudioSource for a given input source.
  23528. @param inputSource the input source to read from
  23529. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23530. this object is deleted
  23531. */
  23532. ResamplingAudioSource (AudioSource* const inputSource,
  23533. const bool deleteInputWhenDeleted);
  23534. /** Destructor. */
  23535. ~ResamplingAudioSource();
  23536. /** Changes the resampling ratio.
  23537. (This value can be changed at any time, even while the source is running).
  23538. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23539. values will speed it up; lower values will slow it
  23540. down. The ratio must be greater than 0
  23541. */
  23542. void setResamplingRatio (const double samplesInPerOutputSample);
  23543. /** Returns the current resampling ratio.
  23544. This is the value that was set by setResamplingRatio().
  23545. */
  23546. double getResamplingRatio() const throw() { return ratio; }
  23547. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23548. void releaseResources();
  23549. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23550. juce_UseDebuggingNewOperator
  23551. private:
  23552. AudioSource* const input;
  23553. const bool deleteInputWhenDeleted;
  23554. double ratio, lastRatio;
  23555. AudioSampleBuffer buffer;
  23556. int bufferPos, sampsInBuffer;
  23557. double subSampleOffset;
  23558. double coefficients[6];
  23559. CriticalSection ratioLock;
  23560. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23561. void createLowPass (const double proportionalRate);
  23562. struct FilterState
  23563. {
  23564. double x1, x2, y1, y2;
  23565. };
  23566. FilterState filterStates[2];
  23567. void resetFilters();
  23568. void applyFilter (float* samples, int num, FilterState& fs);
  23569. ResamplingAudioSource (const ResamplingAudioSource&);
  23570. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23571. };
  23572. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23573. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23574. /**
  23575. An AudioSource that takes a PositionableAudioSource and allows it to be
  23576. played, stopped, started, etc.
  23577. This can also be told use a buffer and background thread to read ahead, and
  23578. if can correct for different sample-rates.
  23579. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23580. to control playback of an audio file.
  23581. @see AudioSource, AudioSourcePlayer
  23582. */
  23583. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23584. public ChangeBroadcaster
  23585. {
  23586. public:
  23587. /** Creates an AudioTransportSource.
  23588. After creating one of these, use the setSource() method to select an input source.
  23589. */
  23590. AudioTransportSource();
  23591. /** Destructor. */
  23592. ~AudioTransportSource();
  23593. /** Sets the reader that is being used as the input source.
  23594. This will stop playback, reset the position to 0 and change to the new reader.
  23595. The source passed in will not be deleted by this object, so must be managed by
  23596. the caller.
  23597. @param newSource the new input source to use. This may be zero
  23598. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23599. is zero, no reading ahead will be done; if it's
  23600. greater than zero, a BufferingAudioSource will be used
  23601. to do the reading-ahead
  23602. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23603. rate of the source, and playback will be sample-rate
  23604. adjusted to maintain playback at the correct pitch. If
  23605. this is 0, no sample-rate adjustment will be performed
  23606. */
  23607. void setSource (PositionableAudioSource* const newSource,
  23608. int readAheadBufferSize = 0,
  23609. double sourceSampleRateToCorrectFor = 0.0);
  23610. /** Changes the current playback position in the source stream.
  23611. The next time the getNextAudioBlock() method is called, this
  23612. is the time from which it'll read data.
  23613. @see getPosition
  23614. */
  23615. void setPosition (double newPosition);
  23616. /** Returns the position that the next data block will be read from
  23617. This is a time in seconds.
  23618. */
  23619. double getCurrentPosition() const;
  23620. /** Returns true if the player has stopped because its input stream ran out of data.
  23621. */
  23622. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23623. /** Starts playing (if a source has been selected).
  23624. If it starts playing, this will send a message to any ChangeListeners
  23625. that are registered with this object.
  23626. */
  23627. void start();
  23628. /** Stops playing.
  23629. If it's actually playing, this will send a message to any ChangeListeners
  23630. that are registered with this object.
  23631. */
  23632. void stop();
  23633. /** Returns true if it's currently playing. */
  23634. bool isPlaying() const throw() { return playing; }
  23635. /** Changes the gain to apply to the output.
  23636. @param newGain a factor by which to multiply the outgoing samples,
  23637. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23638. */
  23639. void setGain (const float newGain) throw();
  23640. /** Returns the current gain setting.
  23641. @see setGain
  23642. */
  23643. float getGain() const throw() { return gain; }
  23644. /** Implementation of the AudioSource method. */
  23645. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23646. /** Implementation of the AudioSource method. */
  23647. void releaseResources();
  23648. /** Implementation of the AudioSource method. */
  23649. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23650. /** Implements the PositionableAudioSource method. */
  23651. void setNextReadPosition (int newPosition);
  23652. /** Implements the PositionableAudioSource method. */
  23653. int getNextReadPosition() const;
  23654. /** Implements the PositionableAudioSource method. */
  23655. int getTotalLength() const;
  23656. /** Implements the PositionableAudioSource method. */
  23657. bool isLooping() const;
  23658. juce_UseDebuggingNewOperator
  23659. private:
  23660. PositionableAudioSource* source;
  23661. ResamplingAudioSource* resamplerSource;
  23662. BufferingAudioSource* bufferingSource;
  23663. PositionableAudioSource* positionableSource;
  23664. AudioSource* masterSource;
  23665. CriticalSection callbackLock;
  23666. float volatile gain, lastGain;
  23667. bool volatile playing, stopped;
  23668. double sampleRate, sourceSampleRate;
  23669. int blockSize, readAheadBufferSize;
  23670. bool isPrepared, inputStreamEOF;
  23671. AudioTransportSource (const AudioTransportSource&);
  23672. const AudioTransportSource& operator= (const AudioTransportSource&);
  23673. };
  23674. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23675. /********* End of inlined file: juce_AudioTransportSource.h *********/
  23676. #endif
  23677. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23678. #endif
  23679. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23680. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23681. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23682. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23683. /**
  23684. An AudioSource that takes the audio from another source, and re-maps its
  23685. input and output channels to a different arrangement.
  23686. You can use this to increase or decrease the number of channels that an
  23687. audio source uses, or to re-order those channels.
  23688. Call the reset() method before using it to set up a default mapping, and then
  23689. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23690. create an appropriate mapping, otherwise no channels will be connected and
  23691. it'll produce silence.
  23692. @see AudioSource
  23693. */
  23694. class ChannelRemappingAudioSource : public AudioSource
  23695. {
  23696. public:
  23697. /** Creates a remapping source that will pass on audio from the given input.
  23698. @param source the input source to use. Make sure that this doesn't
  23699. get deleted before the ChannelRemappingAudioSource object
  23700. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23701. when this object is deleted, if false, the caller is
  23702. responsible for its deletion
  23703. */
  23704. ChannelRemappingAudioSource (AudioSource* const source,
  23705. const bool deleteSourceWhenDeleted);
  23706. /** Destructor. */
  23707. ~ChannelRemappingAudioSource();
  23708. /** Specifies a number of channels that this audio source must produce from its
  23709. getNextAudioBlock() callback.
  23710. */
  23711. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23712. /** Clears any mapped channels.
  23713. After this, no channels are mapped, so this object will produce silence. Create
  23714. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23715. */
  23716. void clearAllMappings() throw();
  23717. /** Creates an input channel mapping.
  23718. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23719. data will be sent to destChannelIndex of our input source.
  23720. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23721. source specified when this object was created).
  23722. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23723. during our getNextAudioBlock() callback
  23724. */
  23725. void setInputChannelMapping (const int destChannelIndex,
  23726. const int sourceChannelIndex) throw();
  23727. /** Creates an output channel mapping.
  23728. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23729. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23730. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23731. (i.e. the source specified when this object was created).
  23732. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23733. during our getNextAudioBlock() callback
  23734. */
  23735. void setOutputChannelMapping (const int sourceChannelIndex,
  23736. const int destChannelIndex) throw();
  23737. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23738. our input audio source.
  23739. */
  23740. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23741. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23742. source will be sent to.
  23743. */
  23744. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23745. /** Returns an XML object to encapsulate the state of the mappings.
  23746. @see restoreFromXml
  23747. */
  23748. XmlElement* createXml() const throw();
  23749. /** Restores the mappings from an XML object created by createXML().
  23750. @see createXml
  23751. */
  23752. void restoreFromXml (const XmlElement& e) throw();
  23753. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23754. void releaseResources();
  23755. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23756. juce_UseDebuggingNewOperator
  23757. private:
  23758. int requiredNumberOfChannels;
  23759. Array <int> remappedInputs, remappedOutputs;
  23760. AudioSource* const source;
  23761. const bool deleteSourceWhenDeleted;
  23762. AudioSampleBuffer buffer;
  23763. AudioSourceChannelInfo remappedInfo;
  23764. CriticalSection lock;
  23765. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23766. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23767. };
  23768. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23769. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  23770. #endif
  23771. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23772. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  23773. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23774. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23775. /**
  23776. An AudioSource that performs an IIR filter on another source.
  23777. */
  23778. class JUCE_API IIRFilterAudioSource : public AudioSource
  23779. {
  23780. public:
  23781. /** Creates a IIRFilterAudioSource for a given input source.
  23782. @param inputSource the input source to read from
  23783. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23784. this object is deleted
  23785. */
  23786. IIRFilterAudioSource (AudioSource* const inputSource,
  23787. const bool deleteInputWhenDeleted);
  23788. /** Destructor. */
  23789. ~IIRFilterAudioSource();
  23790. /** Changes the filter to use the same parameters as the one being passed in.
  23791. */
  23792. void setFilterParameters (const IIRFilter& newSettings);
  23793. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23794. void releaseResources();
  23795. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23796. juce_UseDebuggingNewOperator
  23797. private:
  23798. AudioSource* const input;
  23799. const bool deleteInputWhenDeleted;
  23800. OwnedArray <IIRFilter> iirFilters;
  23801. IIRFilterAudioSource (const IIRFilterAudioSource&);
  23802. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  23803. };
  23804. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23805. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  23806. #endif
  23807. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23808. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  23809. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23810. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23811. /**
  23812. An AudioSource that mixes together the output of a set of other AudioSources.
  23813. Input sources can be added and removed while the mixer is running as long as their
  23814. prepareToPlay() and releaseResources() methods are called before and after adding
  23815. them to the mixer.
  23816. */
  23817. class JUCE_API MixerAudioSource : public AudioSource
  23818. {
  23819. public:
  23820. /** Creates a MixerAudioSource.
  23821. */
  23822. MixerAudioSource();
  23823. /** Destructor. */
  23824. ~MixerAudioSource();
  23825. /** Adds an input source to the mixer.
  23826. If the mixer is running you'll need to make sure that the input source
  23827. is ready to play by calling its prepareToPlay() method before adding it.
  23828. If the mixer is stopped, then its input sources will be automatically
  23829. prepared when the mixer's prepareToPlay() method is called.
  23830. @param newInput the source to add to the mixer
  23831. @param deleteWhenRemoved if true, then this source will be deleted when
  23832. the mixer is deleted or when removeAllInputs() is
  23833. called (unless the source is previously removed
  23834. with the removeInputSource method)
  23835. */
  23836. void addInputSource (AudioSource* newInput,
  23837. const bool deleteWhenRemoved);
  23838. /** Removes an input source.
  23839. If the mixer is running, this will remove the source but not call its
  23840. releaseResources() method, so the caller might want to do this manually.
  23841. @param input the source to remove
  23842. @param deleteSource whether to delete this source after it's been removed
  23843. */
  23844. void removeInputSource (AudioSource* input,
  23845. const bool deleteSource);
  23846. /** Removes all the input sources.
  23847. If the mixer is running, this will remove the sources but not call their
  23848. releaseResources() method, so the caller might want to do this manually.
  23849. Any sources which were added with the deleteWhenRemoved flag set will be
  23850. deleted by this method.
  23851. */
  23852. void removeAllInputs();
  23853. /** Implementation of the AudioSource method.
  23854. This will call prepareToPlay() on all its input sources.
  23855. */
  23856. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23857. /** Implementation of the AudioSource method.
  23858. This will call releaseResources() on all its input sources.
  23859. */
  23860. void releaseResources();
  23861. /** Implementation of the AudioSource method. */
  23862. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23863. juce_UseDebuggingNewOperator
  23864. private:
  23865. VoidArray inputs;
  23866. BitArray inputsToDelete;
  23867. CriticalSection lock;
  23868. AudioSampleBuffer tempBuffer;
  23869. double currentSampleRate;
  23870. int bufferSizeExpected;
  23871. MixerAudioSource (const MixerAudioSource&);
  23872. const MixerAudioSource& operator= (const MixerAudioSource&);
  23873. };
  23874. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23875. /********* End of inlined file: juce_MixerAudioSource.h *********/
  23876. #endif
  23877. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23878. #endif
  23879. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23880. #endif
  23881. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23882. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23883. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23884. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23885. /**
  23886. A simple AudioSource that generates a sine wave.
  23887. */
  23888. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  23889. {
  23890. public:
  23891. /** Creates a ToneGeneratorAudioSource. */
  23892. ToneGeneratorAudioSource();
  23893. /** Destructor. */
  23894. ~ToneGeneratorAudioSource();
  23895. /** Sets the signal's amplitude. */
  23896. void setAmplitude (const float newAmplitude);
  23897. /** Sets the signal's frequency. */
  23898. void setFrequency (const double newFrequencyHz);
  23899. /** Implementation of the AudioSource method. */
  23900. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23901. /** Implementation of the AudioSource method. */
  23902. void releaseResources();
  23903. /** Implementation of the AudioSource method. */
  23904. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23905. juce_UseDebuggingNewOperator
  23906. private:
  23907. double frequency, sampleRate;
  23908. double currentPhase, phasePerSample;
  23909. float amplitude;
  23910. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  23911. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  23912. };
  23913. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23914. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  23915. #endif
  23916. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23917. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  23918. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23919. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23920. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  23921. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23922. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23923. class AudioDeviceManager;
  23924. class Component;
  23925. /**
  23926. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  23927. To get a list of available audio driver types, use the createDeviceTypes()
  23928. method. Each of the objects returned can then be used to list the available
  23929. devices of that type. E.g.
  23930. @code
  23931. OwnedArray <AudioIODeviceType> types;
  23932. AudioIODeviceType::createDeviceTypes (types);
  23933. for (int i = 0; i < types.size(); ++i)
  23934. {
  23935. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  23936. types[i]->scanForDevices(); // This must be called before getting the list of devices
  23937. String deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  23938. for (int j = 0; j < deviceNames.size(); ++j)
  23939. {
  23940. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  23941. ...
  23942. }
  23943. }
  23944. @endcode
  23945. For an easier way of managing audio devices and their settings, have a look at the
  23946. AudioDeviceManager class.
  23947. @see AudioIODevice, AudioDeviceManager
  23948. */
  23949. class JUCE_API AudioIODeviceType
  23950. {
  23951. public:
  23952. /** Returns the name of this type of driver that this object manages.
  23953. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  23954. */
  23955. const String& getTypeName() const throw() { return typeName; }
  23956. /** Refreshes the object's cached list of known devices.
  23957. This must be called at least once before calling getDeviceNames() or any of
  23958. the other device creation methods.
  23959. */
  23960. virtual void scanForDevices() = 0;
  23961. /** Returns the list of available devices of this type.
  23962. The scanForDevices() method must have been called to create this list.
  23963. @param wantInputNames only really used by DirectSound where devices are split up
  23964. into inputs and outputs, this indicates whether to use
  23965. the input or output name to refer to a pair of devices.
  23966. */
  23967. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  23968. /** Returns the name of the default device.
  23969. This will be one of the names from the getDeviceNames() list.
  23970. @param forInput if true, this means that a default input device should be
  23971. returned; if false, it should return the default output
  23972. */
  23973. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  23974. /** Returns the index of a given device in the list of device names.
  23975. If asInput is true, it shows the index in the inputs list, otherwise it
  23976. looks for it in the outputs list.
  23977. */
  23978. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  23979. /** Returns true if two different devices can be used for the input and output.
  23980. */
  23981. virtual bool hasSeparateInputsAndOutputs() const = 0;
  23982. /** Creates one of the devices of this type.
  23983. The deviceName must be one of the strings returned by getDeviceNames(), and
  23984. scanForDevices() must have been called before this method is used.
  23985. */
  23986. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  23987. const String& inputDeviceName) = 0;
  23988. struct DeviceSetupDetails
  23989. {
  23990. AudioDeviceManager* manager;
  23991. int minNumInputChannels, maxNumInputChannels;
  23992. int minNumOutputChannels, maxNumOutputChannels;
  23993. bool useStereoPairs;
  23994. };
  23995. /** Destructor. */
  23996. virtual ~AudioIODeviceType();
  23997. protected:
  23998. AudioIODeviceType (const tchar* const typeName);
  23999. private:
  24000. String typeName;
  24001. AudioIODeviceType (const AudioIODeviceType&);
  24002. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  24003. };
  24004. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24005. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  24006. /********* Start of inlined file: juce_MidiOutput.h *********/
  24007. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24008. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24009. /**
  24010. Represents a midi output device.
  24011. To create one of these, use the static getDevices() method to find out what
  24012. outputs are available, then use the openDevice() method to try to open one.
  24013. @see MidiInput
  24014. */
  24015. class JUCE_API MidiOutput : private Thread
  24016. {
  24017. public:
  24018. /** Returns a list of the available midi output devices.
  24019. You can open one of the devices by passing its index into the
  24020. openDevice() method.
  24021. @see getDefaultDeviceIndex, openDevice
  24022. */
  24023. static const StringArray getDevices();
  24024. /** Returns the index of the default midi output device to use.
  24025. This refers to the index in the list returned by getDevices().
  24026. */
  24027. static int getDefaultDeviceIndex();
  24028. /** Tries to open one of the midi output devices.
  24029. This will return a MidiOutput object if it manages to open it. You can then
  24030. send messages to this device, and delete it when no longer needed.
  24031. If the device can't be opened, this will return a null pointer.
  24032. @param deviceIndex the index of a device from the list returned by getDevices()
  24033. @see getDevices
  24034. */
  24035. static MidiOutput* openDevice (int deviceIndex);
  24036. #if JUCE_LINUX || DOXYGEN
  24037. /** LINUX ONLY - This will try to create a new midi output device.
  24038. This will attempt to create a new midi output device that other apps can connect
  24039. to and use as their midi input.
  24040. Returns 0 if a device can't be created.
  24041. @param deviceName the name to use for the new device
  24042. */
  24043. static MidiOutput* createNewDevice (const String& deviceName);
  24044. #endif
  24045. /** Destructor. */
  24046. virtual ~MidiOutput();
  24047. /** Makes this device output a midi message.
  24048. @see MidiMessage
  24049. */
  24050. virtual void sendMessageNow (const MidiMessage& message);
  24051. /** Sends a midi reset to the device. */
  24052. virtual void reset();
  24053. /** Returns the current volume setting for this device. */
  24054. virtual bool getVolume (float& leftVol,
  24055. float& rightVol);
  24056. /** Changes the overall volume for this device. */
  24057. virtual void setVolume (float leftVol,
  24058. float rightVol);
  24059. /** This lets you supply a block of messages that will be sent out at some point
  24060. in the future.
  24061. The MidiOutput class has an internal thread that can send out timestamped
  24062. messages - this appends a set of messages to its internal buffer, ready for
  24063. sending.
  24064. This will only work if you've already started the thread with startBackgroundThread().
  24065. A time is supplied, at which the block of messages should be sent. This time uses
  24066. the same time base as Time::getMillisecondCounter(), and must be in the future.
  24067. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  24068. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  24069. samplesPerSecondForBuffer value is needed to convert this sample position to a
  24070. real time.
  24071. */
  24072. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  24073. const double millisecondCounterToStartAt,
  24074. double samplesPerSecondForBuffer) throw();
  24075. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  24076. */
  24077. virtual void clearAllPendingMessages() throw();
  24078. /** Starts up a background thread so that the device can send blocks of data.
  24079. Call this to get the device ready, before using sendBlockOfMessages().
  24080. */
  24081. virtual void startBackgroundThread() throw();
  24082. /** Stops the background thread, and clears any pending midi events.
  24083. @see startBackgroundThread
  24084. */
  24085. virtual void stopBackgroundThread() throw();
  24086. juce_UseDebuggingNewOperator
  24087. protected:
  24088. void* internal;
  24089. struct PendingMessage
  24090. {
  24091. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  24092. MidiMessage message;
  24093. PendingMessage* next;
  24094. juce_UseDebuggingNewOperator
  24095. };
  24096. CriticalSection lock;
  24097. PendingMessage* firstMessage;
  24098. MidiOutput() throw();
  24099. MidiOutput (const MidiOutput&);
  24100. void run();
  24101. };
  24102. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24103. /********* End of inlined file: juce_MidiOutput.h *********/
  24104. /********* Start of inlined file: juce_ComboBox.h *********/
  24105. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24106. #define __JUCE_COMBOBOX_JUCEHEADER__
  24107. /********* Start of inlined file: juce_Label.h *********/
  24108. #ifndef __JUCE_LABEL_JUCEHEADER__
  24109. #define __JUCE_LABEL_JUCEHEADER__
  24110. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  24111. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24112. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24113. /**
  24114. Object for monitoring a component, and later testing whether it's still valid.
  24115. Slightly obscure, this one, but it's used internally for making sure that
  24116. after some callbacks, a component hasn't been deleted. It's more reliable than
  24117. just using isValidComponent(), which can provide false-positives if a new
  24118. component is created at the same memory location as an old one.
  24119. */
  24120. class JUCE_API ComponentDeletionWatcher
  24121. {
  24122. public:
  24123. /** Creates a watcher for a given component.
  24124. The component must be valid at the time it's passed in.
  24125. */
  24126. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  24127. /** Destructor. */
  24128. ~ComponentDeletionWatcher() throw();
  24129. /** Returns true if the component has been deleted since the time that this
  24130. object was created.
  24131. */
  24132. bool hasBeenDeleted() const throw();
  24133. /** Returns the component that's being watched, or null if it has been deleted. */
  24134. const Component* getComponent() const throw();
  24135. juce_UseDebuggingNewOperator
  24136. private:
  24137. const Component* const componentToWatch;
  24138. const uint32 componentUID;
  24139. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  24140. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  24141. };
  24142. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24143. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24144. /********* Start of inlined file: juce_TextEditor.h *********/
  24145. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24146. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24147. /********* Start of inlined file: juce_UndoManager.h *********/
  24148. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24149. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24150. /********* Start of inlined file: juce_UndoableAction.h *********/
  24151. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24152. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24153. /**
  24154. Used by the UndoManager class to store an action which can be done
  24155. and undone.
  24156. @see UndoManager
  24157. */
  24158. class JUCE_API UndoableAction
  24159. {
  24160. protected:
  24161. /** Creates an action. */
  24162. UndoableAction() throw() {}
  24163. public:
  24164. /** Destructor. */
  24165. virtual ~UndoableAction() {}
  24166. /** Overridden by a subclass to perform the action.
  24167. This method is called by the UndoManager, and shouldn't be used directly by
  24168. applications.
  24169. Be careful not to make any calls in a perform() method that could call
  24170. recursively back into the UndoManager::perform() method
  24171. @returns true if the action could be performed.
  24172. @see UndoManager::perform
  24173. */
  24174. virtual bool perform() = 0;
  24175. /** Overridden by a subclass to undo the action.
  24176. This method is called by the UndoManager, and shouldn't be used directly by
  24177. applications.
  24178. Be careful not to make any calls in an undo() method that could call
  24179. recursively back into the UndoManager::perform() method
  24180. @returns true if the action could be undone without any errors.
  24181. @see UndoManager::perform
  24182. */
  24183. virtual bool undo() = 0;
  24184. /** Returns a value to indicate how much memory this object takes up.
  24185. Because the UndoManager keeps a list of UndoableActions, this is used
  24186. to work out how much space each one will take up, so that the UndoManager
  24187. can work out how many to keep.
  24188. The default value returned here is 10 - units are arbitrary and
  24189. don't have to be accurate.
  24190. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24191. UndoManager::setMaxNumberOfStoredUnits
  24192. */
  24193. virtual int getSizeInUnits() { return 10; }
  24194. };
  24195. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24196. /********* End of inlined file: juce_UndoableAction.h *********/
  24197. /**
  24198. Manages a list of undo/redo commands.
  24199. An UndoManager object keeps a list of past actions and can use these actions
  24200. to move backwards and forwards through an undo history.
  24201. To use it, create subclasses of UndoableAction which perform all the
  24202. actions you need, then when you need to actually perform an action, create one
  24203. and pass it to the UndoManager's perform() method.
  24204. The manager also uses the concept of 'transactions' to group the actions
  24205. together - all actions performed between calls to beginNewTransaction() are
  24206. grouped together and are all undone/redone as a group.
  24207. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24208. when actions are performed or undone.
  24209. @see UndoableAction
  24210. */
  24211. class JUCE_API UndoManager : public ChangeBroadcaster
  24212. {
  24213. public:
  24214. /** Creates an UndoManager.
  24215. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24216. to indicate how much storage it takes up
  24217. (UndoableAction::getSizeInUnits()), so this
  24218. lets you specify the maximum total number of
  24219. units that the undomanager is allowed to
  24220. keep in memory before letting the older actions
  24221. drop off the end of the list.
  24222. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24223. that will be kept, even if this involves exceeding
  24224. the amount of space specified in maxNumberOfUnitsToKeep
  24225. */
  24226. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24227. const int minimumTransactionsToKeep = 30);
  24228. /** Destructor. */
  24229. ~UndoManager();
  24230. /** Deletes all stored actions in the list. */
  24231. void clearUndoHistory();
  24232. /** Returns the current amount of space to use for storing UndoableAction objects.
  24233. @see setMaxNumberOfStoredUnits
  24234. */
  24235. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24236. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24237. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24238. to indicate how much storage it takes up
  24239. (UndoableAction::getSizeInUnits()), so this
  24240. lets you specify the maximum total number of
  24241. units that the undomanager is allowed to
  24242. keep in memory before letting the older actions
  24243. drop off the end of the list.
  24244. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24245. that will be kept, even if this involves exceeding
  24246. the amount of space specified in maxNumberOfUnitsToKeep
  24247. @see getNumberOfUnitsTakenUpByStoredCommands
  24248. */
  24249. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24250. const int minimumTransactionsToKeep);
  24251. /** Performs an action and adds it to the undo history list.
  24252. @param action the action to perform - this will be deleted by the UndoManager
  24253. when no longer needed
  24254. @param actionName if this string is non-empty, the current transaction will be
  24255. given this name; if it's empty, the current transaction name will
  24256. be left unchanged. See setCurrentTransactionName()
  24257. @returns true if the command succeeds - see UndoableAction::perform
  24258. @see beginNewTransaction
  24259. */
  24260. bool perform (UndoableAction* const action,
  24261. const String& actionName = String::empty);
  24262. /** Starts a new group of actions that together will be treated as a single transaction.
  24263. All actions that are passed to the perform() method between calls to this
  24264. method are grouped together and undone/redone together by a single call to
  24265. undo() or redo().
  24266. @param actionName a description of the transaction that is about to be
  24267. performed
  24268. */
  24269. void beginNewTransaction (const String& actionName = String::empty);
  24270. /** Changes the name stored for the current transaction.
  24271. Each transaction is given a name when the beginNewTransaction() method is
  24272. called, but this can be used to change that name without starting a new
  24273. transaction.
  24274. */
  24275. void setCurrentTransactionName (const String& newName);
  24276. /** Returns true if there's at least one action in the list to undo.
  24277. @see getUndoDescription, undo, canRedo
  24278. */
  24279. bool canUndo() const;
  24280. /** Returns the description of the transaction that would be next to get undone.
  24281. The description returned is the one that was passed into beginNewTransaction
  24282. before the set of actions was performed.
  24283. @see undo
  24284. */
  24285. const String getUndoDescription() const;
  24286. /** Tries to roll-back the last transaction.
  24287. @returns true if the transaction can be undone, and false if it fails, or
  24288. if there aren't any transactions to undo
  24289. */
  24290. bool undo();
  24291. /** Tries to roll-back any actions that were added to the current transaction.
  24292. This will perform an undo() only if there are some actions in the undo list
  24293. that were added after the last call to beginNewTransaction().
  24294. This is useful because it lets you call beginNewTransaction(), then
  24295. perform an operation which may or may not actually perform some actions, and
  24296. then call this method to get rid of any actions that might have been done
  24297. without it rolling back the previous transaction if nothing was actually
  24298. done.
  24299. @returns true if any actions were undone.
  24300. */
  24301. bool undoCurrentTransactionOnly();
  24302. /** Returns a list of the UndoableAction objects that have been performed during the
  24303. transaction that is currently open.
  24304. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24305. were to be called now.
  24306. The first item in the list is the earliest action performed.
  24307. */
  24308. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24309. /** Returns true if there's at least one action in the list to redo.
  24310. @see getRedoDescription, redo, canUndo
  24311. */
  24312. bool canRedo() const;
  24313. /** Returns the description of the transaction that would be next to get redone.
  24314. The description returned is the one that was passed into beginNewTransaction
  24315. before the set of actions was performed.
  24316. @see redo
  24317. */
  24318. const String getRedoDescription() const;
  24319. /** Tries to redo the last transaction that was undone.
  24320. @returns true if the transaction can be redone, and false if it fails, or
  24321. if there aren't any transactions to redo
  24322. */
  24323. bool redo();
  24324. juce_UseDebuggingNewOperator
  24325. private:
  24326. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24327. StringArray transactionNames;
  24328. String currentTransactionName;
  24329. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24330. bool newTransaction, reentrancyCheck;
  24331. // disallow copy constructor
  24332. UndoManager (const UndoManager&);
  24333. const UndoManager& operator= (const UndoManager&);
  24334. };
  24335. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24336. /********* End of inlined file: juce_UndoManager.h *********/
  24337. class TextEditor;
  24338. class TextHolderComponent;
  24339. /**
  24340. Receives callbacks from a TextEditor component when it changes.
  24341. @see TextEditor::addListener
  24342. */
  24343. class JUCE_API TextEditorListener
  24344. {
  24345. public:
  24346. /** Destructor. */
  24347. virtual ~TextEditorListener() {}
  24348. /** Called when the user changes the text in some way. */
  24349. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24350. /** Called when the user presses the return key. */
  24351. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24352. /** Called when the user presses the escape key. */
  24353. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24354. /** Called when the text editor loses focus. */
  24355. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24356. };
  24357. /**
  24358. A component containing text that can be edited.
  24359. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24360. fonts and colours.
  24361. @see TextEditorListener, Label
  24362. */
  24363. class JUCE_API TextEditor : public Component,
  24364. public SettableTooltipClient
  24365. {
  24366. public:
  24367. /** Creates a new, empty text editor.
  24368. @param componentName the name to pass to the component for it to use as its name
  24369. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24370. for all characters that are drawn on screen - e.g. to create
  24371. a password-style textbox containing circular blobs instead of text,
  24372. you could set this value to 0x25cf, which is the unicode character
  24373. for a black splodge (not all fonts include this, though), or 0x2022,
  24374. which is a bullet (probably the best choice for linux).
  24375. */
  24376. TextEditor (const String& componentName = String::empty,
  24377. const tchar passwordCharacter = 0);
  24378. /** Destructor. */
  24379. virtual ~TextEditor();
  24380. /** Puts the editor into either multi- or single-line mode.
  24381. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24382. editor.
  24383. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24384. on if you want a multi-line editor with line-breaks.
  24385. @see isMultiLine, setReturnKeyStartsNewLine
  24386. */
  24387. void setMultiLine (const bool shouldBeMultiLine,
  24388. const bool shouldWordWrap = true);
  24389. /** Returns true if the editor is in multi-line mode.
  24390. */
  24391. bool isMultiLine() const throw();
  24392. /** Changes the behaviour of the return key.
  24393. If set to true, the return key will insert a new-line into the text; if false
  24394. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24395. method. By default this is set to false, and when true it will only insert
  24396. new-lines when in multi-line mode (see setMultiLine()).
  24397. */
  24398. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24399. /** Returns the value set by setReturnKeyStartsNewLine().
  24400. See setReturnKeyStartsNewLine() for more info.
  24401. */
  24402. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24403. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24404. or whether it gets ignored.
  24405. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24406. between components.
  24407. */
  24408. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24409. /** Returns true if the tab key is being used for input.
  24410. @see setTabKeyUsedAsCharacter
  24411. */
  24412. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24413. /** Changes the editor to read-only mode.
  24414. By default, the text editor is not read-only. If you're making it read-only, you
  24415. might also want to call setCaretVisible (false) to get rid of the caret.
  24416. The text can still be highlighted and copied when in read-only mode.
  24417. @see isReadOnly, setCaretVisible
  24418. */
  24419. void setReadOnly (const bool shouldBeReadOnly);
  24420. /** Returns true if the editor is in read-only mode.
  24421. */
  24422. bool isReadOnly() const throw();
  24423. /** Makes the caret visible or invisible.
  24424. By default the caret is visible.
  24425. @see setCaretColour, setCaretPosition
  24426. */
  24427. void setCaretVisible (const bool shouldBeVisible) throw();
  24428. /** Returns true if the caret is enabled.
  24429. @see setCaretVisible
  24430. */
  24431. bool isCaretVisible() const throw() { return caretVisible; }
  24432. /** Enables/disables a vertical scrollbar.
  24433. (This only applies when in multi-line mode). When the text gets too long to fit
  24434. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24435. this is enabled, the scrollbar will be hidden unless it's needed.
  24436. By default the scrollbar is enabled.
  24437. */
  24438. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24439. /** Returns true if scrollbars are enabled.
  24440. @see setScrollbarsShown
  24441. */
  24442. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24443. /** Changes the password character used to disguise the text.
  24444. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24445. for all characters that are drawn on screen - e.g. to create
  24446. a password-style textbox containing circular blobs instead of text,
  24447. you could set this value to 0x25cf, which is the unicode character
  24448. for a black splodge (not all fonts include this, though), or 0x2022,
  24449. which is a bullet (probably the best choice for linux).
  24450. */
  24451. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24452. /** Returns the current password character.
  24453. @see setPasswordCharacter
  24454. l */
  24455. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24456. /** Allows a right-click menu to appear for the editor.
  24457. (This defaults to being enabled).
  24458. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24459. of options such as cut/copy/paste, undo/redo, etc.
  24460. */
  24461. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24462. /** Returns true if the right-click menu is enabled.
  24463. @see setPopupMenuEnabled
  24464. */
  24465. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24466. /** Returns true if a popup-menu is currently being displayed.
  24467. */
  24468. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24469. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24470. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24471. methods.
  24472. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24473. */
  24474. enum ColourIds
  24475. {
  24476. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24477. transparent if necessary. */
  24478. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24479. that because the editor can contain multiple colours, calling this
  24480. method won't change the colour of existing text - to do that, call
  24481. applyFontToAllText() after calling this method.*/
  24482. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24483. the text - this can be transparent if you don't want to show any
  24484. highlighting.*/
  24485. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24486. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24487. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24488. the edge of the component. */
  24489. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24490. the edge of the component when it has focus. */
  24491. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24492. around the edge of the editor. */
  24493. };
  24494. /** Sets the font to use for newly added text.
  24495. This will change the font that will be used next time any text is added or entered
  24496. into the editor. It won't change the font of any existing text - to do that, use
  24497. applyFontToAllText() instead.
  24498. @see applyFontToAllText
  24499. */
  24500. void setFont (const Font& newFont) throw();
  24501. /** Applies a font to all the text in the editor.
  24502. This will also set the current font to use for any new text that's added.
  24503. @see setFont
  24504. */
  24505. void applyFontToAllText (const Font& newFont);
  24506. /** Returns the font that's currently being used for new text.
  24507. @see setFont
  24508. */
  24509. const Font getFont() const throw();
  24510. /** If set to true, focusing on the editor will highlight all its text.
  24511. (Set to false by default).
  24512. This is useful for boxes where you expect the user to re-enter all the
  24513. text when they focus on the component, rather than editing what's already there.
  24514. */
  24515. void setSelectAllWhenFocused (const bool b) throw();
  24516. /** Sets limits on the characters that can be entered.
  24517. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24518. limit is set
  24519. @param allowedCharacters if this is non-empty, then only characters that occur in
  24520. this string are allowed to be entered into the editor.
  24521. */
  24522. void setInputRestrictions (const int maxTextLength,
  24523. const String& allowedCharacters = String::empty) throw();
  24524. /** When the text editor is empty, it can be set to display a message.
  24525. This is handy for things like telling the user what to type in the box - the
  24526. string is only displayed, it's not taken to actually be the contents of
  24527. the editor.
  24528. */
  24529. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24530. /** Changes the size of the scrollbars that are used.
  24531. Handy if you need smaller scrollbars for a small text box.
  24532. */
  24533. void setScrollBarThickness (const int newThicknessPixels);
  24534. /** Shows or hides the buttons on any scrollbars that are used.
  24535. @see ScrollBar::setButtonVisibility
  24536. */
  24537. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24538. /** Registers a listener to be told when things happen to the text.
  24539. @see removeListener
  24540. */
  24541. void addListener (TextEditorListener* const newListener) throw();
  24542. /** Deregisters a listener.
  24543. @see addListener
  24544. */
  24545. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24546. /** Returns the entire contents of the editor. */
  24547. const String getText() const throw();
  24548. /** Returns a section of the contents of the editor. */
  24549. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24550. /** Returns true if there are no characters in the editor.
  24551. This is more efficient than calling getText().isEmpty().
  24552. */
  24553. bool isEmpty() const throw();
  24554. /** Sets the entire content of the editor.
  24555. This will clear the editor and insert the given text (using the current text colour
  24556. and font). You can set the current text colour using
  24557. @code setColour (TextEditor::textColourId, ...);
  24558. @endcode
  24559. @param newText the text to add
  24560. @param sendTextChangeMessage if true, this will cause a change message to
  24561. be sent to all the listeners.
  24562. @see insertText
  24563. */
  24564. void setText (const String& newText,
  24565. const bool sendTextChangeMessage = true);
  24566. /** Inserts some text at the current cursor position.
  24567. If a section of the text is highlighted, it will be replaced by
  24568. this string, otherwise it will be inserted.
  24569. To delete a section of text, you can use setHighlightedRegion() to
  24570. highlight it, and call insertTextAtCursor (String::empty).
  24571. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24572. */
  24573. void insertTextAtCursor (String textToInsert);
  24574. /** Deletes all the text from the editor. */
  24575. void clear();
  24576. /** Deletes the currently selected region, and puts it on the clipboard.
  24577. @see copy, paste, SystemClipboard
  24578. */
  24579. void cut();
  24580. /** Copies any currently selected region to the clipboard.
  24581. @see cut, paste, SystemClipboard
  24582. */
  24583. void copy();
  24584. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24585. @see cut, copy, SystemClipboard
  24586. */
  24587. void paste();
  24588. /** Moves the caret to be in front of a given character.
  24589. @see getCaretPosition
  24590. */
  24591. void setCaretPosition (const int newIndex) throw();
  24592. /** Returns the current index of the caret.
  24593. @see setCaretPosition
  24594. */
  24595. int getCaretPosition() const throw();
  24596. /** Attempts to scroll the text editor so that the caret ends up at
  24597. a specified position.
  24598. This won't affect the caret's position within the text, it tries to scroll
  24599. the entire editor vertically and horizontally so that the caret is sitting
  24600. at the given position (relative to the top-left of this component).
  24601. Depending on the amount of text available, it might not be possible to
  24602. scroll far enough for the caret to reach this exact position, but it
  24603. will go as far as it can in that direction.
  24604. */
  24605. void scrollEditorToPositionCaret (const int desiredCaretX,
  24606. const int desiredCaretY) throw();
  24607. /** Get the graphical position of the caret.
  24608. The rectangle returned is relative to the component's top-left corner.
  24609. @see scrollEditorToPositionCaret
  24610. */
  24611. const Rectangle getCaretRectangle() throw();
  24612. /** Selects a section of the text.
  24613. */
  24614. void setHighlightedRegion (int startIndex,
  24615. int numberOfCharactersToHighlight) throw();
  24616. /** Returns the first character that is selected.
  24617. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  24618. will return 0.
  24619. @see setHighlightedRegion, getHighlightedRegionLength
  24620. */
  24621. int getHighlightedRegionStart() const throw() { return selectionStart; }
  24622. /** Returns the number of characters that are selected.
  24623. @see setHighlightedRegion, getHighlightedRegionStart
  24624. */
  24625. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  24626. /** Returns the section of text that is currently selected. */
  24627. const String getHighlightedText() const throw();
  24628. /** Finds the index of the character at a given position.
  24629. The co-ordinates are relative to the component's top-left.
  24630. */
  24631. int getTextIndexAt (const int x, const int y) throw();
  24632. /** Returns the total width of the text, as it is currently laid-out.
  24633. This may be larger than the size of the TextEditor, and can change when
  24634. the TextEditor is resized or the text changes.
  24635. */
  24636. int getTextWidth() const throw();
  24637. /** Returns the maximum height of the text, as it is currently laid-out.
  24638. This may be larger than the size of the TextEditor, and can change when
  24639. the TextEditor is resized or the text changes.
  24640. */
  24641. int getTextHeight() const throw();
  24642. /** Changes the size of the gap at the top and left-edge of the editor.
  24643. By default there's a gap of 4 pixels.
  24644. */
  24645. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  24646. /** Changes the size of border left around the edge of the component.
  24647. @see getBorder
  24648. */
  24649. void setBorder (const BorderSize& border) throw();
  24650. /** Returns the size of border around the edge of the component.
  24651. @see setBorder
  24652. */
  24653. const BorderSize getBorder() const throw();
  24654. /** Used to disable the auto-scrolling which keeps the cursor visible.
  24655. If true (the default), the editor will scroll when the cursor moves offscreen. If
  24656. set to false, it won't.
  24657. */
  24658. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  24659. /** @internal */
  24660. void paint (Graphics& g);
  24661. /** @internal */
  24662. void paintOverChildren (Graphics& g);
  24663. /** @internal */
  24664. void mouseDown (const MouseEvent& e);
  24665. /** @internal */
  24666. void mouseUp (const MouseEvent& e);
  24667. /** @internal */
  24668. void mouseDrag (const MouseEvent& e);
  24669. /** @internal */
  24670. void mouseDoubleClick (const MouseEvent& e);
  24671. /** @internal */
  24672. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24673. /** @internal */
  24674. bool keyPressed (const KeyPress& key);
  24675. /** @internal */
  24676. bool keyStateChanged();
  24677. /** @internal */
  24678. void focusGained (FocusChangeType cause);
  24679. /** @internal */
  24680. void focusLost (FocusChangeType cause);
  24681. /** @internal */
  24682. void resized();
  24683. /** @internal */
  24684. void enablementChanged();
  24685. /** @internal */
  24686. void colourChanged();
  24687. juce_UseDebuggingNewOperator
  24688. protected:
  24689. /** This adds the items to the popup menu.
  24690. By default it adds the cut/copy/paste items, but you can override this if
  24691. you need to replace these with your own items.
  24692. If you want to add your own items to the existing ones, you can override this,
  24693. call the base class's addPopupMenuItems() method, then append your own items.
  24694. When the menu has been shown, performPopupMenuAction() will be called to
  24695. perform the item that the user has chosen.
  24696. The default menu items will be added using item IDs in the range
  24697. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  24698. menu IDs.
  24699. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  24700. a pointer to the info about it, or may be null if the menu is being triggered
  24701. by some other means.
  24702. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  24703. */
  24704. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  24705. const MouseEvent* mouseClickEvent);
  24706. /** This is called to perform one of the items that was shown on the popup menu.
  24707. If you've overridden addPopupMenuItems(), you should also override this
  24708. to perform the actions that you've added.
  24709. If you've overridden addPopupMenuItems() but have still left the default items
  24710. on the menu, remember to call the superclass's performPopupMenuAction()
  24711. so that it can perform the default actions if that's what the user clicked on.
  24712. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  24713. */
  24714. virtual void performPopupMenuAction (const int menuItemID);
  24715. /** Scrolls the minimum distance needed to get the caret into view. */
  24716. void scrollToMakeSureCursorIsVisible() throw();
  24717. /** @internal */
  24718. void moveCaret (int newCaretPos) throw();
  24719. /** @internal */
  24720. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  24721. /** Used internally to dispatch a text-change message. */
  24722. void textChanged() throw();
  24723. /** Counts the number of characters in the text.
  24724. This is quicker than getting the text as a string if you just need to know
  24725. the length.
  24726. */
  24727. int getTotalNumChars() throw();
  24728. /** Begins a new transaction in the UndoManager.
  24729. */
  24730. void newTransaction() throw();
  24731. /** Used internally to trigger an undo or redo. */
  24732. void doUndoRedo (const bool isRedo);
  24733. /** Can be overridden to intercept return key presses directly */
  24734. virtual void returnPressed();
  24735. /** Can be overridden to intercept escape key presses directly */
  24736. virtual void escapePressed();
  24737. /** @internal */
  24738. void handleCommandMessage (int commandId);
  24739. private:
  24740. Viewport* viewport;
  24741. TextHolderComponent* textHolder;
  24742. BorderSize borderSize;
  24743. bool readOnly : 1;
  24744. bool multiline : 1;
  24745. bool wordWrap : 1;
  24746. bool returnKeyStartsNewLine : 1;
  24747. bool caretVisible : 1;
  24748. bool popupMenuEnabled : 1;
  24749. bool selectAllTextWhenFocused : 1;
  24750. bool scrollbarVisible : 1;
  24751. bool wasFocused : 1;
  24752. bool caretFlashState : 1;
  24753. bool keepCursorOnScreen : 1;
  24754. bool tabKeyUsed : 1;
  24755. bool menuActive : 1;
  24756. UndoManager undoManager;
  24757. float cursorX, cursorY, cursorHeight;
  24758. int maxTextLength;
  24759. int selectionStart, selectionEnd;
  24760. int leftIndent, topIndent;
  24761. unsigned int lastTransactionTime;
  24762. Font currentFont;
  24763. int totalNumChars, caretPosition;
  24764. VoidArray sections;
  24765. String textToShowWhenEmpty;
  24766. Colour colourForTextWhenEmpty;
  24767. tchar passwordCharacter;
  24768. enum
  24769. {
  24770. notDragging,
  24771. draggingSelectionStart,
  24772. draggingSelectionEnd
  24773. } dragType;
  24774. String allowedCharacters;
  24775. SortedSet <void*> listeners;
  24776. friend class TextEditorInsertAction;
  24777. friend class TextEditorRemoveAction;
  24778. void coalesceSimilarSections() throw();
  24779. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  24780. void clearInternal (UndoManager* const um) throw();
  24781. void insert (const String& text,
  24782. const int insertIndex,
  24783. const Font& font,
  24784. const Colour& colour,
  24785. UndoManager* const um,
  24786. const int caretPositionToMoveTo) throw();
  24787. void reinsert (const int insertIndex,
  24788. const VoidArray& sections) throw();
  24789. void remove (const int startIndex,
  24790. int endIndex,
  24791. UndoManager* const um,
  24792. const int caretPositionToMoveTo) throw();
  24793. void getCharPosition (const int index,
  24794. float& x, float& y,
  24795. float& lineHeight) const throw();
  24796. void updateCaretPosition() throw();
  24797. int indexAtPosition (const float x,
  24798. const float y) throw();
  24799. int findWordBreakAfter (const int position) const throw();
  24800. int findWordBreakBefore (const int position) const throw();
  24801. friend class TextHolderComponent;
  24802. friend class TextEditorViewport;
  24803. void drawContent (Graphics& g);
  24804. void updateTextHolderSize() throw();
  24805. float getWordWrapWidth() const throw();
  24806. void timerCallbackInt();
  24807. void repaintCaret();
  24808. void repaintText (int textStartIndex, int textEndIndex);
  24809. TextEditor (const TextEditor&);
  24810. const TextEditor& operator= (const TextEditor&);
  24811. };
  24812. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  24813. /********* End of inlined file: juce_TextEditor.h *********/
  24814. class Label;
  24815. /**
  24816. A class for receiving events from a Label.
  24817. You can register a LabelListener with a Label using the Label::addListener()
  24818. method, and it will be called when the text of the label changes, either because
  24819. of a call to Label::setText() or by the user editing the text (if the label is
  24820. editable).
  24821. @see Label::addListener, Label::removeListener
  24822. */
  24823. class JUCE_API LabelListener
  24824. {
  24825. public:
  24826. /** Destructor. */
  24827. virtual ~LabelListener() {}
  24828. /** Called when a Label's text has changed.
  24829. */
  24830. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  24831. };
  24832. /**
  24833. A component that displays a text string, and can optionally become a text
  24834. editor when clicked.
  24835. */
  24836. class JUCE_API Label : public Component,
  24837. public SettableTooltipClient,
  24838. protected TextEditorListener,
  24839. private ComponentListener
  24840. {
  24841. public:
  24842. /** Creates a Label.
  24843. @param componentName the name to give the component
  24844. @param labelText the text to show in the label
  24845. */
  24846. Label (const String& componentName,
  24847. const String& labelText);
  24848. /** Destructor. */
  24849. ~Label();
  24850. /** Changes the label text.
  24851. If broadcastChangeMessage is true and the new text is different to the current
  24852. text, then the class will broadcast a change message to any LabelListeners that
  24853. are registered.
  24854. */
  24855. void setText (const String& newText,
  24856. const bool broadcastChangeMessage);
  24857. /** Returns the label's current text.
  24858. @param returnActiveEditorContents if this is true and the label is currently
  24859. being edited, then this method will return the
  24860. text as it's being shown in the editor. If false,
  24861. then the value returned here won't be updated until
  24862. the user has finished typing and pressed the return
  24863. key.
  24864. */
  24865. const String getText (const bool returnActiveEditorContents = false) const throw();
  24866. /** Changes the font to use to draw the text.
  24867. @see getFont
  24868. */
  24869. void setFont (const Font& newFont) throw();
  24870. /** Returns the font currently being used.
  24871. @see setFont
  24872. */
  24873. const Font& getFont() const throw();
  24874. /** A set of colour IDs to use to change the colour of various aspects of the label.
  24875. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24876. methods.
  24877. Note that you can also use the constants from TextEditor::ColourIds to change the
  24878. colour of the text editor that is opened when a label is editable.
  24879. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24880. */
  24881. enum ColourIds
  24882. {
  24883. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  24884. textColourId = 0x1000281, /**< The colour for the text. */
  24885. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  24886. Leave this transparent to not have an outline. */
  24887. };
  24888. /** Sets the style of justification to be used for positioning the text.
  24889. (The default is Justification::centredLeft)
  24890. */
  24891. void setJustificationType (const Justification& justification) throw();
  24892. /** Returns the type of justification, as set in setJustificationType(). */
  24893. const Justification getJustificationType() const throw() { return justification; }
  24894. /** Changes the gap that is left between the edge of the component and the text.
  24895. By default there's a small gap left at the sides of the component to allow for
  24896. the drawing of the border, but you can change this if necessary.
  24897. */
  24898. void setBorderSize (int horizontalBorder, int verticalBorder);
  24899. /** Returns the size of the horizontal gap being left around the text.
  24900. */
  24901. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  24902. /** Returns the size of the vertical gap being left around the text.
  24903. */
  24904. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  24905. /** Makes this label "stick to" another component.
  24906. This will cause the label to follow another component around, staying
  24907. either to its left or above it.
  24908. @param owner the component to follow
  24909. @param onLeft if true, the label will stay on the left of its component; if
  24910. false, it will stay above it.
  24911. */
  24912. void attachToComponent (Component* owner,
  24913. const bool onLeft);
  24914. /** If this label has been attached to another component using attachToComponent, this
  24915. returns the other component.
  24916. Returns 0 if the label is not attached.
  24917. */
  24918. Component* getAttachedComponent() const throw() { return ownerComponent; }
  24919. /** If the label is attached to the left of another component, this returns true.
  24920. Returns false if the label is above the other component. This is only relevent if
  24921. attachToComponent() has been called.
  24922. */
  24923. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  24924. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  24925. using ellipsis.
  24926. @see Graphics::drawFittedText
  24927. */
  24928. void setMinimumHorizontalScale (const float newScale);
  24929. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  24930. /** Registers a listener that will be called when the label's text changes. */
  24931. void addListener (LabelListener* const listener) throw();
  24932. /** Deregisters a previously-registered listener. */
  24933. void removeListener (LabelListener* const listener) throw();
  24934. /** Makes the label turn into a TextEditor when clicked.
  24935. By default this is turned off.
  24936. If turned on, then single- or double-clicking will turn the label into
  24937. an editor. If the user then changes the text, then the ChangeBroadcaster
  24938. base class will be used to send change messages to any listeners that
  24939. have registered.
  24940. If the user changes the text, the textWasEdited() method will be called
  24941. afterwards, and subclasses can override this if they need to do anything
  24942. special.
  24943. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  24944. @param editOnDoubleClick if true, a double-click is needed to start editing
  24945. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  24946. edited will discard any changes; if false, then this will
  24947. commit the changes.
  24948. @see showEditor, setEditorColours, TextEditor
  24949. */
  24950. void setEditable (const bool editOnSingleClick,
  24951. const bool editOnDoubleClick = false,
  24952. const bool lossOfFocusDiscardsChanges = false) throw();
  24953. /** Returns true if this option was set using setEditable(). */
  24954. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  24955. /** Returns true if this option was set using setEditable(). */
  24956. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  24957. /** Returns true if this option has been set in a call to setEditable(). */
  24958. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  24959. /** Returns true if the user can edit this label's text. */
  24960. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  24961. /** Makes the editor appear as if the label had been clicked by the user.
  24962. @see textWasEdited, setEditable
  24963. */
  24964. void showEditor();
  24965. /** Hides the editor if it was being shown.
  24966. @param discardCurrentEditorContents if true, the label's text will be
  24967. reset to whatever it was before the editor
  24968. was shown; if false, the current contents of the
  24969. editor will be used to set the label's text
  24970. before it is hidden.
  24971. */
  24972. void hideEditor (const bool discardCurrentEditorContents);
  24973. /** Returns true if the editor is currently focused and active. */
  24974. bool isBeingEdited() const throw();
  24975. juce_UseDebuggingNewOperator
  24976. protected:
  24977. /** @internal */
  24978. void paint (Graphics& g);
  24979. /** @internal */
  24980. void resized();
  24981. /** @internal */
  24982. void mouseUp (const MouseEvent& e);
  24983. /** @internal */
  24984. void mouseDoubleClick (const MouseEvent& e);
  24985. /** @internal */
  24986. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  24987. /** @internal */
  24988. void componentParentHierarchyChanged (Component& component);
  24989. /** @internal */
  24990. void componentVisibilityChanged (Component& component);
  24991. /** @internal */
  24992. void inputAttemptWhenModal();
  24993. /** @internal */
  24994. void focusGained (FocusChangeType);
  24995. /** @internal */
  24996. void enablementChanged();
  24997. /** @internal */
  24998. KeyboardFocusTraverser* createFocusTraverser();
  24999. /** @internal */
  25000. void textEditorTextChanged (TextEditor& editor);
  25001. /** @internal */
  25002. void textEditorReturnKeyPressed (TextEditor& editor);
  25003. /** @internal */
  25004. void textEditorEscapeKeyPressed (TextEditor& editor);
  25005. /** @internal */
  25006. void textEditorFocusLost (TextEditor& editor);
  25007. /** @internal */
  25008. void colourChanged();
  25009. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  25010. Subclasses can override this if they need to customise this component in some way.
  25011. */
  25012. virtual TextEditor* createEditorComponent();
  25013. /** Called after the user changes the text.
  25014. */
  25015. virtual void textWasEdited();
  25016. /** Called when the text has been altered.
  25017. */
  25018. virtual void textWasChanged();
  25019. private:
  25020. String text;
  25021. Font font;
  25022. Justification justification;
  25023. TextEditor* editor;
  25024. SortedSet <void*> listeners;
  25025. Component* ownerComponent;
  25026. ComponentDeletionWatcher* deletionWatcher;
  25027. int horizontalBorderSize, verticalBorderSize;
  25028. float minimumHorizontalScale;
  25029. bool editSingleClick : 1;
  25030. bool editDoubleClick : 1;
  25031. bool lossOfFocusDiscardsChanges : 1;
  25032. bool leftOfOwnerComp : 1;
  25033. bool updateFromTextEditorContents();
  25034. void callChangeListeners();
  25035. Label (const Label&);
  25036. const Label& operator= (const Label&);
  25037. };
  25038. #endif // __JUCE_LABEL_JUCEHEADER__
  25039. /********* End of inlined file: juce_Label.h *********/
  25040. class ComboBox;
  25041. /**
  25042. A class for receiving events from a ComboBox.
  25043. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  25044. method, and it will be called when the selected item in the box changes.
  25045. @see ComboBox::addListener, ComboBox::removeListener
  25046. */
  25047. class JUCE_API ComboBoxListener
  25048. {
  25049. public:
  25050. /** Destructor. */
  25051. virtual ~ComboBoxListener() {}
  25052. /** Called when a ComboBox has its selected item changed.
  25053. */
  25054. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  25055. };
  25056. /**
  25057. A component that lets the user choose from a drop-down list of choices.
  25058. The combo-box has a list of text strings, each with an associated id number,
  25059. that will be shown in the drop-down list when the user clicks on the component.
  25060. The currently selected choice is displayed in the combo-box, and this can
  25061. either be read-only text, or editable.
  25062. To find out when the user selects a different item or edits the text, you
  25063. can register a ComboBoxListener to receive callbacks.
  25064. @see ComboBoxListener
  25065. */
  25066. class JUCE_API ComboBox : public Component,
  25067. public SettableTooltipClient,
  25068. private LabelListener,
  25069. private AsyncUpdater
  25070. {
  25071. public:
  25072. /** Creates a combo-box.
  25073. On construction, the text field will be empty, so you should call the
  25074. setSelectedId() or setText() method to choose the initial value before
  25075. displaying it.
  25076. @param componentName the name to set for the component (see Component::setName())
  25077. */
  25078. ComboBox (const String& componentName);
  25079. /** Destructor. */
  25080. ~ComboBox();
  25081. /** Sets whether the test in the combo-box is editable.
  25082. The default state for a new ComboBox is non-editable, and can only be changed
  25083. by choosing from the drop-down list.
  25084. */
  25085. void setEditableText (const bool isEditable);
  25086. /** Returns true if the text is directly editable.
  25087. @see setEditableText
  25088. */
  25089. bool isTextEditable() const throw();
  25090. /** Sets the style of justification to be used for positioning the text.
  25091. The default is Justification::centredLeft. The text is displayed using a
  25092. Label component inside the ComboBox.
  25093. */
  25094. void setJustificationType (const Justification& justification) throw();
  25095. /** Returns the current justification for the text box.
  25096. @see setJustificationType
  25097. */
  25098. const Justification getJustificationType() const throw();
  25099. /** Adds an item to be shown in the drop-down list.
  25100. @param newItemText the text of the item to show in the list
  25101. @param newItemId an associated ID number that can be set or retrieved - see
  25102. getSelectedId() and setSelectedId()
  25103. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25104. */
  25105. void addItem (const String& newItemText,
  25106. const int newItemId) throw();
  25107. /** Adds a separator line to the drop-down list.
  25108. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25109. */
  25110. void addSeparator() throw();
  25111. /** Adds a heading to the drop-down list, so that you can group the items into
  25112. different sections.
  25113. The headings are indented slightly differently to set them apart from the
  25114. items on the list, and obviously can't be selected. You might want to add
  25115. separators between your sections too.
  25116. @see addItem, addSeparator
  25117. */
  25118. void addSectionHeading (const String& headingName) throw();
  25119. /** This allows items in the drop-down list to be selectively disabled.
  25120. When you add an item, it's enabled by default, but you can call this
  25121. method to change its status.
  25122. If you disable an item which is already selected, this won't change the
  25123. current selection - it just stops the user choosing that item from the list.
  25124. */
  25125. void setItemEnabled (const int itemId,
  25126. const bool isEnabled) throw();
  25127. /** Changes the text for an existing item.
  25128. */
  25129. void changeItemText (const int itemId,
  25130. const String& newText) throw();
  25131. /** Removes all the items from the drop-down list.
  25132. If this call causes the content to be cleared, then a change-message
  25133. will be broadcast unless dontSendChangeMessage is true.
  25134. @see addItem, removeItem, getNumItems
  25135. */
  25136. void clear (const bool dontSendChangeMessage = false);
  25137. /** Returns the number of items that have been added to the list.
  25138. Note that this doesn't include headers or separators.
  25139. */
  25140. int getNumItems() const throw();
  25141. /** Returns the text for one of the items in the list.
  25142. Note that this doesn't include headers or separators.
  25143. @param index the item's index from 0 to (getNumItems() - 1)
  25144. */
  25145. const String getItemText (const int index) const throw();
  25146. /** Returns the ID for one of the items in the list.
  25147. Note that this doesn't include headers or separators.
  25148. @param index the item's index from 0 to (getNumItems() - 1)
  25149. */
  25150. int getItemId (const int index) const throw();
  25151. /** Returns the ID of the item that's currently shown in the box.
  25152. If no item is selected, or if the text is editable and the user
  25153. has entered something which isn't one of the items in the list, then
  25154. this will return 0.
  25155. @see setSelectedId, getSelectedItemIndex, getText
  25156. */
  25157. int getSelectedId() const throw();
  25158. /** Sets one of the items to be the current selection.
  25159. This will set the ComboBox's text to that of the item that matches
  25160. this ID.
  25161. @param newItemId the new item to select
  25162. @param dontSendChangeMessage if set to true, this method won't trigger a
  25163. change notification
  25164. @see getSelectedId, setSelectedItemIndex, setText
  25165. */
  25166. void setSelectedId (const int newItemId,
  25167. const bool dontSendChangeMessage = false) throw();
  25168. /** Returns the index of the item that's currently shown in the box.
  25169. If no item is selected, or if the text is editable and the user
  25170. has entered something which isn't one of the items in the list, then
  25171. this will return -1.
  25172. @see setSelectedItemIndex, getSelectedId, getText
  25173. */
  25174. int getSelectedItemIndex() const throw();
  25175. /** Sets one of the items to be the current selection.
  25176. This will set the ComboBox's text to that of the item at the given
  25177. index in the list.
  25178. @param newItemIndex the new item to select
  25179. @param dontSendChangeMessage if set to true, this method won't trigger a
  25180. change notification
  25181. @see getSelectedItemIndex, setSelectedId, setText
  25182. */
  25183. void setSelectedItemIndex (const int newItemIndex,
  25184. const bool dontSendChangeMessage = false) throw();
  25185. /** Returns the text that is currently shown in the combo-box's text field.
  25186. If the ComboBox has editable text, then this text may have been edited
  25187. by the user; otherwise it will be one of the items from the list, or
  25188. possibly an empty string if nothing was selected.
  25189. @see setText, getSelectedId, getSelectedItemIndex
  25190. */
  25191. const String getText() const throw();
  25192. /** Sets the contents of the combo-box's text field.
  25193. The text passed-in will be set as the current text regardless of whether
  25194. it is one of the items in the list. If the current text isn't one of the
  25195. items, then getSelectedId() will return -1, otherwise it wil return
  25196. the approriate ID.
  25197. @param newText the text to select
  25198. @param dontSendChangeMessage if set to true, this method won't trigger a
  25199. change notification
  25200. @see getText
  25201. */
  25202. void setText (const String& newText,
  25203. const bool dontSendChangeMessage = false) throw();
  25204. /** Programmatically opens the text editor to allow the user to edit the current item.
  25205. This is the same effect as when the box is clicked-on.
  25206. @see Label::showEditor();
  25207. */
  25208. void showEditor();
  25209. /** Registers a listener that will be called when the box's content changes. */
  25210. void addListener (ComboBoxListener* const listener) throw();
  25211. /** Deregisters a previously-registered listener. */
  25212. void removeListener (ComboBoxListener* const listener) throw();
  25213. /** Sets a message to display when there is no item currently selected.
  25214. @see getTextWhenNothingSelected
  25215. */
  25216. void setTextWhenNothingSelected (const String& newMessage) throw();
  25217. /** Returns the text that is shown when no item is selected.
  25218. @see setTextWhenNothingSelected
  25219. */
  25220. const String getTextWhenNothingSelected() const throw();
  25221. /** Sets the message to show when there are no items in the list, and the user clicks
  25222. on the drop-down box.
  25223. By default it just says "no choices", but this lets you change it to something more
  25224. meaningful.
  25225. */
  25226. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25227. /** Returns the text shown when no items have been added to the list.
  25228. @see setTextWhenNoChoicesAvailable
  25229. */
  25230. const String getTextWhenNoChoicesAvailable() const throw();
  25231. /** Gives the ComboBox a tooltip. */
  25232. void setTooltip (const String& newTooltip);
  25233. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25234. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25235. methods.
  25236. To change the colours of the menu that pops up
  25237. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25238. */
  25239. enum ColourIds
  25240. {
  25241. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25242. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25243. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25244. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25245. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25246. };
  25247. /** @internal */
  25248. void labelTextChanged (Label*);
  25249. /** @internal */
  25250. void enablementChanged();
  25251. /** @internal */
  25252. void colourChanged();
  25253. /** @internal */
  25254. void focusGained (Component::FocusChangeType cause);
  25255. /** @internal */
  25256. void focusLost (Component::FocusChangeType cause);
  25257. /** @internal */
  25258. void handleAsyncUpdate();
  25259. /** @internal */
  25260. const String getTooltip() { return label->getTooltip(); }
  25261. /** @internal */
  25262. void mouseDown (const MouseEvent&);
  25263. /** @internal */
  25264. void mouseDrag (const MouseEvent&);
  25265. /** @internal */
  25266. void mouseUp (const MouseEvent&);
  25267. /** @internal */
  25268. void lookAndFeelChanged();
  25269. /** @internal */
  25270. void paint (Graphics&);
  25271. /** @internal */
  25272. void resized();
  25273. /** @internal */
  25274. bool keyStateChanged();
  25275. /** @internal */
  25276. bool keyPressed (const KeyPress&);
  25277. juce_UseDebuggingNewOperator
  25278. private:
  25279. struct ItemInfo
  25280. {
  25281. String name;
  25282. int itemId;
  25283. bool isEnabled : 1, isHeading : 1;
  25284. bool isSeparator() const throw();
  25285. bool isRealItem() const throw();
  25286. };
  25287. OwnedArray <ItemInfo> items;
  25288. int currentIndex;
  25289. bool isButtonDown;
  25290. bool separatorPending;
  25291. bool menuActive;
  25292. SortedSet <void*> listeners;
  25293. Label* label;
  25294. String textWhenNothingSelected, noChoicesMessage;
  25295. void showPopup();
  25296. ItemInfo* getItemForId (const int itemId) const throw();
  25297. ItemInfo* getItemForIndex (const int index) const throw();
  25298. ComboBox (const ComboBox&);
  25299. const ComboBox& operator= (const ComboBox&);
  25300. };
  25301. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25302. /********* End of inlined file: juce_ComboBox.h *********/
  25303. /**
  25304. Manages the state of some audio and midi i/o devices.
  25305. This class keeps tracks of a currently-selected audio device, through
  25306. with which it continuously streams data from an audio callback, as well as
  25307. one or more midi inputs.
  25308. The idea is that your application will create one global instance of this object,
  25309. and let it take care of creating and deleting specific types of audio devices
  25310. internally. So when the device is changed, your callbacks will just keep running
  25311. without having to worry about this.
  25312. The manager can save and reload all of its device settings as XML, which
  25313. makes it very easy for you to save and reload the audio setup of your
  25314. application.
  25315. And to make it easy to let the user change its settings, there's a component
  25316. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25317. device selection/sample-rate/latency controls.
  25318. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25319. call setAudioCallback() to register your audio callback with it, and use that to process
  25320. your audio data.
  25321. The manager also acts as a handy hub for incoming midi messages, allowing a
  25322. listener to register for messages from either a specific midi device, or from whatever
  25323. the current default midi input device is. The listener then doesn't have to worry about
  25324. re-registering with different midi devices if they are changed or deleted.
  25325. And yet another neat trick is that amount of CPU time being used is measured and
  25326. available with the getCpuUsage() method.
  25327. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25328. listeners whenever one of its settings is changed.
  25329. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25330. */
  25331. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25332. {
  25333. public:
  25334. /** Creates a default AudioDeviceManager.
  25335. Initially no audio device will be selected. You should call the initialise() method
  25336. and register an audio callback with setAudioCallback() before it'll be able to
  25337. actually make any noise.
  25338. */
  25339. AudioDeviceManager();
  25340. /** Destructor. */
  25341. ~AudioDeviceManager();
  25342. /**
  25343. This structure holds a set of properties describing the current audio setup.
  25344. @see AudioDeviceManager::setAudioDeviceSetup()
  25345. */
  25346. struct AudioDeviceSetup
  25347. {
  25348. AudioDeviceSetup();
  25349. bool operator== (const AudioDeviceSetup& other) const;
  25350. /** The name of the audio device used for output.
  25351. This may be the same as the input device.
  25352. */
  25353. String outputDeviceName;
  25354. /** The name of the audio device used for input.
  25355. This may be the same as the output device.
  25356. */
  25357. String inputDeviceName;
  25358. /** The current sample rate.
  25359. This rate is used for both the input and output devices.
  25360. */
  25361. double sampleRate;
  25362. /** The buffer size, in samples.
  25363. This buffer size is used for both the input and output devices.
  25364. */
  25365. int bufferSize;
  25366. /** The set of active input channels.
  25367. The bits that are set in this array indicate the channels of the
  25368. input device that are active.
  25369. */
  25370. BitArray inputChannels;
  25371. /** If this is true, it indicates that the inputChannels array
  25372. should be ignored, and instead, the device's default channels
  25373. should be used.
  25374. */
  25375. bool useDefaultInputChannels;
  25376. /** The set of active output channels.
  25377. The bits that are set in this array indicate the channels of the
  25378. input device that are active.
  25379. */
  25380. BitArray outputChannels;
  25381. /** If this is true, it indicates that the outputChannels array
  25382. should be ignored, and instead, the device's default channels
  25383. should be used.
  25384. */
  25385. bool useDefaultOutputChannels;
  25386. };
  25387. /** Opens a set of audio devices ready for use.
  25388. This will attempt to open either a default audio device, or one that was
  25389. previously saved as XML.
  25390. @param numInputChannelsNeeded a minimum number of input channels needed
  25391. by your app.
  25392. @param numOutputChannelsNeeded a minimum number of output channels to open
  25393. @param savedState either a previously-saved state that was produced
  25394. by createStateXml(), or 0 if you want the manager
  25395. to choose the best device to open.
  25396. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25397. fails to open, then a default device will be used
  25398. instead. If false, then on failure, no device is
  25399. opened.
  25400. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25401. name, then that will be used as the default device
  25402. (assuming that there wasn't one specified in the XML).
  25403. The string can actually be a simple wildcard, containing "*"
  25404. and "?" characters
  25405. @param preferredSetupOptions if this is non-null, the structure will be used as the
  25406. set of preferred settings when opening the device. If you
  25407. use this parameter, the preferredDefaultDeviceName
  25408. field will be ignored
  25409. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25410. */
  25411. const String initialise (const int numInputChannelsNeeded,
  25412. const int numOutputChannelsNeeded,
  25413. const XmlElement* const savedState,
  25414. const bool selectDefaultDeviceOnFailure,
  25415. const String& preferredDefaultDeviceName = String::empty,
  25416. const AudioDeviceSetup* preferredSetupOptions = 0);
  25417. /** Returns some XML representing the current state of the manager.
  25418. This stores the current device, its samplerate, block size, etc, and
  25419. can be restored later with initialise().
  25420. */
  25421. XmlElement* createStateXml() const;
  25422. /** Returns the current device properties that are in use.
  25423. @see setAudioDeviceSetup
  25424. */
  25425. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25426. /** Changes the current device or its settings.
  25427. If you want to change a device property, like the current sample rate or
  25428. block size, you can call getAudioDeviceSetup() to retrieve the current
  25429. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  25430. and pass it back into this method to apply the new settings.
  25431. @param newSetup the settings that you'd like to use
  25432. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25433. settings will be taken as having been explicitly chosen by the
  25434. user, and the next time createStateXml() is called, these settings
  25435. will be returned. If it's false, then the device is treated as a
  25436. temporary or default device, and a call to createStateXml() will
  25437. return either the last settings that were made with treatAsChosenDevice
  25438. as true, or the last XML settings that were passed into initialise().
  25439. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25440. @see getAudioDeviceSetup
  25441. */
  25442. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25443. const bool treatAsChosenDevice);
  25444. /** Returns the currently-active audio device. */
  25445. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25446. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25447. void setCurrentAudioDeviceType (const String& type,
  25448. const bool treatAsChosenDevice);
  25449. /** Closes the currently-open device.
  25450. You can call restartLastAudioDevice() later to reopen it in the same state
  25451. that it was just in.
  25452. */
  25453. void closeAudioDevice();
  25454. /** Tries to reload the last audio device that was running.
  25455. Note that this only reloads the last device that was running before
  25456. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25457. and can only be called after a device has been opened with SetAudioDevice().
  25458. If a device is already open, this call will do nothing.
  25459. */
  25460. void restartLastAudioDevice();
  25461. /** Gives the manager an audio callback to use.
  25462. The manager will redirect callbacks from whatever audio device is currently
  25463. in use to this callback object.
  25464. You can pass 0 in here to stop callbacks being made.
  25465. */
  25466. void setAudioCallback (AudioIODeviceCallback* newCallback);
  25467. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25468. Returns a value between 0 and 1.0
  25469. */
  25470. double getCpuUsage() const;
  25471. /** Enables or disables a midi input device.
  25472. The list of devices can be obtained with the MidiInput::getDevices() method.
  25473. Any incoming messages from enabled input devices will be forwarded on to all the
  25474. listeners that have been registered with the addMidiInputCallback() method. They
  25475. can either register for messages from a particular device, or from just the
  25476. "default" midi input.
  25477. Routing the midi input via an AudioDeviceManager means that when a listener
  25478. registers for the default midi input, this default device can be changed by the
  25479. manager without the listeners having to know about it or re-register.
  25480. It also means that a listener can stay registered for a midi input that is disabled
  25481. or not present, so that when the input is re-enabled, the listener will start
  25482. receiving messages again.
  25483. @see addMidiInputCallback, isMidiInputEnabled
  25484. */
  25485. void setMidiInputEnabled (const String& midiInputDeviceName,
  25486. const bool enabled);
  25487. /** Returns true if a given midi input device is being used.
  25488. @see setMidiInputEnabled
  25489. */
  25490. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25491. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25492. The device name can be empty to indicate that it wants events from whatever the
  25493. current "default" device is. Or it can be the name of one of the midi input devices
  25494. (see MidiInput::getDevices() for the names).
  25495. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25496. events forwarded on to listeners.
  25497. */
  25498. void addMidiInputCallback (const String& midiInputDeviceName,
  25499. MidiInputCallback* callback);
  25500. /** Removes a listener that was previously registered with addMidiInputCallback().
  25501. */
  25502. void removeMidiInputCallback (const String& midiInputDeviceName,
  25503. MidiInputCallback* callback);
  25504. /** Sets a midi output device to use as the default.
  25505. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25506. The specified device will be opened automatically and can be retrieved with the
  25507. getDefaultMidiOutput() method.
  25508. Pass in an empty string to deselect all devices. For the default device, you
  25509. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25510. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25511. */
  25512. void setDefaultMidiOutput (const String& deviceName);
  25513. /** Returns the name of the default midi output.
  25514. @see setDefaultMidiOutput, getDefaultMidiOutput
  25515. */
  25516. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25517. /** Returns the current default midi output device.
  25518. If no device has been selected, or the device can't be opened, this will
  25519. return 0.
  25520. @see getDefaultMidiOutputName
  25521. */
  25522. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25523. /**
  25524. */
  25525. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25526. /** Creates a list of available types.
  25527. This will add a set of new AudioIODeviceType objects to the specified list, to
  25528. represent each available types of device.
  25529. You can override this if your app needs to do something specific, like avoid
  25530. using DirectSound devices, etc.
  25531. */
  25532. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25533. /** Plays a beep through the current audio device.
  25534. This is here to allow the audio setup UI panels to easily include a "test"
  25535. button so that the user can check where the audio is coming from.
  25536. */
  25537. void playTestSound();
  25538. /** Turns on level-measuring.
  25539. When enabled, the device manager will measure the peak input level
  25540. across all channels, and you can get this level by calling getCurrentInputLevel().
  25541. This is mainly intended for audio setup UI panels to use to create a mic
  25542. level display, so that the user can check that they've selected the right
  25543. device.
  25544. A simple filter is used to make the level decay smoothly, but this is
  25545. only intended for giving rough feedback, and not for any kind of accurate
  25546. measurement.
  25547. */
  25548. void enableInputLevelMeasurement (const bool enableMeasurement);
  25549. /** Returns the current input level.
  25550. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25551. See enableInputLevelMeasurement() for more info.
  25552. */
  25553. double getCurrentInputLevel() const;
  25554. juce_UseDebuggingNewOperator
  25555. private:
  25556. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25557. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25558. AudioDeviceSetup currentSetup;
  25559. AudioIODevice* currentAudioDevice;
  25560. AudioIODeviceCallback* currentCallback;
  25561. int numInputChansNeeded, numOutputChansNeeded;
  25562. String currentDeviceType;
  25563. BitArray inputChannels, outputChannels;
  25564. XmlElement* lastExplicitSettings;
  25565. mutable bool listNeedsScanning;
  25566. bool useInputNames, inputLevelMeasurementEnabled;
  25567. double inputLevel;
  25568. AudioSampleBuffer* testSound;
  25569. int testSoundPosition;
  25570. StringArray midiInsFromXml;
  25571. OwnedArray <MidiInput> enabledMidiInputs;
  25572. Array <MidiInputCallback*> midiCallbacks;
  25573. Array <MidiInput*> midiCallbackDevices;
  25574. String defaultMidiOutputName;
  25575. MidiOutput* defaultMidiOutput;
  25576. CriticalSection audioCallbackLock, midiCallbackLock;
  25577. double cpuUsageMs, timeToCpuScale;
  25578. class CallbackHandler : public AudioIODeviceCallback,
  25579. public MidiInputCallback
  25580. {
  25581. public:
  25582. AudioDeviceManager* owner;
  25583. void audioDeviceIOCallback (const float** inputChannelData,
  25584. int totalNumInputChannels,
  25585. float** outputChannelData,
  25586. int totalNumOutputChannels,
  25587. int numSamples);
  25588. void audioDeviceAboutToStart (AudioIODevice*);
  25589. void audioDeviceStopped();
  25590. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  25591. };
  25592. CallbackHandler callbackHandler;
  25593. friend class CallbackHandler;
  25594. void audioDeviceIOCallbackInt (const float** inputChannelData,
  25595. int totalNumInputChannels,
  25596. float** outputChannelData,
  25597. int totalNumOutputChannels,
  25598. int numSamples);
  25599. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  25600. void audioDeviceStoppedInt();
  25601. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  25602. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  25603. const BitArray& ins, const BitArray& outs);
  25604. void stopDevice();
  25605. void updateXml();
  25606. void createDeviceTypesIfNeeded();
  25607. void scanDevicesIfNeeded();
  25608. void deleteCurrentDevice();
  25609. double chooseBestSampleRate (double preferred) const;
  25610. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25611. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  25612. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  25613. AudioDeviceManager (const AudioDeviceManager&);
  25614. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  25615. };
  25616. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25617. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  25618. #endif
  25619. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  25620. #endif
  25621. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  25622. #endif
  25623. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  25624. #endif
  25625. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25626. #endif
  25627. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25628. /********* Start of inlined file: juce_Sampler.h *********/
  25629. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  25630. #define __JUCE_SAMPLER_JUCEHEADER__
  25631. /********* Start of inlined file: juce_Synthesiser.h *********/
  25632. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  25633. #define __JUCE_SYNTHESISER_JUCEHEADER__
  25634. /**
  25635. Describes one of the sounds that a Synthesiser can play.
  25636. A synthesiser can contain one or more sounds, and a sound can choose which
  25637. midi notes and channels can trigger it.
  25638. The SynthesiserSound is a passive class that just describes what the sound is -
  25639. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  25640. more than one SynthesiserVoice to play the same sound at the same time.
  25641. @see Synthesiser, SynthesiserVoice
  25642. */
  25643. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  25644. {
  25645. protected:
  25646. SynthesiserSound();
  25647. public:
  25648. /** Destructor. */
  25649. virtual ~SynthesiserSound();
  25650. /** Returns true if this sound should be played when a given midi note is pressed.
  25651. The Synthesiser will use this information when deciding which sounds to trigger
  25652. for a given note.
  25653. */
  25654. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  25655. /** Returns true if the sound should be triggered by midi events on a given channel.
  25656. The Synthesiser will use this information when deciding which sounds to trigger
  25657. for a given note.
  25658. */
  25659. virtual bool appliesToChannel (const int midiChannel) = 0;
  25660. /**
  25661. */
  25662. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  25663. juce_UseDebuggingNewOperator
  25664. };
  25665. /**
  25666. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  25667. A voice plays a single sound at a time, and a synthesiser holds an array of
  25668. voices so that it can play polyphonically.
  25669. @see Synthesiser, SynthesiserSound
  25670. */
  25671. class JUCE_API SynthesiserVoice
  25672. {
  25673. public:
  25674. /** Creates a voice. */
  25675. SynthesiserVoice();
  25676. /** Destructor. */
  25677. virtual ~SynthesiserVoice();
  25678. /** Returns the midi note that this voice is currently playing.
  25679. Returns a value less than 0 if no note is playing.
  25680. */
  25681. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  25682. /** Returns the sound that this voice is currently playing.
  25683. Returns 0 if it's not playing.
  25684. */
  25685. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  25686. /** Must return true if this voice object is capable of playing the given sound.
  25687. If there are different classes of sound, and different classes of voice, a voice can
  25688. choose which ones it wants to take on.
  25689. A typical implementation of this method may just return true if there's only one type
  25690. of voice and sound, or it might check the type of the sound object passed-in and
  25691. see if it's one that it understands.
  25692. */
  25693. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  25694. /** Called to start a new note.
  25695. This will be called during the rendering callback, so must be fast and thread-safe.
  25696. */
  25697. virtual void startNote (const int midiNoteNumber,
  25698. const float velocity,
  25699. SynthesiserSound* sound,
  25700. const int currentPitchWheelPosition) = 0;
  25701. /** Called to stop a note.
  25702. This will be called during the rendering callback, so must be fast and thread-safe.
  25703. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  25704. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  25705. and allow the synth to reassign it another sound.
  25706. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  25707. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  25708. finishes playing (during the rendering callback), it must make sure that it calls
  25709. clearCurrentNote().
  25710. */
  25711. virtual void stopNote (const bool allowTailOff) = 0;
  25712. /** Called to let the voice know that the pitch wheel has been moved.
  25713. This will be called during the rendering callback, so must be fast and thread-safe.
  25714. */
  25715. virtual void pitchWheelMoved (const int newValue) = 0;
  25716. /** Called to let the voice know that a midi controller has been moved.
  25717. This will be called during the rendering callback, so must be fast and thread-safe.
  25718. */
  25719. virtual void controllerMoved (const int controllerNumber,
  25720. const int newValue) = 0;
  25721. /** Renders the next block of data for this voice.
  25722. The output audio data must be added to the current contents of the buffer provided.
  25723. Only the region of the buffer between startSample and (startSample + numSamples)
  25724. should be altered by this method.
  25725. If the voice is currently silent, it should just return without doing anything.
  25726. If the sound that the voice is playing finishes during the course of this rendered
  25727. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  25728. The size of the blocks that are rendered can change each time it is called, and may
  25729. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  25730. the voice's methods will be called to tell it about note and controller events.
  25731. */
  25732. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  25733. int startSample,
  25734. int numSamples) = 0;
  25735. /** Returns true if the voice is currently playing a sound which is mapped to the given
  25736. midi channel.
  25737. If it's not currently playing, this will return false.
  25738. */
  25739. bool isPlayingChannel (const int midiChannel) const;
  25740. /** Changes the voice's reference sample rate.
  25741. The rate is set so that subclasses know the output rate and can set their pitch
  25742. accordingly.
  25743. This method is called by the synth, and subclasses can access the current rate with
  25744. the currentSampleRate member.
  25745. */
  25746. void setCurrentPlaybackSampleRate (const double newRate);
  25747. juce_UseDebuggingNewOperator
  25748. protected:
  25749. /** Returns the current target sample rate at which rendering is being done.
  25750. This is available for subclasses so they can pitch things correctly.
  25751. */
  25752. double getSampleRate() const throw() { return currentSampleRate; }
  25753. /** Resets the state of this voice after a sound has finished playing.
  25754. The subclass must call this when it finishes playing a note and becomes available
  25755. to play new ones.
  25756. It must either call it in the stopNote() method, or if the voice is tailing off,
  25757. then it should call it later during the renderNextBlock method, as soon as it
  25758. finishes its tail-off.
  25759. It can also be called at any time during the render callback if the sound happens
  25760. to have finished, e.g. if it's playing a sample and the sample finishes.
  25761. */
  25762. void clearCurrentNote();
  25763. private:
  25764. friend class Synthesiser;
  25765. double currentSampleRate;
  25766. int currentlyPlayingNote;
  25767. uint32 noteOnTime;
  25768. SynthesiserSound::Ptr currentlyPlayingSound;
  25769. };
  25770. /**
  25771. Base class for a musical device that can play sounds.
  25772. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  25773. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  25774. which can play back one of these sounds.
  25775. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  25776. set of sounds, and a set of voices it can use to play them. If you only give it
  25777. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  25778. have available.
  25779. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  25780. events that go in will be scanned for note on/off messages, and these are used to
  25781. start and stop the voices playing the appropriate sounds.
  25782. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  25783. noteOff() and other controller methods.
  25784. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  25785. what the target playback rate is. This value is passed on to the voices so that
  25786. they can pitch their output correctly.
  25787. */
  25788. class JUCE_API Synthesiser
  25789. {
  25790. public:
  25791. /** Creates a new synthesiser.
  25792. You'll need to add some sounds and voices before it'll make any sound..
  25793. */
  25794. Synthesiser();
  25795. /** Destructor. */
  25796. virtual ~Synthesiser();
  25797. /** Deletes all voices. */
  25798. void clearVoices();
  25799. /** Returns the number of voices that have been added. */
  25800. int getNumVoices() const throw() { return voices.size(); }
  25801. /** Returns one of the voices that have been added. */
  25802. SynthesiserVoice* getVoice (const int index) const throw();
  25803. /** Adds a new voice to the synth.
  25804. All the voices should be the same class of object and are treated equally.
  25805. The object passed in will be managed by the synthesiser, which will delete
  25806. it later on when no longer needed. The caller should not retain a pointer to the
  25807. voice.
  25808. */
  25809. void addVoice (SynthesiserVoice* const newVoice);
  25810. /** Deletes one of the voices. */
  25811. void removeVoice (const int index);
  25812. /** Deletes all sounds. */
  25813. void clearSounds();
  25814. /** Returns the number of sounds that have been added to the synth. */
  25815. int getNumSounds() const throw() { return sounds.size(); }
  25816. /** Returns one of the sounds. */
  25817. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  25818. /** Adds a new sound to the synthesiser.
  25819. The object passed in is reference counted, so will be deleted when it is removed
  25820. from the synthesiser, and when no voices are still using it.
  25821. */
  25822. void addSound (const SynthesiserSound::Ptr& newSound);
  25823. /** Removes and deletes one of the sounds. */
  25824. void removeSound (const int index);
  25825. /** If set to true, then the synth will try to take over an existing voice if
  25826. it runs out and needs to play another note.
  25827. The value of this boolean is passed into findFreeVoice(), so the result will
  25828. depend on the implementation of this method.
  25829. */
  25830. void setNoteStealingEnabled (const bool shouldStealNotes);
  25831. /** Returns true if note-stealing is enabled.
  25832. @see setNoteStealingEnabled
  25833. */
  25834. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  25835. /** Triggers a note-on event.
  25836. The default method here will find all the sounds that want to be triggered by
  25837. this note/channel. For each sound, it'll try to find a free voice, and use the
  25838. voice to start playing the sound.
  25839. Subclasses might want to override this if they need a more complex algorithm.
  25840. This method will be called automatically according to the midi data passed into
  25841. renderNextBlock(), but may be called explicitly too.
  25842. */
  25843. virtual void noteOn (const int midiChannel,
  25844. const int midiNoteNumber,
  25845. const float velocity);
  25846. /** Triggers a note-off event.
  25847. This will turn off any voices that are playing a sound for the given note/channel.
  25848. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25849. (if they can do). If this is false, the notes will all be cut off immediately.
  25850. This method will be called automatically according to the midi data passed into
  25851. renderNextBlock(), but may be called explicitly too.
  25852. */
  25853. virtual void noteOff (const int midiChannel,
  25854. const int midiNoteNumber,
  25855. const bool allowTailOff);
  25856. /** Turns off all notes.
  25857. This will turn off any voices that are playing a sound on the given midi channel.
  25858. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  25859. which channel they're playing.
  25860. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  25861. (if they can do). If this is false, the notes will all be cut off immediately.
  25862. This method will be called automatically according to the midi data passed into
  25863. renderNextBlock(), but may be called explicitly too.
  25864. */
  25865. virtual void allNotesOff (const int midiChannel,
  25866. const bool allowTailOff);
  25867. /** Sends a pitch-wheel message.
  25868. This will send a pitch-wheel message to any voices that are playing sounds on
  25869. the given midi channel.
  25870. This method will be called automatically according to the midi data passed into
  25871. renderNextBlock(), but may be called explicitly too.
  25872. @param midiChannel the midi channel for the event
  25873. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  25874. */
  25875. virtual void handlePitchWheel (const int midiChannel,
  25876. const int wheelValue);
  25877. /** Sends a midi controller message.
  25878. This will send a midi controller message to any voices that are playing sounds on
  25879. the given midi channel.
  25880. This method will be called automatically according to the midi data passed into
  25881. renderNextBlock(), but may be called explicitly too.
  25882. @param midiChannel the midi channel for the event
  25883. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  25884. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  25885. */
  25886. virtual void handleController (const int midiChannel,
  25887. const int controllerNumber,
  25888. const int controllerValue);
  25889. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  25890. render.
  25891. This value is propagated to the voices so that they can use it to render the correct
  25892. pitches.
  25893. */
  25894. void setCurrentPlaybackSampleRate (const double sampleRate);
  25895. /** Creates the next block of audio output.
  25896. This will process the next numSamples of data from all the voices, and add that output
  25897. to the audio block supplied, starting from the offset specified. Note that the
  25898. data will be added to the current contents of the buffer, so you should clear it
  25899. before calling this method if necessary.
  25900. The midi events in the inputMidi buffer are parsed for note and controller events,
  25901. and these are used to trigger the voices. Note that the startSample offset applies
  25902. both to the audio output buffer and the midi input buffer, so any midi events
  25903. with timestamps outside the specified region will be ignored.
  25904. */
  25905. void renderNextBlock (AudioSampleBuffer& outputAudio,
  25906. const MidiBuffer& inputMidi,
  25907. int startSample,
  25908. int numSamples);
  25909. juce_UseDebuggingNewOperator
  25910. protected:
  25911. /** This is used to control access to the rendering callback and the note trigger methods. */
  25912. CriticalSection lock;
  25913. OwnedArray <SynthesiserVoice> voices;
  25914. ReferenceCountedArray <SynthesiserSound> sounds;
  25915. /** The last pitch-wheel values for each midi channel. */
  25916. int lastPitchWheelValues [16];
  25917. /** Searches through the voices to find one that's not currently playing, and which
  25918. can play the given sound.
  25919. Returns 0 if all voices are busy and stealing isn't enabled.
  25920. This can be overridden to implement custom voice-stealing algorithms.
  25921. */
  25922. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  25923. const bool stealIfNoneAvailable) const;
  25924. /** Starts a specified voice playing a particular sound.
  25925. You'll probably never need to call this, it's used internally by noteOn(), but
  25926. may be needed by subclasses for custom behaviours.
  25927. */
  25928. void startVoice (SynthesiserVoice* const voice,
  25929. SynthesiserSound* const sound,
  25930. const int midiChannel,
  25931. const int midiNoteNumber,
  25932. const float velocity);
  25933. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  25934. int findFreeVoice (const bool) const { return 0; }
  25935. private:
  25936. double sampleRate;
  25937. uint32 lastNoteOnCounter;
  25938. bool shouldStealNotes;
  25939. Synthesiser (const Synthesiser&);
  25940. const Synthesiser& operator= (const Synthesiser&);
  25941. };
  25942. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  25943. /********* End of inlined file: juce_Synthesiser.h *********/
  25944. /**
  25945. A subclass of SynthesiserSound that represents a sampled audio clip.
  25946. This is a pretty basic sampler, and just attempts to load the whole audio stream
  25947. into memory.
  25948. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  25949. give it some SampledSound objects to play.
  25950. @see SamplerVoice, Synthesiser, SynthesiserSound
  25951. */
  25952. class JUCE_API SamplerSound : public SynthesiserSound
  25953. {
  25954. public:
  25955. /** Creates a sampled sound from an audio reader.
  25956. This will attempt to load the audio from the source into memory and store
  25957. it in this object.
  25958. @param name a name for the sample
  25959. @param source the audio to load. This object can be safely deleted by the
  25960. caller after this constructor returns
  25961. @param midiNotes the set of midi keys that this sound should be played on. This
  25962. is used by the SynthesiserSound::appliesToNote() method
  25963. @param midiNoteForNormalPitch the midi note at which the sample should be played
  25964. with its natural rate. All other notes will be pitched
  25965. up or down relative to this one
  25966. @param attackTimeSecs the attack (fade-in) time, in seconds
  25967. @param releaseTimeSecs the decay (fade-out) time, in seconds
  25968. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  25969. source, in seconds
  25970. */
  25971. SamplerSound (const String& name,
  25972. AudioFormatReader& source,
  25973. const BitArray& midiNotes,
  25974. const int midiNoteForNormalPitch,
  25975. const double attackTimeSecs,
  25976. const double releaseTimeSecs,
  25977. const double maxSampleLengthSeconds);
  25978. /** Destructor. */
  25979. ~SamplerSound();
  25980. /** Returns the sample's name */
  25981. const String& getName() const throw() { return name; }
  25982. /** Returns the audio sample data.
  25983. This could be 0 if there was a problem loading it.
  25984. */
  25985. AudioSampleBuffer* getAudioData() const throw() { return data; }
  25986. bool appliesToNote (const int midiNoteNumber);
  25987. bool appliesToChannel (const int midiChannel);
  25988. juce_UseDebuggingNewOperator
  25989. private:
  25990. friend class SamplerVoice;
  25991. String name;
  25992. AudioSampleBuffer* data;
  25993. double sourceSampleRate;
  25994. BitArray midiNotes;
  25995. int length, attackSamples, releaseSamples;
  25996. int midiRootNote;
  25997. };
  25998. /**
  25999. A subclass of SynthesiserVoice that can play a SamplerSound.
  26000. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26001. give it some SampledSound objects to play.
  26002. @see SamplerSound, Synthesiser, SynthesiserVoice
  26003. */
  26004. class JUCE_API SamplerVoice : public SynthesiserVoice
  26005. {
  26006. public:
  26007. /** Creates a SamplerVoice.
  26008. */
  26009. SamplerVoice();
  26010. /** Destructor. */
  26011. ~SamplerVoice();
  26012. bool canPlaySound (SynthesiserSound* sound);
  26013. void startNote (const int midiNoteNumber,
  26014. const float velocity,
  26015. SynthesiserSound* sound,
  26016. const int currentPitchWheelPosition);
  26017. void stopNote (const bool allowTailOff);
  26018. void pitchWheelMoved (const int newValue);
  26019. void controllerMoved (const int controllerNumber,
  26020. const int newValue);
  26021. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  26022. juce_UseDebuggingNewOperator
  26023. private:
  26024. double pitchRatio;
  26025. double sourceSamplePosition;
  26026. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  26027. bool isInAttack, isInRelease;
  26028. };
  26029. #endif // __JUCE_SAMPLER_JUCEHEADER__
  26030. /********* End of inlined file: juce_Sampler.h *********/
  26031. #endif
  26032. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26033. #endif
  26034. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26035. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  26036. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26037. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26038. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  26039. /**
  26040. Implements a plugin format manager for AudioUnits.
  26041. */
  26042. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  26043. {
  26044. public:
  26045. AudioUnitPluginFormat();
  26046. ~AudioUnitPluginFormat();
  26047. const String getName() const { return "AudioUnit"; }
  26048. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26049. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26050. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26051. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26052. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26053. bool doesPluginStillExist (const PluginDescription& desc);
  26054. const FileSearchPath getDefaultLocationsToSearch();
  26055. juce_UseDebuggingNewOperator
  26056. private:
  26057. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  26058. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  26059. };
  26060. #endif
  26061. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26062. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  26063. #endif
  26064. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26065. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  26066. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26067. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26068. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  26069. // Sorry, this file is just a placeholder at the moment!...
  26070. /**
  26071. Implements a plugin format manager for DirectX plugins.
  26072. */
  26073. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  26074. {
  26075. public:
  26076. DirectXPluginFormat();
  26077. ~DirectXPluginFormat();
  26078. const String getName() const { return "DirectX"; }
  26079. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26080. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26081. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26082. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26083. const FileSearchPath getDefaultLocationsToSearch();
  26084. juce_UseDebuggingNewOperator
  26085. private:
  26086. DirectXPluginFormat (const DirectXPluginFormat&);
  26087. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  26088. };
  26089. #endif
  26090. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26091. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  26092. #endif
  26093. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26094. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  26095. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26096. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26097. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  26098. // Sorry, this file is just a placeholder at the moment!...
  26099. /**
  26100. Implements a plugin format manager for DirectX plugins.
  26101. */
  26102. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  26103. {
  26104. public:
  26105. LADSPAPluginFormat();
  26106. ~LADSPAPluginFormat();
  26107. const String getName() const { return "LADSPA"; }
  26108. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26109. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26110. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26111. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26112. const FileSearchPath getDefaultLocationsToSearch();
  26113. juce_UseDebuggingNewOperator
  26114. private:
  26115. LADSPAPluginFormat (const LADSPAPluginFormat&);
  26116. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  26117. };
  26118. #endif
  26119. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26120. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  26121. #endif
  26122. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26123. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  26124. #ifdef __aeffect__
  26125. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26126. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26127. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26128. events to the list.
  26129. This is used by both the VST hosting code and the plugin wrapper.
  26130. */
  26131. class VSTMidiEventList
  26132. {
  26133. public:
  26134. VSTMidiEventList()
  26135. : events (0), numEventsUsed (0), numEventsAllocated (0)
  26136. {
  26137. }
  26138. ~VSTMidiEventList()
  26139. {
  26140. freeEvents();
  26141. }
  26142. void clear()
  26143. {
  26144. numEventsUsed = 0;
  26145. if (events != 0)
  26146. events->numEvents = 0;
  26147. }
  26148. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26149. {
  26150. ensureSize (numEventsUsed + 1);
  26151. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26152. events->numEvents = ++numEventsUsed;
  26153. if (numBytes <= 4)
  26154. {
  26155. if (e->type == kVstSysExType)
  26156. {
  26157. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26158. e->type = kVstMidiType;
  26159. e->byteSize = sizeof (VstMidiEvent);
  26160. e->noteLength = 0;
  26161. e->noteOffset = 0;
  26162. e->detune = 0;
  26163. e->noteOffVelocity = 0;
  26164. }
  26165. e->deltaFrames = frameOffset;
  26166. memcpy (e->midiData, midiData, numBytes);
  26167. }
  26168. else
  26169. {
  26170. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26171. if (se->type == kVstSysExType)
  26172. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26173. else
  26174. se->sysexDump = (char*) juce_malloc (numBytes);
  26175. memcpy (se->sysexDump, midiData, numBytes);
  26176. se->type = kVstSysExType;
  26177. se->byteSize = sizeof (VstMidiSysexEvent);
  26178. se->deltaFrames = frameOffset;
  26179. se->flags = 0;
  26180. se->dumpBytes = numBytes;
  26181. se->resvd1 = 0;
  26182. se->resvd2 = 0;
  26183. }
  26184. }
  26185. // Handy method to pull the events out of an event buffer supplied by the host
  26186. // or plugin.
  26187. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26188. {
  26189. for (int i = 0; i < events->numEvents; ++i)
  26190. {
  26191. const VstEvent* const e = events->events[i];
  26192. if (e != 0)
  26193. {
  26194. if (e->type == kVstMidiType)
  26195. {
  26196. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26197. 4, e->deltaFrames);
  26198. }
  26199. else if (e->type == kVstSysExType)
  26200. {
  26201. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26202. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26203. e->deltaFrames);
  26204. }
  26205. }
  26206. }
  26207. }
  26208. void ensureSize (int numEventsNeeded)
  26209. {
  26210. if (numEventsNeeded > numEventsAllocated)
  26211. {
  26212. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26213. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26214. if (events == 0)
  26215. events = (VstEvents*) juce_calloc (size);
  26216. else
  26217. events = (VstEvents*) juce_realloc (events, size);
  26218. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26219. {
  26220. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26221. (int) sizeof (VstMidiSysexEvent)));
  26222. e->type = kVstMidiType;
  26223. e->byteSize = sizeof (VstMidiEvent);
  26224. events->events[i] = (VstEvent*) e;
  26225. }
  26226. numEventsAllocated = numEventsNeeded;
  26227. }
  26228. }
  26229. void freeEvents()
  26230. {
  26231. if (events != 0)
  26232. {
  26233. for (int i = numEventsAllocated; --i >= 0;)
  26234. {
  26235. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26236. if (e->type == kVstSysExType)
  26237. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26238. juce_free (e);
  26239. }
  26240. juce_free (events);
  26241. events = 0;
  26242. numEventsUsed = 0;
  26243. numEventsAllocated = 0;
  26244. }
  26245. }
  26246. VstEvents* events;
  26247. private:
  26248. int numEventsUsed, numEventsAllocated;
  26249. };
  26250. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26251. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26252. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  26253. #endif
  26254. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26255. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  26256. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26257. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26258. #if JUCE_PLUGINHOST_VST
  26259. /**
  26260. Implements a plugin format manager for VSTs.
  26261. */
  26262. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  26263. {
  26264. public:
  26265. VSTPluginFormat();
  26266. ~VSTPluginFormat();
  26267. const String getName() const { return "VST"; }
  26268. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26269. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26270. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26271. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26272. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26273. bool doesPluginStillExist (const PluginDescription& desc);
  26274. const FileSearchPath getDefaultLocationsToSearch();
  26275. juce_UseDebuggingNewOperator
  26276. private:
  26277. VSTPluginFormat (const VSTPluginFormat&);
  26278. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  26279. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  26280. };
  26281. #endif
  26282. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26283. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  26284. #endif
  26285. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26286. #endif
  26287. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  26288. #endif
  26289. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26290. #endif
  26291. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  26292. #endif
  26293. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  26294. #endif
  26295. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26296. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  26297. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26298. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26299. /**
  26300. Scans a directory for plugins, and adds them to a KnownPluginList.
  26301. To use one of these, create it and call scanNextFile() repeatedly, until
  26302. it returns false.
  26303. */
  26304. class JUCE_API PluginDirectoryScanner
  26305. {
  26306. public:
  26307. /**
  26308. Creates a scanner.
  26309. @param listToAddResultsTo this will get the new types added to it.
  26310. @param formatToLookFor this is the type of format that you want to look for
  26311. @param directoriesToSearch the path to search
  26312. @param searchRecursively true to search recursively
  26313. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  26314. be used as a file to store the names of any plugins
  26315. that crash during initialisation. If there are
  26316. any plugins listed in it, then these will always
  26317. be scanned after all other possible files have
  26318. been tried - in this way, even if there's a few
  26319. dodgy plugins in your path, then a couple of rescans
  26320. will still manage to find all the proper plugins.
  26321. It's probably best to choose a file in the user's
  26322. application data directory (alongside your app's
  26323. settings file) for this. The file format it uses
  26324. is just a list of filenames of the modules that
  26325. failed.
  26326. */
  26327. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  26328. AudioPluginFormat& formatToLookFor,
  26329. FileSearchPath directoriesToSearch,
  26330. const bool searchRecursively,
  26331. const File& deadMansPedalFile);
  26332. /** Destructor. */
  26333. ~PluginDirectoryScanner();
  26334. /** Tries the next likely-looking file.
  26335. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26336. re-tested if it's not already in the list, or if the file's modification
  26337. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26338. false, the file will always be reloaded and tested.
  26339. Returns false when there are no more files to try.
  26340. */
  26341. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26342. /** Returns the description of the plugin that will be scanned during the next
  26343. call to scanNextFile().
  26344. This is handy if you want to show the user which file is currently getting
  26345. scanned.
  26346. */
  26347. const String getNextPluginFileThatWillBeScanned() const throw();
  26348. /** Returns the estimated progress, between 0 and 1.
  26349. */
  26350. float getProgress() const { return progress; }
  26351. /** This returns a list of all the filenames of things that looked like being
  26352. a plugin file, but which failed to open for some reason.
  26353. */
  26354. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26355. juce_UseDebuggingNewOperator
  26356. private:
  26357. KnownPluginList& list;
  26358. AudioPluginFormat& format;
  26359. StringArray filesOrIdentifiersToScan;
  26360. File deadMansPedalFile;
  26361. StringArray failedFiles;
  26362. int nextIndex;
  26363. float progress;
  26364. const StringArray getDeadMansPedalFile() throw();
  26365. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26366. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26367. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26368. };
  26369. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26370. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26371. #endif
  26372. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26373. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26374. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26375. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26376. /********* Start of inlined file: juce_ListBox.h *********/
  26377. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26378. #define __JUCE_LISTBOX_JUCEHEADER__
  26379. class ListViewport;
  26380. /**
  26381. A subclass of this is used to drive a ListBox.
  26382. @see ListBox
  26383. */
  26384. class JUCE_API ListBoxModel
  26385. {
  26386. public:
  26387. /** Destructor. */
  26388. virtual ~ListBoxModel() {}
  26389. /** This has to return the number of items in the list.
  26390. @see ListBox::getNumRows()
  26391. */
  26392. virtual int getNumRows() = 0;
  26393. /** This method must be implemented to draw a row of the list.
  26394. */
  26395. virtual void paintListBoxItem (int rowNumber,
  26396. Graphics& g,
  26397. int width, int height,
  26398. bool rowIsSelected) = 0;
  26399. /** This is used to create or update a custom component to go in a row of the list.
  26400. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26401. and handle mouse clicks with listBoxItemClicked().
  26402. This method will be called whenever a custom component might need to be updated - e.g.
  26403. when the table is changed, or TableListBox::updateContent() is called.
  26404. If you don't need a custom component for the specified row, then return 0.
  26405. If you do want a custom component, and the existingComponentToUpdate is null, then
  26406. this method must create a suitable new component and return it.
  26407. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26408. by this method. In this case, the method must either update it to make sure it's correctly representing
  26409. the given row (which may be different from the one that the component was created for), or it can
  26410. delete this component and return a new one.
  26411. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26412. */
  26413. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26414. Component* existingComponentToUpdate);
  26415. /** This can be overridden to react to the user clicking on a row.
  26416. @see listBoxItemDoubleClicked
  26417. */
  26418. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26419. /** This can be overridden to react to the user double-clicking on a row.
  26420. @see listBoxItemClicked
  26421. */
  26422. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26423. /** This can be overridden to react to the user double-clicking on a part of the list where
  26424. there are no rows.
  26425. @see listBoxItemClicked
  26426. */
  26427. virtual void backgroundClicked();
  26428. /** Override this to be informed when rows are selected or deselected.
  26429. This will be called whenever a row is selected or deselected. If a range of
  26430. rows is selected all at once, this will just be called once for that event.
  26431. @param lastRowSelected the last row that the user selected. If no
  26432. rows are currently selected, this may be -1.
  26433. */
  26434. virtual void selectedRowsChanged (int lastRowSelected);
  26435. /** Override this to be informed when the delete key is pressed.
  26436. If no rows are selected when they press the key, this won't be called.
  26437. @param lastRowSelected the last row that had been selected when they pressed the
  26438. key - if there are multiple selections, this might not be
  26439. very useful
  26440. */
  26441. virtual void deleteKeyPressed (int lastRowSelected);
  26442. /** Override this to be informed when the return key is pressed.
  26443. If no rows are selected when they press the key, this won't be called.
  26444. @param lastRowSelected the last row that had been selected when they pressed the
  26445. key - if there are multiple selections, this might not be
  26446. very useful
  26447. */
  26448. virtual void returnKeyPressed (int lastRowSelected);
  26449. /** Override this to be informed when the list is scrolled.
  26450. This might be caused by the user moving the scrollbar, or by programmatic changes
  26451. to the list position.
  26452. */
  26453. virtual void listWasScrolled();
  26454. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26455. If this returns a non-empty name then when the user drags a row, the listbox will
  26456. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26457. a drag-and-drop operation, using this string as the source description, with the listbox
  26458. itself as the source component.
  26459. @see DragAndDropContainer::startDragging
  26460. */
  26461. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26462. };
  26463. /**
  26464. A list of items that can be scrolled vertically.
  26465. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26466. either paint each row of the list and respond to events via callbacks, or for
  26467. more specialised tasks, it can supply a custom component to fill each row.
  26468. @see ComboBox, TableListBox
  26469. */
  26470. class JUCE_API ListBox : public Component,
  26471. public SettableTooltipClient
  26472. {
  26473. public:
  26474. /** Creates a ListBox.
  26475. The model pointer passed-in can be null, in which case you can set it later
  26476. with setModel().
  26477. */
  26478. ListBox (const String& componentName,
  26479. ListBoxModel* const model);
  26480. /** Destructor. */
  26481. ~ListBox();
  26482. /** Changes the current data model to display. */
  26483. void setModel (ListBoxModel* const newModel);
  26484. /** Returns the current list model. */
  26485. ListBoxModel* getModel() const throw() { return model; }
  26486. /** Causes the list to refresh its content.
  26487. Call this when the number of rows in the list changes, or if you want it
  26488. to call refreshComponentForRow() on all the row components.
  26489. Be careful not to call it from a different thread, though, as it's not
  26490. thread-safe.
  26491. */
  26492. void updateContent();
  26493. /** Turns on multiple-selection of rows.
  26494. By default this is disabled.
  26495. When your row component gets clicked you'll need to call the
  26496. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26497. clicked and to get it to do the appropriate selection based on whether
  26498. the ctrl/shift keys are held down.
  26499. */
  26500. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26501. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26502. This function is here primarily for the ComboBox class to use, but might be
  26503. useful for some other purpose too.
  26504. */
  26505. void setMouseMoveSelectsRows (bool shouldSelect);
  26506. /** Selects a row.
  26507. If the row is already selected, this won't do anything.
  26508. @param rowNumber the row to select
  26509. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26510. the selected row is off-screen, it'll scroll to make
  26511. sure that row is on-screen
  26512. @param deselectOthersFirst if true and there are multiple selections, these will
  26513. first be deselected before this item is selected
  26514. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26515. deselectAllRows, selectRangeOfRows
  26516. */
  26517. void selectRow (const int rowNumber,
  26518. bool dontScrollToShowThisRow = false,
  26519. bool deselectOthersFirst = true);
  26520. /** Selects a set of rows.
  26521. This will add these rows to the current selection, so you might need to
  26522. clear the current selection first with deselectAllRows()
  26523. @param firstRow the first row to select (inclusive)
  26524. @param lastRow the last row to select (inclusive)
  26525. */
  26526. void selectRangeOfRows (int firstRow,
  26527. int lastRow);
  26528. /** Deselects a row.
  26529. If it's not currently selected, this will do nothing.
  26530. @see selectRow, deselectAllRows
  26531. */
  26532. void deselectRow (const int rowNumber);
  26533. /** Deselects any currently selected rows.
  26534. @see deselectRow
  26535. */
  26536. void deselectAllRows();
  26537. /** Selects or deselects a row.
  26538. If the row's currently selected, this deselects it, and vice-versa.
  26539. */
  26540. void flipRowSelection (const int rowNumber);
  26541. /** Returns a sparse set indicating the rows that are currently selected.
  26542. @see setSelectedRows
  26543. */
  26544. const SparseSet<int> getSelectedRows() const;
  26545. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26546. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26547. method will be called. If it's false, no notification will be sent to the model.
  26548. @see getSelectedRows
  26549. */
  26550. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26551. const bool sendNotificationEventToModel = true);
  26552. /** Checks whether a row is selected.
  26553. */
  26554. bool isRowSelected (const int rowNumber) const;
  26555. /** Returns the number of rows that are currently selected.
  26556. @see getSelectedRow, isRowSelected, getLastRowSelected
  26557. */
  26558. int getNumSelectedRows() const;
  26559. /** Returns the row number of a selected row.
  26560. This will return the row number of the Nth selected row. The row numbers returned will
  26561. be sorted in order from low to high.
  26562. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26563. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26564. selected
  26565. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26566. */
  26567. int getSelectedRow (const int index = 0) const;
  26568. /** Returns the last row that the user selected.
  26569. This isn't the same as the highest row number that is currently selected - if the user
  26570. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26571. If nothing is selected, it will return -1.
  26572. */
  26573. int getLastRowSelected() const;
  26574. /** Multiply-selects rows based on the modifier keys.
  26575. If no modifier keys are down, this will select the given row and
  26576. deselect any others.
  26577. If the ctrl (or command on the Mac) key is down, it'll flip the
  26578. state of the selected row.
  26579. If the shift key is down, it'll select up to the given row from the
  26580. last row selected.
  26581. @see selectRow
  26582. */
  26583. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  26584. const ModifierKeys& modifiers);
  26585. /** Scrolls the list to a particular position.
  26586. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  26587. 1.0 scrolls to the bottom.
  26588. If the total number of rows all fit onto the screen at once, then this
  26589. method won't do anything.
  26590. @see getVerticalPosition
  26591. */
  26592. void setVerticalPosition (const double newProportion);
  26593. /** Returns the current vertical position as a proportion of the total.
  26594. This can be used in conjunction with setVerticalPosition() to save and restore
  26595. the list's position. It returns a value in the range 0 to 1.
  26596. @see setVerticalPosition
  26597. */
  26598. double getVerticalPosition() const;
  26599. /** Scrolls if necessary to make sure that a particular row is visible.
  26600. */
  26601. void scrollToEnsureRowIsOnscreen (const int row);
  26602. /** Returns a pointer to the scrollbar.
  26603. (Unlikely to be useful for most people).
  26604. */
  26605. ScrollBar* getVerticalScrollBar() const throw();
  26606. /** Returns a pointer to the scrollbar.
  26607. (Unlikely to be useful for most people).
  26608. */
  26609. ScrollBar* getHorizontalScrollBar() const throw();
  26610. /** Finds the row index that contains a given x,y position.
  26611. The position is relative to the ListBox's top-left.
  26612. If no row exists at this position, the method will return -1.
  26613. @see getComponentForRowNumber
  26614. */
  26615. int getRowContainingPosition (const int x, const int y) const throw();
  26616. /** Finds a row index that would be the most suitable place to insert a new
  26617. item for a given position.
  26618. This is useful when the user is e.g. dragging and dropping onto the listbox,
  26619. because it lets you easily choose the best position to insert the item that
  26620. they drop, based on where they drop it.
  26621. If the position is out of range, this will return -1. If the position is
  26622. beyond the end of the list, it will return getNumRows() to indicate the end
  26623. of the list.
  26624. @see getComponentForRowNumber
  26625. */
  26626. int getInsertionIndexForPosition (const int x, const int y) const throw();
  26627. /** Returns the position of one of the rows, relative to the top-left of
  26628. the listbox.
  26629. This may be off-screen, and the range of the row number that is passed-in is
  26630. not checked to see if it's a valid row.
  26631. */
  26632. const Rectangle getRowPosition (const int rowNumber,
  26633. const bool relativeToComponentTopLeft) const throw();
  26634. /** Finds the row component for a given row in the list.
  26635. The component returned will have been created using createRowComponent().
  26636. If the component for this row is off-screen or if the row is out-of-range,
  26637. this will return 0.
  26638. @see getRowContainingPosition
  26639. */
  26640. Component* getComponentForRowNumber (const int rowNumber) const throw();
  26641. /** Returns the row number that the given component represents.
  26642. If the component isn't one of the list's rows, this will return -1.
  26643. */
  26644. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  26645. /** Returns the width of a row (which may be less than the width of this component
  26646. if there's a scrollbar).
  26647. */
  26648. int getVisibleRowWidth() const throw();
  26649. /** Sets the height of each row in the list.
  26650. The default height is 22 pixels.
  26651. @see getRowHeight
  26652. */
  26653. void setRowHeight (const int newHeight);
  26654. /** Returns the height of a row in the list.
  26655. @see setRowHeight
  26656. */
  26657. int getRowHeight() const throw() { return rowHeight; }
  26658. /** Returns the number of rows actually visible.
  26659. This is the number of whole rows which will fit on-screen, so the value might
  26660. be more than the actual number of rows in the list.
  26661. */
  26662. int getNumRowsOnScreen() const throw();
  26663. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26664. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26665. methods.
  26666. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26667. */
  26668. enum ColourIds
  26669. {
  26670. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  26671. Make this transparent if you don't want the background to be filled. */
  26672. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  26673. Make this transparent to not have an outline. */
  26674. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  26675. };
  26676. /** Sets the thickness of a border that will be drawn around the box.
  26677. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  26678. @see outlineColourId
  26679. */
  26680. void setOutlineThickness (const int outlineThickness);
  26681. /** Returns the thickness of outline that will be drawn around the listbox.
  26682. @see setOutlineColour
  26683. */
  26684. int getOutlineThickness() const throw() { return outlineThickness; }
  26685. /** Sets a component that the list should use as a header.
  26686. This will position the given component at the top of the list, maintaining the
  26687. height of the component passed-in, but rescaling it horizontally to match the
  26688. width of the items in the listbox.
  26689. The component will be deleted when setHeaderComponent() is called with a
  26690. different component, or when the listbox is deleted.
  26691. */
  26692. void setHeaderComponent (Component* const newHeaderComponent);
  26693. /** Changes the width of the rows in the list.
  26694. This can be used to make the list's row components wider than the list itself - the
  26695. width of the rows will be either the width of the list or this value, whichever is
  26696. greater, and if the rows become wider than the list, a horizontal scrollbar will
  26697. appear.
  26698. The default value for this is 0, which means that the rows will always
  26699. be the same width as the list.
  26700. */
  26701. void setMinimumContentWidth (const int newMinimumWidth);
  26702. /** Returns the space currently available for the row items, taking into account
  26703. borders, scrollbars, etc.
  26704. */
  26705. int getVisibleContentWidth() const throw();
  26706. /** Repaints one of the rows.
  26707. This is a lightweight alternative to calling updateContent, and just causes a
  26708. repaint of the row's area.
  26709. */
  26710. void repaintRow (const int rowNumber) throw();
  26711. /** This fairly obscure method creates an image that just shows the currently
  26712. selected row components.
  26713. It's a handy method for doing drag-and-drop, as it can be passed to the
  26714. DragAndDropContainer for use as the drag image.
  26715. Note that it will make the row components temporarily invisible, so if you're
  26716. using custom components this could affect them if they're sensitive to that
  26717. sort of thing.
  26718. @see Component::createComponentSnapshot
  26719. */
  26720. Image* createSnapshotOfSelectedRows();
  26721. /** Returns the viewport that this ListBox uses.
  26722. You may need to use this to change parameters such as whether scrollbars
  26723. are shown, etc.
  26724. */
  26725. Viewport* getViewport() const throw();
  26726. /** @internal */
  26727. bool keyPressed (const KeyPress& key);
  26728. /** @internal */
  26729. bool keyStateChanged();
  26730. /** @internal */
  26731. void paint (Graphics& g);
  26732. /** @internal */
  26733. void paintOverChildren (Graphics& g);
  26734. /** @internal */
  26735. void resized();
  26736. /** @internal */
  26737. void visibilityChanged();
  26738. /** @internal */
  26739. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26740. /** @internal */
  26741. void mouseMove (const MouseEvent&);
  26742. /** @internal */
  26743. void mouseExit (const MouseEvent&);
  26744. /** @internal */
  26745. void mouseUp (const MouseEvent&);
  26746. /** @internal */
  26747. void colourChanged();
  26748. juce_UseDebuggingNewOperator
  26749. private:
  26750. friend class ListViewport;
  26751. friend class TableListBox;
  26752. ListBoxModel* model;
  26753. ListViewport* viewport;
  26754. Component* headerComponent;
  26755. int totalItems, rowHeight, minimumRowWidth;
  26756. int outlineThickness;
  26757. int lastMouseX, lastMouseY, lastRowSelected;
  26758. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  26759. SparseSet <int> selected;
  26760. void selectRowInternal (const int rowNumber,
  26761. bool dontScrollToShowThisRow,
  26762. bool deselectOthersFirst,
  26763. bool isMouseClick);
  26764. ListBox (const ListBox&);
  26765. const ListBox& operator= (const ListBox&);
  26766. };
  26767. #endif // __JUCE_LISTBOX_JUCEHEADER__
  26768. /********* End of inlined file: juce_ListBox.h *********/
  26769. /********* Start of inlined file: juce_TextButton.h *********/
  26770. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  26771. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  26772. /**
  26773. A button that uses the standard lozenge-shaped background with a line of
  26774. text on it.
  26775. @see Button, DrawableButton
  26776. */
  26777. class JUCE_API TextButton : public Button
  26778. {
  26779. public:
  26780. /** Creates a TextButton.
  26781. @param buttonName the text to put in the button (the component's name is also
  26782. initially set to this string, but these can be changed later
  26783. using the setName() and setButtonText() methods)
  26784. @param toolTip an optional string to use as a toolip
  26785. @see Button
  26786. */
  26787. TextButton (const String& buttonName,
  26788. const String& toolTip = String::empty);
  26789. /** Destructor. */
  26790. ~TextButton();
  26791. /** A set of colour IDs to use to change the colour of various aspects of the button.
  26792. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26793. methods.
  26794. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26795. */
  26796. enum ColourIds
  26797. {
  26798. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  26799. 'off'). The look-and-feel class might re-interpret this to add
  26800. effects, etc. */
  26801. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  26802. 'on'). The look-and-feel class might re-interpret this to add
  26803. effects, etc. */
  26804. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  26805. };
  26806. /** Resizes the button to fit neatly around its current text.
  26807. If newHeight is >= 0, the button's height will be changed to this
  26808. value. If it's less than zero, its height will be unaffected.
  26809. */
  26810. void changeWidthToFitText (const int newHeight = -1);
  26811. /** This can be overridden to use different fonts than the default one.
  26812. Note that you'll need to set the font's size appropriately, too.
  26813. */
  26814. virtual const Font getFont();
  26815. juce_UseDebuggingNewOperator
  26816. protected:
  26817. /** @internal */
  26818. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  26819. /** @internal */
  26820. void colourChanged();
  26821. private:
  26822. TextButton (const TextButton&);
  26823. const TextButton& operator= (const TextButton&);
  26824. };
  26825. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  26826. /********* End of inlined file: juce_TextButton.h *********/
  26827. /**
  26828. A component displaying a list of plugins, with options to scan for them,
  26829. add, remove and sort them.
  26830. */
  26831. class JUCE_API PluginListComponent : public Component,
  26832. public ListBoxModel,
  26833. public ChangeListener,
  26834. public ButtonListener,
  26835. public Timer
  26836. {
  26837. public:
  26838. /**
  26839. Creates the list component.
  26840. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  26841. The properties file, if supplied, is used to store the user's last search paths.
  26842. */
  26843. PluginListComponent (KnownPluginList& listToRepresent,
  26844. const File& deadMansPedalFile,
  26845. PropertiesFile* const propertiesToUse);
  26846. /** Destructor. */
  26847. ~PluginListComponent();
  26848. /** @internal */
  26849. void resized();
  26850. /** @internal */
  26851. bool isInterestedInFileDrag (const StringArray& files);
  26852. /** @internal */
  26853. void filesDropped (const StringArray& files, int, int);
  26854. /** @internal */
  26855. int getNumRows();
  26856. /** @internal */
  26857. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  26858. /** @internal */
  26859. void deleteKeyPressed (int lastRowSelected);
  26860. /** @internal */
  26861. void buttonClicked (Button* b);
  26862. /** @internal */
  26863. void changeListenerCallback (void*);
  26864. /** @internal */
  26865. void timerCallback();
  26866. juce_UseDebuggingNewOperator
  26867. private:
  26868. KnownPluginList& list;
  26869. File deadMansPedalFile;
  26870. ListBox* listBox;
  26871. TextButton* optionsButton;
  26872. PropertiesFile* propertiesToUse;
  26873. int typeToScan;
  26874. void scanFor (AudioPluginFormat* format);
  26875. PluginListComponent (const PluginListComponent&);
  26876. const PluginListComponent& operator= (const PluginListComponent&);
  26877. };
  26878. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26879. /********* End of inlined file: juce_PluginListComponent.h *********/
  26880. #endif
  26881. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26882. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  26883. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26884. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  26885. /********* Start of inlined file: juce_AudioFormat.h *********/
  26886. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  26887. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  26888. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  26889. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26890. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26891. /**
  26892. Writes samples to an audio file stream.
  26893. A subclass that writes a specific type of audio format will be created by
  26894. an AudioFormat object.
  26895. After creating one of these with the AudioFormat::createWriterFor() method
  26896. you can call its write() method to store the samples, and then delete it.
  26897. @see AudioFormat, AudioFormatReader
  26898. */
  26899. class JUCE_API AudioFormatWriter
  26900. {
  26901. protected:
  26902. /** Creates an AudioFormatWriter object.
  26903. @param destStream the stream to write to - this will be deleted
  26904. by this object when it is no longer needed
  26905. @param formatName the description that will be returned by the getFormatName()
  26906. method
  26907. @param sampleRate the sample rate to use - the base class just stores
  26908. this value, it doesn't do anything with it
  26909. @param numberOfChannels the number of channels to write - the base class just stores
  26910. this value, it doesn't do anything with it
  26911. @param bitsPerSample the bit depth of the stream - the base class just stores
  26912. this value, it doesn't do anything with it
  26913. */
  26914. AudioFormatWriter (OutputStream* const destStream,
  26915. const String& formatName,
  26916. const double sampleRate,
  26917. const unsigned int numberOfChannels,
  26918. const unsigned int bitsPerSample);
  26919. public:
  26920. /** Destructor. */
  26921. virtual ~AudioFormatWriter();
  26922. /** Returns a description of what type of format this is.
  26923. E.g. "AIFF file"
  26924. */
  26925. const String getFormatName() const throw() { return formatName; }
  26926. /** Writes a set of samples to the audio stream.
  26927. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  26928. can use AudioSampleBuffer::writeToAudioWriter().
  26929. @param samplesToWrite an array of arrays containing the sample data for
  26930. each channel to write. This is a zero-terminated
  26931. array of arrays, and can contain a different number
  26932. of channels than the actual stream uses, and the
  26933. writer should do its best to cope with this.
  26934. If the format is fixed-point, each channel will be formatted
  26935. as an array of signed integers using the full 32-bit
  26936. range -0x80000000 to 0x7fffffff, regardless of the source's
  26937. bit-depth. If it is a floating-point format, you should treat
  26938. the arrays as arrays of floats, and just cast it to an (int**)
  26939. to pass it into the method.
  26940. @param numSamples the number of samples to write
  26941. */
  26942. virtual bool write (const int** samplesToWrite,
  26943. int numSamples) = 0;
  26944. /** Reads a section of samples from an AudioFormatReader, and writes these to
  26945. the output.
  26946. This will take care of any floating-point conversion that's required to convert
  26947. between the two formats. It won't deal with sample-rate conversion, though.
  26948. @returns false if it can't read or write properly during the operation
  26949. */
  26950. bool writeFromAudioReader (AudioFormatReader& reader,
  26951. int64 startSample,
  26952. int numSamplesToRead);
  26953. /** Reads some samples from an AudioSource, and writes these to the output.
  26954. The source must already have been initialised with the AudioSource::prepareToPlay() method
  26955. @param source the source to read from
  26956. @param numSamplesToRead total number of samples to read and write
  26957. @param samplesPerBlock the maximum number of samples to fetch from the source
  26958. @returns false if it can't read or write properly during the operation
  26959. */
  26960. bool writeFromAudioSource (AudioSource& source,
  26961. int numSamplesToRead,
  26962. const int samplesPerBlock = 2048);
  26963. /** Returns the sample rate being used. */
  26964. double getSampleRate() const throw() { return sampleRate; }
  26965. /** Returns the number of channels being written. */
  26966. int getNumChannels() const throw() { return numChannels; }
  26967. /** Returns the bit-depth of the data being written. */
  26968. int getBitsPerSample() const throw() { return bitsPerSample; }
  26969. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  26970. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  26971. juce_UseDebuggingNewOperator
  26972. protected:
  26973. /** The sample rate of the stream. */
  26974. double sampleRate;
  26975. /** The number of channels being written to the stream. */
  26976. unsigned int numChannels;
  26977. /** The bit depth of the file. */
  26978. unsigned int bitsPerSample;
  26979. /** True if it's a floating-point format, false if it's fixed-point. */
  26980. bool usesFloatingPointData;
  26981. /** The output stream for Use by subclasses. */
  26982. OutputStream* output;
  26983. private:
  26984. String formatName;
  26985. };
  26986. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  26987. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  26988. /**
  26989. Subclasses of AudioFormat are used to read and write different audio
  26990. file formats.
  26991. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  26992. */
  26993. class JUCE_API AudioFormat
  26994. {
  26995. public:
  26996. /** Destructor. */
  26997. virtual ~AudioFormat();
  26998. /** Returns the name of this format.
  26999. e.g. "WAV file" or "AIFF file"
  27000. */
  27001. const String& getFormatName() const;
  27002. /** Returns all the file extensions that might apply to a file of this format.
  27003. The first item will be the one that's preferred when creating a new file.
  27004. So for a wav file this might just return ".wav"; for an AIFF file it might
  27005. return two items, ".aif" and ".aiff"
  27006. */
  27007. const StringArray& getFileExtensions() const;
  27008. /** Returns true if this the given file can be read by this format.
  27009. Subclasses shouldn't do too much work here, just check the extension or
  27010. file type. The base class implementation just checks the file's extension
  27011. against one of the ones that was registered in the constructor.
  27012. */
  27013. virtual bool canHandleFile (const File& fileToTest);
  27014. /** Returns a set of sample rates that the format can read and write. */
  27015. virtual const Array <int> getPossibleSampleRates() = 0;
  27016. /** Returns a set of bit depths that the format can read and write. */
  27017. virtual const Array <int> getPossibleBitDepths() = 0;
  27018. /** Returns true if the format can do 2-channel audio. */
  27019. virtual bool canDoStereo() = 0;
  27020. /** Returns true if the format can do 1-channel audio. */
  27021. virtual bool canDoMono() = 0;
  27022. /** Returns true if the format uses compressed data. */
  27023. virtual bool isCompressed();
  27024. /** Returns a list of different qualities that can be used when writing.
  27025. Non-compressed formats will just return an empty array, but for something
  27026. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27027. When calling createWriterFor(), an index from this array is passed in to
  27028. tell the format which option is required.
  27029. */
  27030. virtual const StringArray getQualityOptions();
  27031. /** Tries to create an object that can read from a stream containing audio
  27032. data in this format.
  27033. The reader object that is returned can be used to read from the stream, and
  27034. should then be deleted by the caller.
  27035. @param sourceStream the stream to read from - the AudioFormatReader object
  27036. that is returned will delete this stream when it no longer
  27037. needs it.
  27038. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27039. should delete the stream object that was passed-in. (If a valid
  27040. reader is returned, it will always be in charge of deleting the
  27041. stream, so this parameter is ignored)
  27042. @see AudioFormatReader
  27043. */
  27044. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27045. const bool deleteStreamIfOpeningFails) = 0;
  27046. /** Tries to create an object that can write to a stream with this audio format.
  27047. The writer object that is returned can be used to write to the stream, and
  27048. should then be deleted by the caller.
  27049. If the stream can't be created for some reason (e.g. the parameters passed in
  27050. here aren't suitable), this will return 0.
  27051. @param streamToWriteTo the stream that the data will go to - this will be
  27052. deleted by the AudioFormatWriter object when it's no longer
  27053. needed. If no AudioFormatWriter can be created by this method,
  27054. the stream will NOT be deleted, so that the caller can re-use it
  27055. to try to open a different format, etc
  27056. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27057. returned by getPossibleSampleRates()
  27058. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27059. the choice will depend on the results of canDoMono() and
  27060. canDoStereo()
  27061. @param bitsPerSample the bits per sample to use - this must be one of the values
  27062. returned by getPossibleBitDepths()
  27063. @param metadataValues a set of metadata values that the writer should try to write
  27064. to the stream. Exactly what these are depends on the format,
  27065. and the subclass doesn't actually have to do anything with
  27066. them if it doesn't want to. Have a look at the specific format
  27067. implementation classes to see possible values that can be
  27068. used
  27069. @param qualityOptionIndex the index of one of compression qualities returned by the
  27070. getQualityOptions() method. If there aren't any quality options
  27071. for this format, just pass 0 in this parameter, as it'll be
  27072. ignored
  27073. @see AudioFormatWriter
  27074. */
  27075. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27076. double sampleRateToUse,
  27077. unsigned int numberOfChannels,
  27078. int bitsPerSample,
  27079. const StringPairArray& metadataValues,
  27080. int qualityOptionIndex) = 0;
  27081. protected:
  27082. /** Creates an AudioFormat object.
  27083. @param formatName this sets the value that will be returned by getFormatName()
  27084. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27085. be returned by getFileExtension()
  27086. */
  27087. AudioFormat (const String& formatName,
  27088. const tchar** const fileExtensions);
  27089. private:
  27090. String formatName;
  27091. StringArray fileExtensions;
  27092. };
  27093. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27094. /********* End of inlined file: juce_AudioFormat.h *********/
  27095. /**
  27096. Reads and Writes AIFF format audio files.
  27097. @see AudioFormat
  27098. */
  27099. class JUCE_API AiffAudioFormat : public AudioFormat
  27100. {
  27101. public:
  27102. /** Creates an format object. */
  27103. AiffAudioFormat();
  27104. /** Destructor. */
  27105. ~AiffAudioFormat();
  27106. const Array <int> getPossibleSampleRates();
  27107. const Array <int> getPossibleBitDepths();
  27108. bool canDoStereo();
  27109. bool canDoMono();
  27110. #if JUCE_MAC
  27111. bool canHandleFile (const File& fileToTest);
  27112. #endif
  27113. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27114. const bool deleteStreamIfOpeningFails);
  27115. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27116. double sampleRateToUse,
  27117. unsigned int numberOfChannels,
  27118. int bitsPerSample,
  27119. const StringPairArray& metadataValues,
  27120. int qualityOptionIndex);
  27121. juce_UseDebuggingNewOperator
  27122. };
  27123. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27124. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  27125. #endif
  27126. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27127. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  27128. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27129. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27130. /**
  27131. */
  27132. class AudioCDBurner
  27133. {
  27134. public:
  27135. /** Returns a list of available optical drives.
  27136. Use openDevice() to open one of the items from this list.
  27137. */
  27138. static const StringArray findAvailableDevices();
  27139. /** Tries to open one of the optical drives.
  27140. The deviceIndex is an index into the array returned by findAvailableDevices().
  27141. */
  27142. static AudioCDBurner* openDevice (const int deviceIndex);
  27143. /** Destructor. */
  27144. ~AudioCDBurner();
  27145. /** Returns true if there's a writable disk in the drive.
  27146. */
  27147. bool isDiskPresent() const;
  27148. /** Returns the number of free blocks on the disk.
  27149. There are 75 blocks per second, at 44100Hz.
  27150. */
  27151. int getNumAvailableAudioBlocks() const;
  27152. /** Adds a track to be written.
  27153. The source passed-in here will be kept by this object, and it will
  27154. be used and deleted at some point in the future, either during the
  27155. burn() method or when this AudioCDBurner object is deleted. Your caller
  27156. method shouldn't keep a reference to it or use it again after passing
  27157. it in here.
  27158. */
  27159. bool addAudioTrack (AudioSource* source, int numSamples);
  27160. /**
  27161. Return true to cancel the current burn operation
  27162. */
  27163. class BurnProgressListener
  27164. {
  27165. public:
  27166. BurnProgressListener() throw() {}
  27167. virtual ~BurnProgressListener() {}
  27168. /** Called at intervals to report on the progress of the AudioCDBurner.
  27169. To cancel the burn, return true from this.
  27170. */
  27171. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  27172. };
  27173. const String burn (BurnProgressListener* listener,
  27174. const bool ejectDiscAfterwards,
  27175. const bool peformFakeBurnForTesting);
  27176. juce_UseDebuggingNewOperator
  27177. private:
  27178. AudioCDBurner (const int deviceIndex);
  27179. void* internal;
  27180. };
  27181. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27182. /********* End of inlined file: juce_AudioCDBurner.h *********/
  27183. #endif
  27184. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27185. /********* Start of inlined file: juce_AudioCDReader.h *********/
  27186. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27187. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  27188. #if JUCE_MAC
  27189. #endif
  27190. /**
  27191. A type of AudioFormatReader that reads from an audio CD.
  27192. One of these can be used to read a CD as if it's one big audio stream. Use the
  27193. getPositionOfTrackStart() method to find where the individual tracks are
  27194. within the stream.
  27195. @see AudioFormatReader
  27196. */
  27197. class JUCE_API AudioCDReader : public AudioFormatReader
  27198. {
  27199. public:
  27200. /** Returns a list of names of Audio CDs currently available for reading.
  27201. If there's a CD drive but no CD in it, this might return an empty list, or
  27202. possibly a device that can be opened but which has no tracks, depending
  27203. on the platform.
  27204. @see createReaderForCD
  27205. */
  27206. static const StringArray getAvailableCDNames();
  27207. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  27208. @param index the index of one of the available CDs - use getAvailableCDNames()
  27209. to find out how many there are.
  27210. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  27211. caller will be responsible for deleting the object returned.
  27212. */
  27213. static AudioCDReader* createReaderForCD (const int index);
  27214. /** Destructor. */
  27215. ~AudioCDReader();
  27216. /** Implementation of the AudioFormatReader method. */
  27217. bool read (int** destSamples,
  27218. int64 startSampleInFile,
  27219. int numSamples);
  27220. /** Checks whether the CD has been removed from the drive.
  27221. */
  27222. bool isCDStillPresent() const;
  27223. /** Returns the total number of tracks (audio + data).
  27224. */
  27225. int getNumTracks() const;
  27226. /** Finds the sample offset of the start of a track.
  27227. @param trackNum the track number, where 0 is the first track.
  27228. */
  27229. int getPositionOfTrackStart (int trackNum) const;
  27230. /** Returns true if a given track is an audio track.
  27231. @param trackNum the track number, where 0 is the first track.
  27232. */
  27233. bool isTrackAudio (int trackNum) const;
  27234. /** Refreshes the object's table of contents.
  27235. If the disc has been ejected and a different one put in since this
  27236. object was created, this will cause it to update its idea of how many tracks
  27237. there are, etc.
  27238. */
  27239. void refreshTrackLengths();
  27240. /** Enables scanning for indexes within tracks.
  27241. @see getLastIndex
  27242. */
  27243. void enableIndexScanning (bool enabled);
  27244. /** Returns the index number found during the last read() call.
  27245. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27246. Then when the read() method is called, if it comes across an index within that
  27247. block, the index number is stored and returned by this method.
  27248. Some devices might not support indexes, of course.
  27249. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27250. @see enableIndexScanning
  27251. */
  27252. int getLastIndex() const;
  27253. /** Scans a track to find the position of any indexes within it.
  27254. @param trackNumber the track to look in, where 0 is the first track on the disc
  27255. @returns an array of sample positions of any index points found (not including
  27256. the index that marks the start of the track)
  27257. */
  27258. const Array <int> findIndexesInTrack (const int trackNumber);
  27259. /** Returns the CDDB id number for the CD.
  27260. It's not a great way of identifying a disc, but it's traditional.
  27261. */
  27262. int getCDDBId();
  27263. /** Tries to eject the disk.
  27264. Of course this might not be possible, if some other process is using it.
  27265. */
  27266. void ejectDisk();
  27267. juce_UseDebuggingNewOperator
  27268. private:
  27269. #if JUCE_MAC
  27270. File volumeDir;
  27271. OwnedArray<File> tracks;
  27272. Array <int> trackStartSamples;
  27273. int currentReaderTrack;
  27274. AudioFormatReader* reader;
  27275. AudioCDReader (const File& volume);
  27276. public:
  27277. static int compareElements (const File* const, const File* const) throw();
  27278. private:
  27279. #elif JUCE_WIN32
  27280. int numTracks;
  27281. int trackStarts[100];
  27282. bool audioTracks [100];
  27283. void* handle;
  27284. bool indexingEnabled;
  27285. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27286. MemoryBlock buffer;
  27287. AudioCDReader (void* handle);
  27288. int getIndexAt (int samplePos);
  27289. #elif JUCE_LINUX
  27290. AudioCDReader();
  27291. #endif
  27292. AudioCDReader (const AudioCDReader&);
  27293. const AudioCDReader& operator= (const AudioCDReader&);
  27294. };
  27295. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27296. /********* End of inlined file: juce_AudioCDReader.h *********/
  27297. #endif
  27298. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27299. #endif
  27300. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27301. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  27302. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27303. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27304. /**
  27305. A class for keeping a list of available audio formats, and for deciding which
  27306. one to use to open a given file.
  27307. You can either use this class as a singleton object, or create instances of it
  27308. yourself. Once created, use its registerFormat() method to tell it which
  27309. formats it should use.
  27310. @see AudioFormat
  27311. */
  27312. class JUCE_API AudioFormatManager
  27313. {
  27314. public:
  27315. /** Creates an empty format manager.
  27316. Before it'll be any use, you'll need to call registerFormat() with all the
  27317. formats you want it to be able to recognise.
  27318. */
  27319. AudioFormatManager();
  27320. /** Destructor. */
  27321. ~AudioFormatManager();
  27322. juce_DeclareSingleton (AudioFormatManager, false);
  27323. /** Adds a format to the manager's list of available file types.
  27324. The object passed-in will be deleted by this object, so don't keep a pointer
  27325. to it!
  27326. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27327. return this one when called.
  27328. */
  27329. void registerFormat (AudioFormat* newFormat,
  27330. const bool makeThisTheDefaultFormat);
  27331. /** Handy method to make it easy to register the formats that come with Juce.
  27332. Currently, this will add WAV and AIFF to the list.
  27333. */
  27334. void registerBasicFormats();
  27335. /** Clears the list of known formats. */
  27336. void clearFormats();
  27337. /** Returns the number of currently registered file formats. */
  27338. int getNumKnownFormats() const;
  27339. /** Returns one of the registered file formats. */
  27340. AudioFormat* getKnownFormat (const int index) const;
  27341. /** Looks for which of the known formats is listed as being for a given file
  27342. extension.
  27343. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27344. */
  27345. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27346. /** Returns the format which has been set as the default one.
  27347. You can set a format as being the default when it is registered. It's useful
  27348. when you want to write to a file, because the best format may change between
  27349. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27350. If none has been set as the default, this method will just return the first
  27351. one in the list.
  27352. */
  27353. AudioFormat* getDefaultFormat() const;
  27354. /** Returns a set of wildcards for file-matching that contains the extensions for
  27355. all known formats.
  27356. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27357. */
  27358. const String getWildcardForAllFormats() const;
  27359. /** Searches through the known formats to try to create a suitable reader for
  27360. this file.
  27361. If none of the registered formats can open the file, it'll return 0. If it
  27362. returns a reader, it's the caller's responsibility to delete the reader.
  27363. */
  27364. AudioFormatReader* createReaderFor (const File& audioFile);
  27365. /** Searches through the known formats to try to create a suitable reader for
  27366. this stream.
  27367. The stream object that is passed-in will be deleted by this method or by the
  27368. reader that is returned, so the caller should not keep any references to it.
  27369. The stream that is passed-in must be capable of being repositioned so
  27370. that all the formats can have a go at opening it.
  27371. If none of the registered formats can open the stream, it'll return 0. If it
  27372. returns a reader, it's the caller's responsibility to delete the reader.
  27373. */
  27374. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27375. juce_UseDebuggingNewOperator
  27376. private:
  27377. VoidArray knownFormats;
  27378. int defaultFormatIndex;
  27379. };
  27380. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27381. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27382. #endif
  27383. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27384. #endif
  27385. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27386. #endif
  27387. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27388. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  27389. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27390. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27391. /**
  27392. This class is used to wrap an AudioFormatReader and only read from a
  27393. subsection of the file.
  27394. So if you have a reader which can read a 1000 sample file, you could wrap it
  27395. in one of these to only access, e.g. samples 100 to 200, and any samples
  27396. outside that will come back as 0. Accessing sample 0 from this reader will
  27397. actually read the first sample from the other's subsection, which might
  27398. be at a non-zero position.
  27399. @see AudioFormatReader
  27400. */
  27401. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27402. {
  27403. public:
  27404. /** Creates a AudioSubsectionReader for a given data source.
  27405. @param sourceReader the source reader from which we'll be taking data
  27406. @param subsectionStartSample the sample within the source reader which will be
  27407. mapped onto sample 0 for this reader.
  27408. @param subsectionLength the number of samples from the source that will
  27409. make up the subsection. If this reader is asked for
  27410. any samples beyond this region, it will return zero.
  27411. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27412. this object is deleted.
  27413. */
  27414. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  27415. const int64 subsectionStartSample,
  27416. const int64 subsectionLength,
  27417. const bool deleteSourceWhenDeleted);
  27418. /** Destructor. */
  27419. ~AudioSubsectionReader();
  27420. bool read (int** destSamples,
  27421. int64 startSample,
  27422. int numSamples);
  27423. void readMaxLevels (int64 startSample,
  27424. int64 numSamples,
  27425. float& lowestLeft,
  27426. float& highestLeft,
  27427. float& lowestRight,
  27428. float& highestRight);
  27429. juce_UseDebuggingNewOperator
  27430. private:
  27431. AudioFormatReader* const source;
  27432. int64 startSample, length;
  27433. const bool deleteSourceWhenDeleted;
  27434. AudioSubsectionReader (const AudioSubsectionReader&);
  27435. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  27436. };
  27437. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27438. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  27439. #endif
  27440. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27441. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27442. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27443. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27444. class AudioThumbnailCache;
  27445. /**
  27446. Makes it easy to quickly draw scaled views of the waveform shape of an
  27447. audio file.
  27448. To use this class, just create an AudioThumbNail class for the file you want
  27449. to draw, call setSource to tell it which file or resource to use, then call
  27450. drawChannel() to draw it.
  27451. The class will asynchronously scan the wavefile to create its scaled-down view,
  27452. so you should make your UI repaint itself as this data comes in. To do this, the
  27453. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27454. listeners should repaint themselves.
  27455. The thumbnail stores an internal low-res version of the wave data, and this can
  27456. be loaded and saved to avoid having to scan the file again.
  27457. @see AudioThumbnailCache
  27458. */
  27459. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27460. public TimeSliceClient,
  27461. private Timer
  27462. {
  27463. public:
  27464. /** Creates an audio thumbnail.
  27465. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27466. of the audio data, this is the scale at which it should be done
  27467. @param formatManagerToUse the audio format manager that is used to open the file
  27468. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27469. thread and storage that is used to by the thumbnail, and the cache
  27470. object can be shared between multiple thumbnails
  27471. */
  27472. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27473. AudioFormatManager& formatManagerToUse,
  27474. AudioThumbnailCache& cacheToUse);
  27475. /** Destructor. */
  27476. ~AudioThumbnail();
  27477. /** Specifies the file or stream that contains the audio file.
  27478. For a file, just call
  27479. @code
  27480. setSource (new FileInputSource (file))
  27481. @endcode
  27482. You can pass a zero in here to clear the thumbnail.
  27483. The source that is passed in will be deleted by this object when it is no
  27484. longer needed
  27485. */
  27486. void setSource (InputSource* const newSource);
  27487. /** Reloads the low res thumbnail data from an input stream.
  27488. The thumb will automatically attempt to reload itself from its
  27489. AudioThumbnailCache.
  27490. */
  27491. void loadFrom (InputStream& input);
  27492. /** Saves the low res thumbnail data to an output stream.
  27493. The thumb will automatically attempt to save itself to its
  27494. AudioThumbnailCache after it finishes scanning the wave file.
  27495. */
  27496. void saveTo (OutputStream& output) const;
  27497. /** Returns the number of channels in the file.
  27498. */
  27499. int getNumChannels() const throw();
  27500. /** Returns the length of the audio file.
  27501. */
  27502. double getTotalLength() const throw();
  27503. /** Renders the waveform shape for a channel.
  27504. The waveform will be drawn within the specified rectangle, where startTime
  27505. and endTime specify the times within the audio file that should be positioned
  27506. at the left and right edges of the rectangle.
  27507. The waveform will be scaled vertically so that a full-volume sample will fill
  27508. the rectangle vertically, but you can also specify an extra vertical scale factor
  27509. with the verticalZoomFactor parameter.
  27510. */
  27511. void drawChannel (Graphics& g,
  27512. int x, int y, int w, int h,
  27513. double startTime,
  27514. double endTime,
  27515. int channelNum,
  27516. const float verticalZoomFactor);
  27517. /** Returns true if the low res preview is fully generated.
  27518. */
  27519. bool isFullyLoaded() const throw();
  27520. /** @internal */
  27521. bool useTimeSlice();
  27522. /** @internal */
  27523. void timerCallback();
  27524. juce_UseDebuggingNewOperator
  27525. private:
  27526. AudioFormatManager& formatManagerToUse;
  27527. AudioThumbnailCache& cache;
  27528. InputSource* source;
  27529. CriticalSection readerLock;
  27530. AudioFormatReader* reader;
  27531. MemoryBlock data, cachedLevels;
  27532. int orginalSamplesPerThumbnailSample;
  27533. int numChannelsCached, numSamplesCached;
  27534. double cachedStart, cachedTimePerPixel;
  27535. bool cacheNeedsRefilling;
  27536. void clear();
  27537. AudioFormatReader* createReader() const;
  27538. void generateSection (AudioFormatReader& reader,
  27539. int64 startSample,
  27540. int numSamples);
  27541. char* getChannelData (int channel) const;
  27542. void refillCache (const int numSamples,
  27543. double startTime,
  27544. const double timePerPixel);
  27545. friend class AudioThumbnailCache;
  27546. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27547. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27548. // returns true if more needs to be read
  27549. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27550. };
  27551. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27552. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27553. #endif
  27554. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27555. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27556. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27557. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27558. struct ThumbnailCacheEntry;
  27559. /**
  27560. An instance of this class is used to manage multiple AudioThumbnail objects.
  27561. The cache runs a single background thread that is shared by all the thumbnails
  27562. that need it, and it maintains a set of low-res previews in memory, to avoid
  27563. having to re-scan audio files too often.
  27564. @see AudioThumbnail
  27565. */
  27566. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27567. {
  27568. public:
  27569. /** Creates a cache object.
  27570. The maxNumThumbsToStore parameter lets you specify how many previews should
  27571. be kept in memory at once.
  27572. */
  27573. AudioThumbnailCache (const int maxNumThumbsToStore);
  27574. /** Destructor. */
  27575. ~AudioThumbnailCache();
  27576. /** Clears out any stored thumbnails.
  27577. */
  27578. void clear();
  27579. /** Reloads the specified thumb if this cache contains the appropriate stored
  27580. data.
  27581. This is called automatically by the AudioThumbnail class, so you shouldn't
  27582. normally need to call it directly.
  27583. */
  27584. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27585. /** Stores the cachable data from the specified thumb in this cache.
  27586. This is called automatically by the AudioThumbnail class, so you shouldn't
  27587. normally need to call it directly.
  27588. */
  27589. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27590. juce_UseDebuggingNewOperator
  27591. private:
  27592. OwnedArray <ThumbnailCacheEntry> thumbs;
  27593. int maxNumThumbsToStore;
  27594. friend class AudioThumbnail;
  27595. void addThumbnail (AudioThumbnail* const thumb);
  27596. void removeThumbnail (AudioThumbnail* const thumb);
  27597. };
  27598. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27599. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  27600. #endif
  27601. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27602. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  27603. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27604. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27605. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27606. /**
  27607. Reads and writes the lossless-compression FLAC audio format.
  27608. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27609. and make sure your include search path and library search path are set up to find
  27610. the FLAC header files and static libraries.
  27611. @see AudioFormat
  27612. */
  27613. class JUCE_API FlacAudioFormat : public AudioFormat
  27614. {
  27615. public:
  27616. FlacAudioFormat();
  27617. ~FlacAudioFormat();
  27618. const Array <int> getPossibleSampleRates();
  27619. const Array <int> getPossibleBitDepths();
  27620. bool canDoStereo();
  27621. bool canDoMono();
  27622. bool isCompressed();
  27623. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27624. const bool deleteStreamIfOpeningFails);
  27625. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27626. double sampleRateToUse,
  27627. unsigned int numberOfChannels,
  27628. int bitsPerSample,
  27629. const StringPairArray& metadataValues,
  27630. int qualityOptionIndex);
  27631. juce_UseDebuggingNewOperator
  27632. };
  27633. #endif
  27634. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27635. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  27636. #endif
  27637. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27638. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  27639. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27640. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27641. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  27642. /**
  27643. Reads and writes the Ogg-Vorbis audio format.
  27644. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  27645. and make sure your include search path and library search path are set up to find
  27646. the Vorbis and Ogg header files and static libraries.
  27647. @see AudioFormat,
  27648. */
  27649. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  27650. {
  27651. public:
  27652. OggVorbisAudioFormat();
  27653. ~OggVorbisAudioFormat();
  27654. const Array <int> getPossibleSampleRates();
  27655. const Array <int> getPossibleBitDepths();
  27656. bool canDoStereo();
  27657. bool canDoMono();
  27658. bool isCompressed();
  27659. const StringArray getQualityOptions();
  27660. /** Tries to estimate the quality level of an ogg file based on its size.
  27661. If it can't read the file for some reason, this will just return 1 (medium quality),
  27662. otherwise it will return the approximate quality setting that would have been used
  27663. to create the file.
  27664. @see getQualityOptions
  27665. */
  27666. int estimateOggFileQuality (const File& source);
  27667. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27668. const bool deleteStreamIfOpeningFails);
  27669. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27670. double sampleRateToUse,
  27671. unsigned int numberOfChannels,
  27672. int bitsPerSample,
  27673. const StringPairArray& metadataValues,
  27674. int qualityOptionIndex);
  27675. juce_UseDebuggingNewOperator
  27676. };
  27677. #endif
  27678. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  27679. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  27680. #endif
  27681. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27682. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  27683. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27684. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27685. #if JUCE_QUICKTIME
  27686. /**
  27687. Uses QuickTime to read the audio track a movie or media file.
  27688. As well as QuickTime movies, this should also manage to open other audio
  27689. files that quicktime can understand, like mp3, m4a, etc.
  27690. @see AudioFormat
  27691. */
  27692. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  27693. {
  27694. public:
  27695. /** Creates a format object. */
  27696. QuickTimeAudioFormat();
  27697. /** Destructor. */
  27698. ~QuickTimeAudioFormat();
  27699. const Array <int> getPossibleSampleRates();
  27700. const Array <int> getPossibleBitDepths();
  27701. bool canDoStereo();
  27702. bool canDoMono();
  27703. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27704. const bool deleteStreamIfOpeningFails);
  27705. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27706. double sampleRateToUse,
  27707. unsigned int numberOfChannels,
  27708. int bitsPerSample,
  27709. const StringPairArray& metadataValues,
  27710. int qualityOptionIndex);
  27711. juce_UseDebuggingNewOperator
  27712. };
  27713. #endif
  27714. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  27715. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  27716. #endif
  27717. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27718. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  27719. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27720. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27721. /**
  27722. Reads and Writes WAV format audio files.
  27723. @see AudioFormat
  27724. */
  27725. class JUCE_API WavAudioFormat : public AudioFormat
  27726. {
  27727. public:
  27728. /** Creates a format object. */
  27729. WavAudioFormat();
  27730. /** Destructor. */
  27731. ~WavAudioFormat();
  27732. /** Metadata property name used by wav readers and writers for adding
  27733. a BWAV chunk to the file.
  27734. @see AudioFormatReader::metadataValues, createWriterFor
  27735. */
  27736. static const tchar* const bwavDescription;
  27737. /** Metadata property name used by wav readers and writers for adding
  27738. a BWAV chunk to the file.
  27739. @see AudioFormatReader::metadataValues, createWriterFor
  27740. */
  27741. static const tchar* const bwavOriginator;
  27742. /** Metadata property name used by wav readers and writers for adding
  27743. a BWAV chunk to the file.
  27744. @see AudioFormatReader::metadataValues, createWriterFor
  27745. */
  27746. static const tchar* const bwavOriginatorRef;
  27747. /** Metadata property name used by wav readers and writers for adding
  27748. a BWAV chunk to the file.
  27749. Date format is: yyyy-mm-dd
  27750. @see AudioFormatReader::metadataValues, createWriterFor
  27751. */
  27752. static const tchar* const bwavOriginationDate;
  27753. /** Metadata property name used by wav readers and writers for adding
  27754. a BWAV chunk to the file.
  27755. Time format is: hh-mm-ss
  27756. @see AudioFormatReader::metadataValues, createWriterFor
  27757. */
  27758. static const tchar* const bwavOriginationTime;
  27759. /** Metadata property name used by wav readers and writers for adding
  27760. a BWAV chunk to the file.
  27761. This is the number of samples from the start of an edit that the
  27762. file is supposed to begin at. Seems like an obvious mistake to
  27763. only allow a file to occur in an edit once, but that's the way
  27764. it is..
  27765. @see AudioFormatReader::metadataValues, createWriterFor
  27766. */
  27767. static const tchar* const bwavTimeReference;
  27768. /** Metadata property name used by wav readers and writers for adding
  27769. a BWAV chunk to the file.
  27770. This is a
  27771. @see AudioFormatReader::metadataValues, createWriterFor
  27772. */
  27773. static const tchar* const bwavCodingHistory;
  27774. /** Utility function to fill out the appropriate metadata for a BWAV file.
  27775. This just makes it easier than using the property names directly, and it
  27776. fills out the time and date in the right format.
  27777. */
  27778. static const StringPairArray createBWAVMetadata (const String& description,
  27779. const String& originator,
  27780. const String& originatorRef,
  27781. const Time& dateAndTime,
  27782. const int64 timeReferenceSamples,
  27783. const String& codingHistory);
  27784. const Array <int> getPossibleSampleRates();
  27785. const Array <int> getPossibleBitDepths();
  27786. bool canDoStereo();
  27787. bool canDoMono();
  27788. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27789. const bool deleteStreamIfOpeningFails);
  27790. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27791. double sampleRateToUse,
  27792. unsigned int numberOfChannels,
  27793. int bitsPerSample,
  27794. const StringPairArray& metadataValues,
  27795. int qualityOptionIndex);
  27796. juce_UseDebuggingNewOperator
  27797. };
  27798. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  27799. /********* End of inlined file: juce_WavAudioFormat.h *********/
  27800. #endif
  27801. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27802. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  27803. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27804. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27805. /********* Start of inlined file: juce_ActionListenerList.h *********/
  27806. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27807. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27808. /**
  27809. A set of ActionListeners.
  27810. Listeners can be added and removed from the list, and messages can be
  27811. broadcast to all the listeners.
  27812. @see ActionListener, ActionBroadcaster
  27813. */
  27814. class JUCE_API ActionListenerList : public MessageListener
  27815. {
  27816. public:
  27817. /** Creates an empty list. */
  27818. ActionListenerList() throw();
  27819. /** Destructor. */
  27820. ~ActionListenerList() throw();
  27821. /** Adds a listener to the list.
  27822. (Trying to add a listener that's already on the list will have no effect).
  27823. */
  27824. void addActionListener (ActionListener* const listener) throw();
  27825. /** Removes a listener from the list.
  27826. If the listener isn't on the list, this won't have any effect.
  27827. */
  27828. void removeActionListener (ActionListener* const listener) throw();
  27829. /** Removes all listeners from the list. */
  27830. void removeAllActionListeners() throw();
  27831. /** Broadcasts a message to all the registered listeners.
  27832. This sends the message asynchronously.
  27833. If a listener is on the list when this method is called but is removed from
  27834. the list before the message arrives, it won't receive the message. Similarly
  27835. listeners that are added to the list after the message is sent but before it
  27836. arrives won't get the message either.
  27837. */
  27838. void sendActionMessage (const String& message) const;
  27839. /** @internal */
  27840. void handleMessage (const Message&);
  27841. juce_UseDebuggingNewOperator
  27842. private:
  27843. SortedSet <void*> actionListeners_;
  27844. CriticalSection actionListenerLock_;
  27845. ActionListenerList (const ActionListenerList&);
  27846. const ActionListenerList& operator= (const ActionListenerList&);
  27847. };
  27848. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27849. /********* End of inlined file: juce_ActionListenerList.h *********/
  27850. /** Manages a list of ActionListeners, and can send them messages.
  27851. To quickly add methods to your class that can add/remove action
  27852. listeners and broadcast to them, you can derive from this.
  27853. @see ActionListenerList, ActionListener
  27854. */
  27855. class JUCE_API ActionBroadcaster
  27856. {
  27857. public:
  27858. /** Creates an ActionBroadcaster. */
  27859. ActionBroadcaster() throw();
  27860. /** Destructor. */
  27861. virtual ~ActionBroadcaster();
  27862. /** Adds a listener to the list.
  27863. (Trying to add a listener that's already on the list will have no effect).
  27864. */
  27865. void addActionListener (ActionListener* const listener);
  27866. /** Removes a listener from the list.
  27867. If the listener isn't on the list, this won't have any effect.
  27868. */
  27869. void removeActionListener (ActionListener* const listener);
  27870. /** Removes all listeners from the list. */
  27871. void removeAllActionListeners();
  27872. /** Broadcasts a message to all the registered listeners.
  27873. @see ActionListenerList::sendActionMessage
  27874. */
  27875. void sendActionMessage (const String& message) const;
  27876. private:
  27877. ActionListenerList actionListenerList;
  27878. ActionBroadcaster (const ActionBroadcaster&);
  27879. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  27880. };
  27881. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  27882. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  27883. #endif
  27884. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  27885. #endif
  27886. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  27887. #endif
  27888. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  27889. #endif
  27890. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  27891. #endif
  27892. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  27893. #endif
  27894. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  27895. #endif
  27896. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27897. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  27898. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27899. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  27900. class InterprocessConnectionServer;
  27901. /**
  27902. Manages a simple two-way messaging connection to another process, using either
  27903. a socket or a named pipe as the transport medium.
  27904. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  27905. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  27906. and incoming messages will result in a callback via the messageReceived()
  27907. method.
  27908. To open a pipe and wait for another client to connect to it, use the createPipe()
  27909. method.
  27910. To act as a socket server and create connections for one or more client, see the
  27911. InterprocessConnectionServer class.
  27912. @see InterprocessConnectionServer, Socket, NamedPipe
  27913. */
  27914. class JUCE_API InterprocessConnection : public Thread,
  27915. private MessageListener
  27916. {
  27917. public:
  27918. /** Creates a connection.
  27919. Connections are created manually, connecting them with the connectToSocket()
  27920. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  27921. when a client wants to connect.
  27922. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  27923. connectionLost() and messageReceived() methods will
  27924. always be made using the message thread; if false,
  27925. these will be called immediately on the connection's
  27926. own thread.
  27927. @param magicMessageHeaderNumber a magic number to use in the header to check the
  27928. validity of the data blocks being sent and received. This
  27929. can be any number, but the sender and receiver must obviously
  27930. use matching values or they won't recognise each other.
  27931. */
  27932. InterprocessConnection (const bool callbacksOnMessageThread = true,
  27933. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  27934. /** Destructor. */
  27935. ~InterprocessConnection();
  27936. /** Tries to connect this object to a socket.
  27937. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  27938. object waiting to receive client connections on this port number.
  27939. @param hostName the host computer, either a network address or name
  27940. @param portNumber the socket port number to try to connect to
  27941. @param timeOutMillisecs how long to keep trying before giving up
  27942. @returns true if the connection is established successfully
  27943. @see Socket
  27944. */
  27945. bool connectToSocket (const String& hostName,
  27946. const int portNumber,
  27947. const int timeOutMillisecs);
  27948. /** Tries to connect the object to an existing named pipe.
  27949. For this to work, another process on the same computer must already have opened
  27950. an InterprocessConnection object and used createPipe() to create a pipe for this
  27951. to connect to.
  27952. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27953. @returns true if it connects successfully.
  27954. @see createPipe, NamedPipe
  27955. */
  27956. bool connectToPipe (const String& pipeName,
  27957. const int pipeReceiveMessageTimeoutMs = -1);
  27958. /** Tries to create a new pipe for other processes to connect to.
  27959. This creates a pipe with the given name, so that other processes can use
  27960. connectToPipe() to connect to the other end.
  27961. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  27962. If another process is already using this pipe, this will fail and return false.
  27963. */
  27964. bool createPipe (const String& pipeName,
  27965. const int pipeReceiveMessageTimeoutMs = -1);
  27966. /** Disconnects and closes any currently-open sockets or pipes. */
  27967. void disconnect();
  27968. /** True if a socket or pipe is currently active. */
  27969. bool isConnected() const;
  27970. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  27971. StreamingSocket* getSocket() const throw() { return socket; }
  27972. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  27973. NamedPipe* getPipe() const throw() { return pipe; }
  27974. /** Returns the name of the machine at the other end of this connection.
  27975. This will return an empty string if the other machine isn't known for
  27976. some reason.
  27977. */
  27978. const String getConnectedHostName() const;
  27979. /** Tries to send a message to the other end of this connection.
  27980. This will fail if it's not connected, or if there's some kind of write error. If
  27981. it succeeds, the connection object at the other end will receive the message by
  27982. a callback to its messageReceived() method.
  27983. @see messageReceived
  27984. */
  27985. bool sendMessage (const MemoryBlock& message);
  27986. /** Called when the connection is first connected.
  27987. If the connection was created with the callbacksOnMessageThread flag set, then
  27988. this will be called on the message thread; otherwise it will be called on a server
  27989. thread.
  27990. */
  27991. virtual void connectionMade() = 0;
  27992. /** Called when the connection is broken.
  27993. If the connection was created with the callbacksOnMessageThread flag set, then
  27994. this will be called on the message thread; otherwise it will be called on a server
  27995. thread.
  27996. */
  27997. virtual void connectionLost() = 0;
  27998. /** Called when a message arrives.
  27999. When the object at the other end of this connection sends us a message with sendMessage(),
  28000. this callback is used to deliver it to us.
  28001. If the connection was created with the callbacksOnMessageThread flag set, then
  28002. this will be called on the message thread; otherwise it will be called on a server
  28003. thread.
  28004. @see sendMessage
  28005. */
  28006. virtual void messageReceived (const MemoryBlock& message) = 0;
  28007. juce_UseDebuggingNewOperator
  28008. private:
  28009. CriticalSection pipeAndSocketLock;
  28010. StreamingSocket* socket;
  28011. NamedPipe* pipe;
  28012. bool callbackConnectionState;
  28013. const bool useMessageThread;
  28014. const uint32 magicMessageHeader;
  28015. int pipeReceiveMessageTimeout;
  28016. friend class InterprocessConnectionServer;
  28017. void initialiseWithSocket (StreamingSocket* const socket_);
  28018. void initialiseWithPipe (NamedPipe* const pipe_);
  28019. void handleMessage (const Message& message);
  28020. void connectionMadeInt();
  28021. void connectionLostInt();
  28022. void deliverDataInt (const MemoryBlock& data);
  28023. bool readNextMessageInt();
  28024. void run();
  28025. InterprocessConnection (const InterprocessConnection&);
  28026. const InterprocessConnection& operator= (const InterprocessConnection&);
  28027. };
  28028. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28029. /********* End of inlined file: juce_InterprocessConnection.h *********/
  28030. #endif
  28031. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28032. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  28033. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28034. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28035. /**
  28036. An object that waits for client sockets to connect to a port on this host, and
  28037. creates InterprocessConnection objects for each one.
  28038. To use this, create a class derived from it which implements the createConnectionObject()
  28039. method, so that it creates suitable connection objects for each client that tries
  28040. to connect.
  28041. @see InterprocessConnection
  28042. */
  28043. class JUCE_API InterprocessConnectionServer : private Thread
  28044. {
  28045. public:
  28046. /** Creates an uninitialised server object.
  28047. */
  28048. InterprocessConnectionServer();
  28049. /** Destructor. */
  28050. ~InterprocessConnectionServer();
  28051. /** Starts an internal thread which listens on the given port number.
  28052. While this is running, in another process tries to connect with the
  28053. InterprocessConnection::connectToSocket() method, this object will call
  28054. createConnectionObject() to create a connection to that client.
  28055. Use stop() to stop the thread running.
  28056. @see createConnectionObject, stop
  28057. */
  28058. bool beginWaitingForSocket (const int portNumber);
  28059. /** Terminates the listener thread, if it's active.
  28060. @see beginWaitingForSocket
  28061. */
  28062. void stop();
  28063. protected:
  28064. /** Creates a suitable connection object for a client process that wants to
  28065. connect to this one.
  28066. This will be called by the listener thread when a client process tries
  28067. to connect, and must return a new InterprocessConnection object that will
  28068. then run as this end of the connection.
  28069. @see InterprocessConnection
  28070. */
  28071. virtual InterprocessConnection* createConnectionObject() = 0;
  28072. public:
  28073. juce_UseDebuggingNewOperator
  28074. private:
  28075. StreamingSocket* volatile socket;
  28076. void run();
  28077. InterprocessConnectionServer (const InterprocessConnectionServer&);
  28078. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  28079. };
  28080. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28081. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  28082. #endif
  28083. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  28084. #endif
  28085. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  28086. #endif
  28087. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28088. /********* Start of inlined file: juce_MessageManager.h *********/
  28089. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28090. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28091. class Component;
  28092. class MessageManagerLock;
  28093. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  28094. */
  28095. typedef void* (MessageCallbackFunction) (void* userData);
  28096. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  28097. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  28098. */
  28099. class JUCE_API MessageManager : private DeletedAtShutdown
  28100. {
  28101. public:
  28102. /** Returns the global instance of the MessageManager. */
  28103. static MessageManager* getInstance() throw();
  28104. /** Runs the event dispatch loop until a stop message is posted.
  28105. This method is only intended to be run by the application's startup routine,
  28106. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  28107. @see stopDispatchLoop
  28108. */
  28109. void runDispatchLoop();
  28110. /** Sends a signal that the dispatch loop should terminate.
  28111. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  28112. will be interrupted and will return.
  28113. @see runDispatchLoop
  28114. */
  28115. void stopDispatchLoop();
  28116. /** Returns true if the stopDispatchLoop() method has been called.
  28117. */
  28118. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  28119. /** Synchronously dispatches messages until a given time has elapsed.
  28120. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  28121. otherwise returns true.
  28122. */
  28123. bool runDispatchLoopUntil (int millisecondsToRunFor);
  28124. /** Calls a function using the message-thread.
  28125. This can be used by any thread to cause this function to be called-back
  28126. by the message thread. If it's the message-thread that's calling this method,
  28127. then the function will just be called; if another thread is calling, a message
  28128. will be posted to the queue, and this method will block until that message
  28129. is delivered, the function is called, and the result is returned.
  28130. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  28131. thread has a critical section locked, which an unrelated message callback then tries to lock
  28132. before the message thread gets round to processing this callback.
  28133. @param callback the function to call - its signature must be @code
  28134. void* myCallbackFunction (void*) @endcode
  28135. @param userData a user-defined pointer that will be passed to the function that gets called
  28136. @returns the value that the callback function returns.
  28137. @see MessageManagerLock
  28138. */
  28139. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  28140. void* userData);
  28141. /** Returns true if the caller-thread is the message thread. */
  28142. bool isThisTheMessageThread() const throw();
  28143. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  28144. (Best to ignore this method unless you really know what you're doing..)
  28145. @see getCurrentMessageThread
  28146. */
  28147. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  28148. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  28149. (Best to ignore this method unless you really know what you're doing..)
  28150. @see setCurrentMessageThread
  28151. */
  28152. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  28153. /** Returns true if the caller thread has currenltly got the message manager locked.
  28154. see the MessageManagerLock class for more info about this.
  28155. This will be true if the caller is the message thread, because that automatically
  28156. gains a lock while a message is being dispatched.
  28157. */
  28158. bool currentThreadHasLockedMessageManager() const throw();
  28159. /** Sends a message to all other JUCE applications that are running.
  28160. @param messageText the string that will be passed to the actionListenerCallback()
  28161. method of the broadcast listeners in the other app.
  28162. @see registerBroadcastListener, ActionListener
  28163. */
  28164. static void broadcastMessage (const String& messageText) throw();
  28165. /** Registers a listener to get told about broadcast messages.
  28166. The actionListenerCallback() callback's string parameter
  28167. is the message passed into broadcastMessage().
  28168. @see broadcastMessage
  28169. */
  28170. void registerBroadcastListener (ActionListener* listener) throw();
  28171. /** Deregisters a broadcast listener. */
  28172. void deregisterBroadcastListener (ActionListener* listener) throw();
  28173. /** @internal */
  28174. void deliverMessage (void*);
  28175. /** @internal */
  28176. void deliverBroadcastMessage (const String&);
  28177. juce_UseDebuggingNewOperator
  28178. private:
  28179. MessageManager() throw();
  28180. ~MessageManager() throw();
  28181. friend class MessageListener;
  28182. friend class ChangeBroadcaster;
  28183. friend class ActionBroadcaster;
  28184. static MessageManager* instance;
  28185. SortedSet<const MessageListener*> messageListeners;
  28186. ActionListenerList* broadcastListeners;
  28187. friend class JUCEApplication;
  28188. bool quitMessagePosted, quitMessageReceived;
  28189. Thread::ThreadID messageThreadId;
  28190. VoidArray modalComponents;
  28191. static void* exitModalLoopCallback (void*);
  28192. void postMessageToQueue (Message* const message);
  28193. static void doPlatformSpecificInitialisation();
  28194. static void doPlatformSpecificShutdown();
  28195. friend class MessageManagerLock;
  28196. CriticalSection messageDispatchLock;
  28197. Thread::ThreadID currentLockingThreadId;
  28198. MessageManager (const MessageManager&);
  28199. const MessageManager& operator= (const MessageManager&);
  28200. };
  28201. /** Used to make sure that the calling thread has exclusive access to the message loop.
  28202. Because it's not thread-safe to call any of the Component or other UI classes
  28203. from threads other than the message thread, one of these objects can be used to
  28204. lock the message loop and allow this to be done. The message thread will be
  28205. suspended for the lifetime of the MessageManagerLock object, so create one on
  28206. the stack like this: @code
  28207. void MyThread::run()
  28208. {
  28209. someData = 1234;
  28210. const MessageManagerLock mmLock;
  28211. // the event loop will now be locked so it's safe to make a few calls..
  28212. myComponent->setBounds (newBounds);
  28213. myComponent->repaint();
  28214. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  28215. }
  28216. @endcode
  28217. Obviously be careful not to create one of these and leave it lying around, or
  28218. your app will grind to a halt!
  28219. Another caveat is that using this in conjunction with other CriticalSections
  28220. can create lots of interesting ways of producing a deadlock! In particular, if
  28221. your message thread calls stopThread() for a thread that uses these locks,
  28222. you'll get an (occasional) deadlock..
  28223. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  28224. */
  28225. class JUCE_API MessageManagerLock
  28226. {
  28227. public:
  28228. /** Tries to acquire a lock on the message manager.
  28229. If this constructor
  28230. When this constructor returns, the message manager will have finished processing the
  28231. last message and will not send another message until this MessageManagerLock is
  28232. deleted.
  28233. If the current thread already has the lock, nothing will be done, so it's perfectly
  28234. safe to create these locks recursively.
  28235. */
  28236. MessageManagerLock() throw();
  28237. /** Releases the current thread's lock on the message manager.
  28238. Make sure this object is created and deleted by the same thread,
  28239. otherwise there are no guarantees what will happen!
  28240. */
  28241. ~MessageManagerLock() throw();
  28242. /** Tries to acquire a lock on the message manager.
  28243. This does the same thing as the normal constructor, but while it's waiting to get
  28244. the lock, it checks the specified thread to see if it has been given the
  28245. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  28246. without gaining the lock.
  28247. To find out whether the lock was successful, call lockWasGained(). If this is
  28248. false, your thread is being told to die, so you'd better get out of there.
  28249. If the current thread already has the lock, nothing will be done, so it's perfectly
  28250. safe to create these locks recursively.
  28251. E.g.
  28252. @code
  28253. void run()
  28254. {
  28255. ...
  28256. while (! threadShouldExit())
  28257. {
  28258. MessageManagerLock mml (Thread::getCurrentThread());
  28259. if (! mml.lockWasGained)
  28260. return; // another thread is trying to kill us!
  28261. ..do some locked stuff here..
  28262. }
  28263. ..and now the MM is now unlocked..
  28264. }
  28265. @endcode
  28266. */
  28267. MessageManagerLock (Thread* const threadToCheckForExitSignal) throw();
  28268. /** Returns true if the lock was successfully acquired.
  28269. (See the constructor that takes a Thread for more info).
  28270. */
  28271. bool lockWasGained() const throw() { return locked; }
  28272. private:
  28273. Thread::ThreadID lastLockingThreadId;
  28274. bool locked;
  28275. };
  28276. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28277. /********* End of inlined file: juce_MessageManager.h *********/
  28278. #endif
  28279. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28280. /********* Start of inlined file: juce_MultiTimer.h *********/
  28281. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28282. #define __JUCE_MULTITIMER_JUCEHEADER__
  28283. /**
  28284. A type of timer class that can run multiple timers with different frequencies,
  28285. all of which share a single callback.
  28286. This class is very similar to the Timer class, but allows you run multiple
  28287. separate timers, where each one has a unique ID number. The methods in this
  28288. class are exactly equivalent to those in Timer, but with the addition of
  28289. this ID number.
  28290. To use it, you need to create a subclass of MultiTimer, implementing the
  28291. timerCallback() method. Then you can start timers with startTimer(), and
  28292. each time the callback is triggered, it passes in the ID of the timer that
  28293. caused it.
  28294. @see Timer
  28295. */
  28296. class JUCE_API MultiTimer
  28297. {
  28298. protected:
  28299. /** Creates a MultiTimer.
  28300. When created, no timers are running, so use startTimer() to start things off.
  28301. */
  28302. MultiTimer() throw();
  28303. /** Creates a copy of another timer.
  28304. Note that this timer will not contain any running timers, even if the one you're
  28305. copying from was running.
  28306. */
  28307. MultiTimer (const MultiTimer& other) throw();
  28308. public:
  28309. /** Destructor. */
  28310. virtual ~MultiTimer();
  28311. /** The user-defined callback routine that actually gets called by each of the
  28312. timers that are running.
  28313. It's perfectly ok to call startTimer() or stopTimer() from within this
  28314. callback to change the subsequent intervals.
  28315. */
  28316. virtual void timerCallback (const int timerId) = 0;
  28317. /** Starts a timer and sets the length of interval required.
  28318. If the timer is already started, this will reset it, so the
  28319. time between calling this method and the next timer callback
  28320. will not be less than the interval length passed in.
  28321. @param timerId a unique Id number that identifies the timer to
  28322. start. This is the id that will be passed back
  28323. to the timerCallback() method when this timer is
  28324. triggered
  28325. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  28326. rounded up to 1)
  28327. */
  28328. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  28329. /** Stops a timer.
  28330. If a timer has been started with the given ID number, it will be cancelled.
  28331. No more callbacks will be made for the specified timer after this method returns.
  28332. If this is called from a different thread, any callbacks that may
  28333. be currently executing may be allowed to finish before the method
  28334. returns.
  28335. */
  28336. void stopTimer (const int timerId) throw();
  28337. /** Checks whether a timer has been started for a specified ID.
  28338. @returns true if a timer with the given ID is running.
  28339. */
  28340. bool isTimerRunning (const int timerId) const throw();
  28341. /** Returns the interval for a specified timer ID.
  28342. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28343. is running for the ID number specified.
  28344. */
  28345. int getTimerInterval (const int timerId) const throw();
  28346. private:
  28347. CriticalSection timerListLock;
  28348. VoidArray timers;
  28349. const MultiTimer& operator= (const MultiTimer&);
  28350. };
  28351. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28352. /********* End of inlined file: juce_MultiTimer.h *********/
  28353. #endif
  28354. #ifndef __JUCE_TIMER_JUCEHEADER__
  28355. #endif
  28356. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28357. #endif
  28358. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28359. /********* Start of inlined file: juce_GradientBrush.h *********/
  28360. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28361. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28362. /********* Start of inlined file: juce_ColourGradient.h *********/
  28363. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28364. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28365. /**
  28366. Structure used to define a colour gradient for painting areas.
  28367. @see GradientBrush
  28368. */
  28369. class JUCE_API ColourGradient
  28370. {
  28371. public:
  28372. /** Creates a gradient object.
  28373. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28374. colour2 should be. In between them there's a gradient.
  28375. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28376. its centre.
  28377. The alpha transparencies of the colours are used, so note that
  28378. if you blend from transparent to a solid colour, the RGB of the transparent
  28379. colour will become visible in parts of the gradient. e.g. blending
  28380. from Colour::transparentBlack to Colours::white will produce a
  28381. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28382. will be white all the way across.
  28383. @see ColourGradient
  28384. */
  28385. ColourGradient (const Colour& colour1,
  28386. const float x1,
  28387. const float y1,
  28388. const Colour& colour2,
  28389. const float x2,
  28390. const float y2,
  28391. const bool isRadial) throw();
  28392. /** Creates an uninitialised gradient.
  28393. If you use this constructor instead of the other one, be sure to set all the
  28394. object's public member variables before using it!
  28395. */
  28396. ColourGradient() throw();
  28397. /** Destructor */
  28398. ~ColourGradient() throw();
  28399. /** Removes any colours that have been added.
  28400. This will also remove any start and end colours, so the gradient won't work. You'll
  28401. need to add more colours with addColour().
  28402. */
  28403. void clearColours() throw();
  28404. /** Adds a colour at a point along the length of the gradient.
  28405. This allows the gradient to go through a spectrum of colours, instead of just a
  28406. start and end colour.
  28407. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28408. of the distance along the line between the two points
  28409. at which the colour should occur.
  28410. @param colour the colour that should be used at this point
  28411. */
  28412. void addColour (const double proportionAlongGradient,
  28413. const Colour& colour) throw();
  28414. /** Multiplies the alpha value of all the colours by the given scale factor */
  28415. void multiplyOpacity (const float multiplier) throw();
  28416. /** Returns the number of colour-stops that have been added. */
  28417. int getNumColours() const throw();
  28418. /** Returns the position along the length of the gradient of the colour with this index.
  28419. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28420. */
  28421. double getColourPosition (const int index) const throw();
  28422. /** Returns the colour that was added with a given index.
  28423. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28424. */
  28425. const Colour getColour (const int index) const throw();
  28426. /** Creates a set of interpolated premultiplied ARGB values.
  28427. The caller must delete the array that is returned using juce_free().
  28428. */
  28429. PixelARGB* createLookupTable (int& numEntries) const throw();
  28430. /** Returns true if all colours are opaque. */
  28431. bool isOpaque() const throw();
  28432. /** Returns true if all colours are completely transparent. */
  28433. bool isInvisible() const throw();
  28434. float x1;
  28435. float y1;
  28436. float x2;
  28437. float y2;
  28438. /** If true, the gradient should be filled circularly, centred around
  28439. (x1, y1), with (x2, y2) defining a point on the circumference.
  28440. If false, the gradient is linear between the two points.
  28441. */
  28442. bool isRadial;
  28443. /** A transform to apply to the resultant gradient shape */
  28444. AffineTransform transform;
  28445. juce_UseDebuggingNewOperator
  28446. private:
  28447. Array <uint32> colours;
  28448. };
  28449. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28450. /********* End of inlined file: juce_ColourGradient.h *********/
  28451. /**
  28452. A Brush that fills areas with a colour gradient.
  28453. The gradient can either be linear or circular.
  28454. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28455. */
  28456. class JUCE_API GradientBrush : public Brush
  28457. {
  28458. public:
  28459. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28460. (x1, y1) is the location relative to the origin of the Graphics context,
  28461. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28462. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28463. its centre.
  28464. The alpha transparencies of the colours are used, so the brush
  28465. need not be completely opaque. Note that this means that if you
  28466. blend from transparent to a solid colour, the RGB of the transparent
  28467. colour will become visible in parts of the gradient. e.g. blending
  28468. from Colour::transparentBlack to Colours::white will produce a
  28469. grey colour, but Colour::transparentWhite to Colours::white will be
  28470. white all the way across.
  28471. @see ColourGradient
  28472. */
  28473. GradientBrush (const Colour& colour1,
  28474. const float x1,
  28475. const float y1,
  28476. const Colour& colour2,
  28477. const float x2,
  28478. const float y2,
  28479. const bool isRadial) throw();
  28480. /** Creates a gradient brush from a ColourGradient object.
  28481. */
  28482. GradientBrush (const ColourGradient& gradient) throw();
  28483. /** Destructor. */
  28484. ~GradientBrush() throw();
  28485. Brush* createCopy() const throw();
  28486. void applyTransform (const AffineTransform& transform) throw();
  28487. void multiplyOpacity (const float multiple) throw();
  28488. bool isInvisible() const throw();
  28489. void paintPath (LowLevelGraphicsContext& context,
  28490. const Path& path, const AffineTransform& transform) throw();
  28491. void paintRectangle (LowLevelGraphicsContext& context,
  28492. int x, int y, int w, int h) throw();
  28493. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28494. const Image& alphaChannelImage, int imageX, int imageY,
  28495. int x, int y, int w, int h) throw();
  28496. juce_UseDebuggingNewOperator
  28497. protected:
  28498. ColourGradient gradient;
  28499. private:
  28500. GradientBrush (const GradientBrush&);
  28501. const GradientBrush& operator= (const GradientBrush&);
  28502. };
  28503. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28504. /********* End of inlined file: juce_GradientBrush.h *********/
  28505. #endif
  28506. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28507. /********* Start of inlined file: juce_ImageBrush.h *********/
  28508. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28509. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28510. /********* Start of inlined file: juce_Image.h *********/
  28511. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28512. #define __JUCE_IMAGE_JUCEHEADER__
  28513. /**
  28514. Holds a fixed-size bitmap.
  28515. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28516. To draw into an image, create a Graphics object for it.
  28517. e.g. @code
  28518. // create a transparent 500x500 image..
  28519. Image myImage (Image::RGB, 500, 500, true);
  28520. Graphics g (myImage);
  28521. g.setColour (Colours::red);
  28522. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28523. @endcode
  28524. Other useful ways to create an image are with the ImageCache class, or the
  28525. ImageFileFormat, which provides a way to load common image files.
  28526. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  28527. */
  28528. class JUCE_API Image
  28529. {
  28530. public:
  28531. enum PixelFormat
  28532. {
  28533. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  28534. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  28535. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  28536. };
  28537. /** Creates an in-memory image with a specified size and format.
  28538. @param format the number of colour channels in the image
  28539. @param imageWidth the desired width of the image, in pixels - this value must be
  28540. greater than zero (otherwise a width of 1 will be used)
  28541. @param imageHeight the desired width of the image, in pixels - this value must be
  28542. greater than zero (otherwise a height of 1 will be used)
  28543. @param clearImage if true, the image will initially be cleared to black or transparent
  28544. black. If false, the image may contain random data, and the
  28545. user will have to deal with this
  28546. */
  28547. Image (const PixelFormat format,
  28548. const int imageWidth,
  28549. const int imageHeight,
  28550. const bool clearImage);
  28551. /** Creates a copy of another image.
  28552. @see createCopy
  28553. */
  28554. Image (const Image& other);
  28555. /** Destructor. */
  28556. virtual ~Image();
  28557. /** Returns the image's width (in pixels). */
  28558. int getWidth() const throw() { return imageWidth; }
  28559. /** Returns the image's height (in pixels). */
  28560. int getHeight() const throw() { return imageHeight; }
  28561. /** Returns the image's pixel format. */
  28562. PixelFormat getFormat() const throw() { return format; }
  28563. /** True if the image's format is ARGB. */
  28564. bool isARGB() const throw() { return format == ARGB; }
  28565. /** True if the image's format is RGB. */
  28566. bool isRGB() const throw() { return format == RGB; }
  28567. /** True if the image contains an alpha-channel. */
  28568. bool hasAlphaChannel() const throw() { return format != RGB; }
  28569. /** Clears a section of the image with a given colour.
  28570. This won't do any alpha-blending - it just sets all pixels in the image to
  28571. the given colour (which may be non-opaque if the image has an alpha channel).
  28572. */
  28573. virtual void clear (int x, int y, int w, int h,
  28574. const Colour& colourToClearTo = Colour (0x00000000));
  28575. /** Returns a new image that's a copy of this one.
  28576. A new size for the copied image can be specified, or values less than
  28577. zero can be passed-in to use the image's existing dimensions.
  28578. It's up to the caller to delete the image when no longer needed.
  28579. */
  28580. virtual Image* createCopy (int newWidth = -1,
  28581. int newHeight = -1,
  28582. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  28583. /** Returns the colour of one of the pixels in the image.
  28584. If the co-ordinates given are beyond the image's boundaries, this will
  28585. return Colours::transparentBlack.
  28586. (0, 0) is the image's top-left corner.
  28587. @see getAlphaAt, setPixelAt, blendPixelAt
  28588. */
  28589. virtual const Colour getPixelAt (const int x, const int y) const;
  28590. /** Sets the colour of one of the image's pixels.
  28591. If the co-ordinates are beyond the image's boundaries, then nothing will
  28592. happen.
  28593. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  28594. just replace the existing pixel with the given one. The colour's opacity
  28595. will be ignored if this image doesn't have an alpha-channel.
  28596. (0, 0) is the image's top-left corner.
  28597. @see blendPixelAt
  28598. */
  28599. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  28600. /** Changes the opacity of a pixel.
  28601. This only has an effect if the image has an alpha channel and if the
  28602. given co-ordinates are inside the image's boundary.
  28603. The multiplier must be in the range 0 to 1.0, and the current alpha
  28604. at the given co-ordinates will be multiplied by this value.
  28605. @see getAlphaAt, setPixelAt
  28606. */
  28607. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  28608. /** Changes the overall opacity of the image.
  28609. This will multiply the alpha value of each pixel in the image by the given
  28610. amount (limiting the resulting alpha values between 0 and 255). This allows
  28611. you to make an image more or less transparent.
  28612. If the image doesn't have an alpha channel, this won't have any effect.
  28613. */
  28614. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  28615. /** Changes all the colours to be shades of grey, based on their current luminosity.
  28616. */
  28617. virtual void desaturate();
  28618. /** Locks some of the pixels in the image so they can be read and written to.
  28619. This returns a pointer to some memory containing the pixels in the given
  28620. rectangle. It also returns values for the line and pixel stride used within
  28621. the data. The format of the pixel data is the same as that of this image.
  28622. When you've finished reading and changing the data, you must call
  28623. releasePixelDataReadWrite() to give the pixels back to the image.
  28624. For images that are stored in memory, this method may just return a direct
  28625. pointer to the image's data, but other types of image may be stored elsewhere,
  28626. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28627. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28628. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  28629. instead.
  28630. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  28631. */
  28632. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  28633. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  28634. */
  28635. virtual void releasePixelDataReadWrite (void* sourceData);
  28636. /** Locks some of the pixels in the image so they can be read.
  28637. This returns a pointer to some memory containing the pixels in the given
  28638. rectangle. It also returns values for the line and pixel stride used within
  28639. the data. The format of the pixel data is the same as that of this image.
  28640. When you've finished reading the data, you must call releasePixelDataReadOnly()
  28641. to let the image free the memory if necessary.
  28642. For images that are stored in memory, this method may just return a direct
  28643. pointer to the image's data, but other types of image may be stored elsewhere,
  28644. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  28645. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  28646. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  28647. instead.
  28648. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  28649. */
  28650. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  28651. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  28652. */
  28653. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  28654. /** Copies some pixel values to a rectangle of the image.
  28655. The format of the pixel data must match that of the image itself, and the
  28656. rectangle supplied must be within the image's bounds.
  28657. */
  28658. virtual void setPixelData (int destX, int destY, int destW, int destH,
  28659. const uint8* sourcePixelData, int sourceLineStride);
  28660. /** Copies a section of the image to somewhere else within itself.
  28661. */
  28662. virtual void moveImageSection (int destX, int destY,
  28663. int sourceX, int sourceY,
  28664. int width, int height);
  28665. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  28666. of the image.
  28667. @param result the list that will have the area added to it
  28668. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  28669. above this level will be considered opaque
  28670. */
  28671. void createSolidAreaMask (RectangleList& result,
  28672. const float alphaThreshold = 0.5f) const;
  28673. juce_UseDebuggingNewOperator
  28674. /** Creates a context suitable for drawing onto this image.
  28675. Don't call this method directly! It's used internally by the Graphics class.
  28676. */
  28677. virtual LowLevelGraphicsContext* createLowLevelContext();
  28678. protected:
  28679. const PixelFormat format;
  28680. const int imageWidth, imageHeight;
  28681. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  28682. Image (const PixelFormat format,
  28683. const int imageWidth,
  28684. const int imageHeight);
  28685. int pixelStride, lineStride;
  28686. uint8* imageData;
  28687. private:
  28688. const Image& operator= (const Image&);
  28689. };
  28690. #endif // __JUCE_IMAGE_JUCEHEADER__
  28691. /********* End of inlined file: juce_Image.h *********/
  28692. /**
  28693. A Brush that fills areas with tiled repetitions of an image.
  28694. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  28695. */
  28696. class JUCE_API ImageBrush : public Brush
  28697. {
  28698. public:
  28699. /* Creates an image brush, ready for use in Graphics::setBrush().
  28700. (x, y) is an anchor point for the top-left of the image
  28701. A reference to the image passed in will be kept, so don't delete
  28702. it within the lifetime of this object
  28703. */
  28704. ImageBrush (Image* const image,
  28705. const int anchorX,
  28706. const int anchorY,
  28707. const float opacity) throw();
  28708. /** Destructor. */
  28709. ~ImageBrush() throw();
  28710. Brush* createCopy() const throw();
  28711. void applyTransform (const AffineTransform& transform) throw();
  28712. void multiplyOpacity (const float multiple) throw();
  28713. bool isInvisible() const throw();
  28714. void paintPath (LowLevelGraphicsContext& context,
  28715. const Path& path, const AffineTransform& transform) throw();
  28716. void paintRectangle (LowLevelGraphicsContext& context,
  28717. int x, int y, int w, int h) throw();
  28718. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28719. const Image& alphaChannelImage, int imageX, int imageY,
  28720. int x, int y, int w, int h) throw();
  28721. juce_UseDebuggingNewOperator
  28722. protected:
  28723. Image* image;
  28724. int anchorX, anchorY;
  28725. float opacity;
  28726. private:
  28727. ImageBrush (const ImageBrush&);
  28728. const ImageBrush& operator= (const ImageBrush&);
  28729. void getStartXY (int& x, int& y) const throw();
  28730. };
  28731. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  28732. /********* End of inlined file: juce_ImageBrush.h *********/
  28733. #endif
  28734. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  28735. #endif
  28736. #ifndef __JUCE_COLOUR_JUCEHEADER__
  28737. #endif
  28738. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28739. #endif
  28740. #ifndef __JUCE_COLOURS_JUCEHEADER__
  28741. #endif
  28742. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  28743. #endif
  28744. #ifndef __JUCE_FONT_JUCEHEADER__
  28745. #endif
  28746. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28747. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  28748. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28749. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28750. /**
  28751. An glyph from a particular font, with a particular size, style,
  28752. typeface and position.
  28753. @see GlyphArrangement, Font
  28754. */
  28755. class JUCE_API PositionedGlyph
  28756. {
  28757. public:
  28758. /** Returns the character the glyph represents. */
  28759. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  28760. /** Checks whether the glyph is actually empty. */
  28761. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  28762. /** Returns the position of the glyph's left-hand edge. */
  28763. float getLeft() const throw() { return x; }
  28764. /** Returns the position of the glyph's right-hand edge. */
  28765. float getRight() const throw() { return x + w; }
  28766. /** Returns the y position of the glyph's baseline. */
  28767. float getBaselineY() const throw() { return y; }
  28768. /** Returns the y position of the top of the glyph. */
  28769. float getTop() const throw() { return y - fontAscent; }
  28770. /** Returns the y position of the bottom of the glyph. */
  28771. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  28772. /** Shifts the glyph's position by a relative amount. */
  28773. void moveBy (const float deltaX,
  28774. const float deltaY) throw();
  28775. /** Draws the glyph into a graphics context. */
  28776. void draw (const Graphics& g) const throw();
  28777. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  28778. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28779. /** Returns the path for this glyph.
  28780. @param path the glyph's outline will be appended to this path
  28781. */
  28782. void createPath (Path& path) const throw();
  28783. /** Checks to see if a point lies within this glyph. */
  28784. bool hitTest (float x, float y) const throw();
  28785. juce_UseDebuggingNewOperator
  28786. private:
  28787. friend class GlyphArrangement;
  28788. float x, y, w;
  28789. float fontHeight, fontAscent, fontHorizontalScale;
  28790. bool isUnderlined;
  28791. const TypefaceGlyphInfo* glyphInfo;
  28792. PositionedGlyph() throw();
  28793. };
  28794. /**
  28795. A set of glyphs, each with a position.
  28796. You can create a GlyphArrangement, text to it and then draw it onto a
  28797. graphics context. It's used internally by the text methods in the
  28798. Graphics class, but can be used directly if more control is needed.
  28799. @see Font, PositionedGlyph
  28800. */
  28801. class JUCE_API GlyphArrangement
  28802. {
  28803. public:
  28804. /** Creates an empty arrangement. */
  28805. GlyphArrangement() throw();
  28806. /** Takes a copy of another arrangement. */
  28807. GlyphArrangement (const GlyphArrangement& other) throw();
  28808. /** Copies another arrangement onto this one.
  28809. To add another arrangement without clearing this one, use addGlyphArrangement().
  28810. */
  28811. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  28812. /** Destructor. */
  28813. ~GlyphArrangement() throw();
  28814. /** Returns the total number of glyphs in the arrangement. */
  28815. int getNumGlyphs() const throw() { return numGlyphs; }
  28816. /** Returns one of the glyphs from the arrangement.
  28817. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  28818. careful not to pass an out-of-range index here, as it
  28819. doesn't do any bounds-checking.
  28820. */
  28821. PositionedGlyph& getGlyph (const int index) const throw();
  28822. /** Clears all text from the arrangement and resets it.
  28823. */
  28824. void clear() throw();
  28825. /** Appends a line of text to the arrangement.
  28826. This will add the text as a single line, where x is the left-hand edge of the
  28827. first character, and y is the position for the text's baseline.
  28828. If the text contains new-lines or carriage-returns, this will ignore them - use
  28829. addJustifiedText() to add multi-line arrangements.
  28830. */
  28831. void addLineOfText (const Font& font,
  28832. const String& text,
  28833. const float x,
  28834. const float y) throw();
  28835. /** Adds a line of text, truncating it if it's wider than a specified size.
  28836. This is the same as addLineOfText(), but if the line's width exceeds the value
  28837. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  28838. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  28839. */
  28840. void addCurtailedLineOfText (const Font& font,
  28841. const String& text,
  28842. float x,
  28843. const float y,
  28844. const float maxWidthPixels,
  28845. const bool useEllipsis) throw();
  28846. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  28847. This will add text to the arrangement, breaking it into new lines either where there
  28848. is a new-line or carriage-return character in the text, or where a line's width
  28849. exceeds the value set in maxLineWidth.
  28850. Each line that is added will be laid out using the flags set in horizontalLayout, so
  28851. the lines can be left- or right-justified, or centred horizontally in the space
  28852. between x and (x + maxLineWidth).
  28853. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  28854. lines will be placed below it, separated by a distance of font.getHeight().
  28855. */
  28856. void addJustifiedText (const Font& font,
  28857. const String& text,
  28858. float x, float y,
  28859. const float maxLineWidth,
  28860. const Justification& horizontalLayout) throw();
  28861. /** Tries to fit some text withing a given space.
  28862. This does its best to make the given text readable within the specified rectangle,
  28863. so it useful for labelling things.
  28864. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  28865. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  28866. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  28867. it's been truncated.
  28868. A Justification parameter lets you specify how the text is laid out within the rectangle,
  28869. both horizontally and vertically.
  28870. @see Graphics::drawFittedText
  28871. */
  28872. void addFittedText (const Font& font,
  28873. const String& text,
  28874. float x, float y,
  28875. float width, float height,
  28876. const Justification& layout,
  28877. int maximumLinesToUse,
  28878. const float minimumHorizontalScale = 0.7f) throw();
  28879. /** Appends another glyph arrangement to this one. */
  28880. void addGlyphArrangement (const GlyphArrangement& other) throw();
  28881. /** Draws this glyph arrangement to a graphics context.
  28882. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  28883. method, which renders the glyphs as filled vectors.
  28884. */
  28885. void draw (const Graphics& g) const throw();
  28886. /** Draws this glyph arrangement to a graphics context.
  28887. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  28888. method for non-transformed arrangements.
  28889. */
  28890. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  28891. /** Converts the set of glyphs into a path.
  28892. @param path the glyphs' outlines will be appended to this path
  28893. */
  28894. void createPath (Path& path) const throw();
  28895. /** Looks for a glyph that contains the given co-ordinate.
  28896. @returns the index of the glyph, or -1 if none were found.
  28897. */
  28898. int findGlyphIndexAt (float x, float y) const throw();
  28899. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  28900. @param startIndex the first glyph to test
  28901. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  28902. startIndex will be included
  28903. @param left on return, the leftmost co-ordinate of the rectangle
  28904. @param top on return, the top co-ordinate of the rectangle
  28905. @param right on return, the rightmost co-ordinate of the rectangle
  28906. @param bottom on return, the bottom co-ordinate of the rectangle
  28907. @param includeWhitespace if true, the extent of any whitespace characters will also
  28908. be taken into account
  28909. */
  28910. void getBoundingBox (int startIndex,
  28911. int numGlyphs,
  28912. float& left,
  28913. float& top,
  28914. float& right,
  28915. float& bottom,
  28916. const bool includeWhitespace) const throw();
  28917. /** Shifts a set of glyphs by a given amount.
  28918. @param startIndex the first glyph to transform
  28919. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  28920. startIndex will be used
  28921. @param deltaX the amount to add to their x-positions
  28922. @param deltaY the amount to add to their y-positions
  28923. */
  28924. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  28925. const float deltaX,
  28926. const float deltaY) throw();
  28927. /** Removes a set of glyphs from the arrangement.
  28928. @param startIndex the first glyph to remove
  28929. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  28930. startIndex will be deleted
  28931. */
  28932. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  28933. /** Expands or compresses a set of glyphs horizontally.
  28934. @param startIndex the first glyph to transform
  28935. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  28936. startIndex will be used
  28937. @param horizontalScaleFactor how much to scale their horizontal width by
  28938. */
  28939. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  28940. const float horizontalScaleFactor) throw();
  28941. /** Justifies a set of glyphs within a given space.
  28942. This moves the glyphs as a block so that the whole thing is located within the
  28943. given rectangle with the specified layout.
  28944. If the Justification::horizontallyJustified flag is specified, each line will
  28945. be stretched out to fill the specified width.
  28946. */
  28947. void justifyGlyphs (const int startIndex, const int numGlyphs,
  28948. const float x,
  28949. const float y,
  28950. const float width,
  28951. const float height,
  28952. const Justification& justification) throw();
  28953. juce_UseDebuggingNewOperator
  28954. private:
  28955. int numGlyphs, numAllocated;
  28956. PositionedGlyph* glyphs;
  28957. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  28958. void removeLast() throw();
  28959. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  28960. void incGlyphRefCount (const int index) const throw();
  28961. void decGlyphRefCount (const int index) const throw();
  28962. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  28963. };
  28964. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  28965. /********* End of inlined file: juce_GlyphArrangement.h *********/
  28966. #endif
  28967. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28968. /********* Start of inlined file: juce_TextLayout.h *********/
  28969. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  28970. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  28971. class Graphics;
  28972. /**
  28973. A laid-out arrangement of text.
  28974. You can add text in different fonts to a TextLayout object, then call its
  28975. layout() method to word-wrap it into lines. The layout can then be drawn
  28976. using a graphics context.
  28977. It's handy if you've got a message to display, because you can format it,
  28978. measure the extent of the layout, and then create a suitably-sized window
  28979. to show it in.
  28980. @see Font, Graphics::drawFittedText, GlyphArrangement
  28981. */
  28982. class JUCE_API TextLayout
  28983. {
  28984. public:
  28985. /** Creates an empty text layout.
  28986. Text can then be appended using the appendText() method.
  28987. */
  28988. TextLayout() throw();
  28989. /** Creates a copy of another layout object. */
  28990. TextLayout (const TextLayout& other) throw();
  28991. /** Creates a text layout from an initial string and font. */
  28992. TextLayout (const String& text, const Font& font) throw();
  28993. /** Destructor. */
  28994. ~TextLayout() throw();
  28995. /** Copies another layout onto this one. */
  28996. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  28997. /** Clears the layout, removing all its text. */
  28998. void clear() throw();
  28999. /** Adds a string to the end of the arrangement.
  29000. The string will be broken onto new lines wherever it contains
  29001. carriage-returns or linefeeds. After adding it, you can call layout()
  29002. to wrap long lines into a paragraph and justify it.
  29003. */
  29004. void appendText (const String& textToAppend,
  29005. const Font& fontToUse) throw();
  29006. /** Replaces all the text with a new string.
  29007. This is equivalent to calling clear() followed by appendText().
  29008. */
  29009. void setText (const String& newText,
  29010. const Font& fontToUse) throw();
  29011. /** Breaks the text up to form a paragraph with the given width.
  29012. @param maximumWidth any text wider than this will be split
  29013. across multiple lines
  29014. @param justification how the lines are to be laid-out horizontally
  29015. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  29016. width that keeps all the lines of text at a
  29017. similar length - this is good when you're displaying
  29018. a short message and don't want it to get split
  29019. onto two lines with only a couple of words on
  29020. the second line, which looks untidy.
  29021. */
  29022. void layout (int maximumWidth,
  29023. const Justification& justification,
  29024. const bool attemptToBalanceLineLengths) throw();
  29025. /** Returns the overall width of the entire text layout. */
  29026. int getWidth() const throw();
  29027. /** Returns the overall height of the entire text layout. */
  29028. int getHeight() const throw();
  29029. /** Returns the total number of lines of text. */
  29030. int getNumLines() const throw() { return totalLines; }
  29031. /** Returns the width of a particular line of text.
  29032. @param lineNumber the line, from 0 to (getNumLines() - 1)
  29033. */
  29034. int getLineWidth (const int lineNumber) const throw();
  29035. /** Renders the text at a specified position using a graphics context.
  29036. */
  29037. void draw (Graphics& g,
  29038. const int topLeftX,
  29039. const int topLeftY) const throw();
  29040. /** Renders the text within a specified rectangle using a graphics context.
  29041. The justification flags dictate how the block of text should be positioned
  29042. within the rectangle.
  29043. */
  29044. void drawWithin (Graphics& g,
  29045. int x, int y, int w, int h,
  29046. const Justification& layoutFlags) const throw();
  29047. juce_UseDebuggingNewOperator
  29048. private:
  29049. VoidArray tokens;
  29050. int totalLines;
  29051. };
  29052. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  29053. /********* End of inlined file: juce_TextLayout.h *********/
  29054. #endif
  29055. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  29056. #endif
  29057. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29058. /********* Start of inlined file: juce_EdgeTable.h *********/
  29059. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29060. #define __JUCE_EDGETABLE_JUCEHEADER__
  29061. class Path;
  29062. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  29063. /**
  29064. A table of horizontal scan-line segments - used for rasterising Paths.
  29065. @see Path, Graphics
  29066. */
  29067. class JUCE_API EdgeTable
  29068. {
  29069. public:
  29070. /** Indicates the quality at which the edge table should be generated.
  29071. Higher values will have better quality anti-aliasing, but will take
  29072. longer to generate the edge table and to render it.
  29073. */
  29074. enum OversamplingLevel
  29075. {
  29076. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  29077. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  29078. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  29079. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  29080. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  29081. normal user-interface use. */
  29082. };
  29083. /** Creates an empty edge table ready to have paths added.
  29084. A table is created with a fixed vertical size, and only sections of paths
  29085. which lie within their range will be added to the table.
  29086. @param topY the lowest y co-ordinate that the table can contain
  29087. @param height the number of horizontal lines it can contain
  29088. @param verticalOversampling the amount of oversampling used for anti-aliasing
  29089. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  29090. worth changing this except for very special purposes
  29091. */
  29092. EdgeTable (const int topY,
  29093. const int height,
  29094. const OversamplingLevel verticalOversampling = Oversampling_4times,
  29095. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  29096. /** Creates a copy of another edge table. */
  29097. EdgeTable (const EdgeTable& other) throw();
  29098. /** Copies from another edge table. */
  29099. const EdgeTable& operator= (const EdgeTable& other) throw();
  29100. /** Destructor. */
  29101. ~EdgeTable() throw();
  29102. /** Adds edges to the table for a path.
  29103. This will add horizontal lines to the edge table for any parts of the path
  29104. which lie within the vertical bounds for which this table was created.
  29105. @param path the path to add
  29106. @param transform an optional transform to apply to the path while it's
  29107. being added
  29108. */
  29109. void addPath (const Path& path,
  29110. const AffineTransform& transform) throw();
  29111. /** Reduces the amount of space the table has allocated.
  29112. This will shrink the table down to use as little memory as possible - useful for
  29113. read-only tables that get stored and re-used for rendering.
  29114. */
  29115. void optimiseTable() throw();
  29116. /** Iterates the lines in the table, for rendering.
  29117. This function will iterate each line in the table, and call a user-defined class
  29118. to render each pixel or continuous line of pixels that the table contains.
  29119. @param iterationCallback this templated class must contain the following methods:
  29120. @code
  29121. inline void setEdgeTableYPos (int y);
  29122. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  29123. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  29124. @endcode
  29125. (these don't necessarily have to be 'const', but it might help it go faster)
  29126. @param clipLeft the left-hand edge of the rectangle which should be iterated
  29127. @param clipTop the top edge of the rectangle which should be iterated
  29128. @param clipRight the right-hand edge of the rectangle which should be iterated
  29129. @param clipBottom the bottom edge of the rectangle which should be iterated
  29130. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  29131. */
  29132. template <class EdgeTableIterationCallback>
  29133. void iterate (EdgeTableIterationCallback& iterationCallback,
  29134. const int clipLeft,
  29135. int clipTop,
  29136. const int clipRight,
  29137. int clipBottom,
  29138. const int subPixelXOffset) const
  29139. {
  29140. if (clipTop < top)
  29141. clipTop = top;
  29142. if (clipBottom > top + height)
  29143. clipBottom = top + height;
  29144. const int* singleLine = table + lineStrideElements
  29145. * ((clipTop - top) << (int) oversampling);
  29146. int mergedLineAllocation = 128;
  29147. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  29148. int* mergedLine = (int*) temp.getData();
  29149. const int timesOverSampling = 1 << (int) oversampling;
  29150. for (int y = clipTop; y < clipBottom; ++y)
  29151. {
  29152. int numMergedPoints = 0;
  29153. // sort all the oversampled lines into a single merged line ready to draw..
  29154. for (int over = timesOverSampling; --over >= 0;)
  29155. {
  29156. const int* l = singleLine;
  29157. singleLine += lineStrideElements;
  29158. int num = *l;
  29159. jassert (num >= 0);
  29160. if (num > 0)
  29161. {
  29162. if (numMergedPoints + num >= mergedLineAllocation)
  29163. {
  29164. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  29165. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  29166. mergedLine = (int*) temp.getData();
  29167. }
  29168. while (--num >= 0)
  29169. {
  29170. const int x = *++l;
  29171. const int winding = *++l;
  29172. int n = numMergedPoints << 1;
  29173. while (n > 0)
  29174. {
  29175. const int cx = mergedLine [n - 2];
  29176. if (cx <= x)
  29177. break;
  29178. mergedLine [n] = cx;
  29179. --n;
  29180. mergedLine [n + 2] = mergedLine [n];
  29181. --n;
  29182. }
  29183. mergedLine [n] = x;
  29184. mergedLine [n + 1] = winding;
  29185. ++numMergedPoints;
  29186. }
  29187. }
  29188. }
  29189. if (--numMergedPoints > 0)
  29190. {
  29191. const int* line = mergedLine;
  29192. int x = subPixelXOffset + *line;
  29193. int level = *++line;
  29194. int levelAccumulator = 0;
  29195. iterationCallback.setEdgeTableYPos (y);
  29196. while (--numMergedPoints >= 0)
  29197. {
  29198. const int endX = subPixelXOffset + *++line;
  29199. jassert (endX >= x);
  29200. const int absLevel = abs (level);
  29201. int endOfRun = (endX >> 8);
  29202. if (endOfRun == (x >> 8))
  29203. {
  29204. // small segment within the same pixel, so just save it for the next
  29205. // time round..
  29206. levelAccumulator += (endX - x) * absLevel;
  29207. }
  29208. else
  29209. {
  29210. // plot the fist pixel of this segment, including any accumulated
  29211. // levels from smaller segments that haven't been drawn yet
  29212. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  29213. levelAccumulator >>= 8;
  29214. if (levelAccumulator > 0xff)
  29215. levelAccumulator = 0xff;
  29216. x >>= 8;
  29217. if (x >= clipRight)
  29218. {
  29219. levelAccumulator = 0;
  29220. break;
  29221. }
  29222. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  29223. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29224. if (++x >= clipRight)
  29225. {
  29226. levelAccumulator = 0;
  29227. break;
  29228. }
  29229. // if there's a segment of solid pixels, do it all in one go..
  29230. if (absLevel > 0 && endOfRun > x)
  29231. {
  29232. if (x < clipLeft)
  29233. x = clipLeft;
  29234. if (endOfRun > clipRight)
  29235. endOfRun = clipRight;
  29236. const int numPix = endOfRun - x;
  29237. if (numPix > 0)
  29238. iterationCallback.handleEdgeTableLine (x, numPix,
  29239. jmin (absLevel, 0xff));
  29240. }
  29241. // save the bit at the end to be drawn next time round the loop.
  29242. levelAccumulator = (endX & 0xff) * absLevel;
  29243. }
  29244. level += *++line;
  29245. x = endX;
  29246. }
  29247. if (levelAccumulator > 0)
  29248. {
  29249. levelAccumulator >>= 8;
  29250. if (levelAccumulator > 0xff)
  29251. levelAccumulator = 0xff;
  29252. x >>= 8;
  29253. if (x >= clipLeft && x < clipRight)
  29254. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29255. }
  29256. }
  29257. }
  29258. }
  29259. juce_UseDebuggingNewOperator
  29260. private:
  29261. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  29262. int* table;
  29263. int top, height, maxEdgesPerLine, lineStrideElements;
  29264. OversamplingLevel oversampling;
  29265. // this will assume that the y co-ord is within bounds, and will avoid checking
  29266. // this for speed.
  29267. void addEdgePoint (const int x, const int y, const int winding) throw();
  29268. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  29269. };
  29270. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  29271. /********* End of inlined file: juce_EdgeTable.h *********/
  29272. #endif
  29273. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  29274. #endif
  29275. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29276. #endif
  29277. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29278. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29279. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29280. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29281. /**
  29282. Interface class for graphics context objects, used internally by the Graphics class.
  29283. Users are not supposed to create instances of this class directly - do your drawing
  29284. via the Graphics object instead.
  29285. It's a base class for different types of graphics context, that may perform software-based
  29286. or OS-accelerated rendering.
  29287. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  29288. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  29289. context.
  29290. */
  29291. class JUCE_API LowLevelGraphicsContext
  29292. {
  29293. protected:
  29294. LowLevelGraphicsContext();
  29295. public:
  29296. virtual ~LowLevelGraphicsContext();
  29297. /** Returns true if this device is vector-based, e.g. a printer. */
  29298. virtual bool isVectorDevice() const = 0;
  29299. /** Moves the origin to a new position.
  29300. The co-ords are relative to the current origin, and indicate the new position
  29301. of (0, 0).
  29302. */
  29303. virtual void setOrigin (int x, int y) = 0;
  29304. /** Cliping co-ords are relative to the origin. */
  29305. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  29306. /** Cliping co-ords are relative to the origin. */
  29307. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  29308. /** Cliping co-ords are relative to the origin. */
  29309. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  29310. virtual void saveState() = 0;
  29311. virtual void restoreState() = 0;
  29312. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  29313. virtual const Rectangle getClipBounds() const = 0;
  29314. virtual bool isClipEmpty() const = 0;
  29315. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  29316. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  29317. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  29318. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  29319. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29320. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  29321. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  29322. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  29323. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29324. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  29325. virtual void blendImage (const Image& sourceImage,
  29326. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29327. float alpha) = 0;
  29328. virtual void blendImageRescaling (const Image& sourceImage,
  29329. int destX, int destY, int destW, int destH,
  29330. int sourceX, int sourceY, int sourceW, int sourceH,
  29331. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29332. virtual void blendImageWarping (const Image& sourceImage,
  29333. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29334. const AffineTransform& transform,
  29335. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29336. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  29337. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  29338. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29339. };
  29340. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29341. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29342. #endif
  29343. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29344. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29345. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29346. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29347. /**
  29348. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29349. into a PostScript document.
  29350. */
  29351. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29352. {
  29353. public:
  29354. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29355. const String& documentTitle,
  29356. const int totalWidth,
  29357. const int totalHeight);
  29358. ~LowLevelGraphicsPostScriptRenderer();
  29359. bool isVectorDevice() const;
  29360. void setOrigin (int x, int y);
  29361. bool reduceClipRegion (int x, int y, int w, int h);
  29362. bool reduceClipRegion (const RectangleList& clipRegion);
  29363. void excludeClipRegion (int x, int y, int w, int h);
  29364. void saveState();
  29365. void restoreState();
  29366. bool clipRegionIntersects (int x, int y, int w, int h);
  29367. const Rectangle getClipBounds() const;
  29368. bool isClipEmpty() const;
  29369. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29370. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29371. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29372. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29373. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29374. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29375. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29376. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29377. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29378. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29379. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29380. int sourceX, int sourceY, float alpha);
  29381. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29382. int sourceX, int sourceY, int sourceW, int sourceH,
  29383. float alpha, const Graphics::ResamplingQuality quality);
  29384. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29385. const AffineTransform& transform,
  29386. float alpha, const Graphics::ResamplingQuality quality);
  29387. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29388. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29389. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29390. juce_UseDebuggingNewOperator
  29391. protected:
  29392. OutputStream& out;
  29393. RectangleList* clip;
  29394. int totalWidth, totalHeight, xOffset, yOffset;
  29395. bool needToClip;
  29396. Colour lastColour;
  29397. struct SavedState
  29398. {
  29399. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29400. ~SavedState();
  29401. RectangleList* clip;
  29402. const int xOffset, yOffset;
  29403. private:
  29404. SavedState (const SavedState&);
  29405. const SavedState& operator= (const SavedState&);
  29406. };
  29407. OwnedArray <SavedState> stateStack;
  29408. void writeClip();
  29409. void writeColour (const Colour& colour);
  29410. void writePath (const Path& path) const;
  29411. void writeXY (const float x, const float y) const;
  29412. void writeTransform (const AffineTransform& trans) const;
  29413. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29414. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29415. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29416. };
  29417. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29418. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29419. #endif
  29420. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29421. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29422. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29423. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29424. /**
  29425. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29426. its rendering in memory.
  29427. User code is not supposed to create instances of this class directly - do all your
  29428. rendering via the Graphics class instead.
  29429. */
  29430. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29431. {
  29432. public:
  29433. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29434. ~LowLevelGraphicsSoftwareRenderer();
  29435. bool isVectorDevice() const;
  29436. void setOrigin (int x, int y);
  29437. bool reduceClipRegion (int x, int y, int w, int h);
  29438. bool reduceClipRegion (const RectangleList& clipRegion);
  29439. void excludeClipRegion (int x, int y, int w, int h);
  29440. void saveState();
  29441. void restoreState();
  29442. bool clipRegionIntersects (int x, int y, int w, int h);
  29443. const Rectangle getClipBounds() const;
  29444. bool isClipEmpty() const;
  29445. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29446. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29447. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29448. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29449. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29450. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29451. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29452. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29453. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29454. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29455. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29456. int sourceX, int sourceY, float alpha);
  29457. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29458. int sourceX, int sourceY, int sourceW, int sourceH,
  29459. float alpha, const Graphics::ResamplingQuality quality);
  29460. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29461. const AffineTransform& transform,
  29462. float alpha, const Graphics::ResamplingQuality quality);
  29463. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29464. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29465. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29466. RectangleList* getRawClipRegion() throw() { return clip; }
  29467. juce_UseDebuggingNewOperator
  29468. protected:
  29469. Image& image;
  29470. RectangleList* clip;
  29471. int xOffset, yOffset;
  29472. struct SavedState
  29473. {
  29474. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29475. ~SavedState();
  29476. RectangleList* clip;
  29477. const int xOffset, yOffset;
  29478. private:
  29479. SavedState (const SavedState&);
  29480. const SavedState& operator= (const SavedState&);
  29481. };
  29482. OwnedArray <SavedState> stateStack;
  29483. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29484. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29485. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29486. const Path& path, const AffineTransform& transform,
  29487. int& x, int& y, int& w, int& h) const;
  29488. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29489. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29490. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29491. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29492. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29493. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29494. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29495. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29496. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29497. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29498. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29499. float alpha);
  29500. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29501. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29502. const AffineTransform& transform,
  29503. float alpha, const Graphics::ResamplingQuality quality);
  29504. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29505. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29506. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29507. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29508. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29509. };
  29510. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29511. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29512. #endif
  29513. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29514. #endif
  29515. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  29516. #endif
  29517. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29518. #endif
  29519. #ifndef __JUCE_LINE_JUCEHEADER__
  29520. #endif
  29521. #ifndef __JUCE_PATH_JUCEHEADER__
  29522. #endif
  29523. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29524. /********* Start of inlined file: juce_PathIterator.h *********/
  29525. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29526. #define __JUCE_PATHITERATOR_JUCEHEADER__
  29527. /**
  29528. Flattens a Path object into a series of straight-line sections.
  29529. Use one of these to iterate through a Path object, and it will convert
  29530. all the curves into line sections so it's easy to render or perform
  29531. geometric operations on.
  29532. @see Path
  29533. */
  29534. class JUCE_API PathFlatteningIterator
  29535. {
  29536. public:
  29537. /** Creates a PathFlatteningIterator.
  29538. After creation, use the next() method to initialise the fields in the
  29539. object with the first line's position.
  29540. @param path the path to iterate along
  29541. @param transform a transform to apply to each point in the path being iterated
  29542. @param tolerence the amount by which the curves are allowed to deviate from the
  29543. lines into which they are being broken down - a higher tolerence
  29544. is a bit faster, but less smooth.
  29545. */
  29546. PathFlatteningIterator (const Path& path,
  29547. const AffineTransform& transform = AffineTransform::identity,
  29548. float tolerence = 9.0f) throw();
  29549. /** Destructor. */
  29550. ~PathFlatteningIterator() throw();
  29551. /** Fetches the next line segment from the path.
  29552. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  29553. so that they describe the new line segment.
  29554. @returns false when there are no more lines to fetch.
  29555. */
  29556. bool next() throw();
  29557. /** The x position of the start of the current line segment. */
  29558. float x1;
  29559. /** The y position of the start of the current line segment. */
  29560. float y1;
  29561. /** The x position of the end of the current line segment. */
  29562. float x2;
  29563. /** The y position of the end of the current line segment. */
  29564. float y2;
  29565. /** Indicates whether the current line segment is closing a sub-path.
  29566. If the current line is the one that connects the end of a sub-path
  29567. back to the start again, this will be true.
  29568. */
  29569. bool closesSubPath;
  29570. /** The index of the current line within the current sub-path.
  29571. E.g. you can use this to see whether the line is the first one in the
  29572. subpath by seeing if it's 0.
  29573. */
  29574. int subPathIndex;
  29575. /** Returns true if the current segment is the last in the current sub-path. */
  29576. bool isLastInSubpath() const throw() { return stackPos == stackBase
  29577. && (index >= path.numElements
  29578. || points [index] == Path::moveMarker); }
  29579. juce_UseDebuggingNewOperator
  29580. private:
  29581. const Path& path;
  29582. const AffineTransform transform;
  29583. float* points;
  29584. float tolerence, subPathCloseX, subPathCloseY;
  29585. bool isIdentityTransform;
  29586. float* stackBase;
  29587. float* stackPos;
  29588. int index, stackSize;
  29589. PathFlatteningIterator (const PathFlatteningIterator&);
  29590. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  29591. };
  29592. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  29593. /********* End of inlined file: juce_PathIterator.h *********/
  29594. #endif
  29595. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  29596. #endif
  29597. #ifndef __JUCE_POINT_JUCEHEADER__
  29598. #endif
  29599. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29600. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  29601. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29602. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29603. /**
  29604. A rectangle whose co-ordinates can be defined in terms of absolute or
  29605. proportional distances.
  29606. Designed mainly for storing component positions, this gives you a lot of
  29607. control over how each co-ordinate is stored, either as an absolute position,
  29608. or as a proportion of the size of a parent rectangle.
  29609. It also allows you to define the anchor points by which the rectangle is
  29610. positioned, so for example you could specify that the top right of the
  29611. rectangle should be an absolute distance from its parent's bottom-right corner.
  29612. This object can be stored as a string, which takes the form "x y w h", including
  29613. symbols like '%' and letters to indicate the anchor point. See its toString()
  29614. method for more info.
  29615. Example usage:
  29616. @code
  29617. class MyComponent
  29618. {
  29619. void resized()
  29620. {
  29621. // this will set the child component's x to be 20% of our width, its y
  29622. // to be 30, its width to be 150, and its height to be 50% of our
  29623. // height..
  29624. const PositionedRectangle pos1 ("20% 30 150 50%");
  29625. pos1.applyToComponent (*myChildComponent1);
  29626. // this will inset the child component with a gap of 10 pixels
  29627. // around each of its edges..
  29628. const PositionedRectangle pos2 ("10 10 20M 20M");
  29629. pos2.applyToComponent (*myChildComponent2);
  29630. }
  29631. };
  29632. @endcode
  29633. */
  29634. class JUCE_API PositionedRectangle
  29635. {
  29636. public:
  29637. /** Creates an empty rectangle with all co-ordinates set to zero.
  29638. The default anchor point is top-left; the default
  29639. */
  29640. PositionedRectangle() throw();
  29641. /** Initialises a PositionedRectangle from a saved string version.
  29642. The string must be in the format generated by toString().
  29643. */
  29644. PositionedRectangle (const String& stringVersion) throw();
  29645. /** Creates a copy of another PositionedRectangle. */
  29646. PositionedRectangle (const PositionedRectangle& other) throw();
  29647. /** Copies another PositionedRectangle. */
  29648. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  29649. /** Destructor. */
  29650. ~PositionedRectangle() throw();
  29651. /** Returns a string version of this position, from which it can later be
  29652. re-generated.
  29653. The format is four co-ordinates, "x y w h".
  29654. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  29655. - If a co-ordinate is proportional to its parent's width or height, it is stored
  29656. as a percentage, e.g. "80%".
  29657. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  29658. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  29659. the parent's right-hand edge.
  29660. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  29661. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  29662. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  29663. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  29664. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  29665. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  29666. has "c" appended to it. So "-50Rc" would mean that this component's
  29667. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  29668. this component's centre should be placed 40% across the parent's width.
  29669. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  29670. the number has "M" appended to it.
  29671. To reload a stored string, use the constructor that takes a string parameter.
  29672. */
  29673. const String toString() const throw();
  29674. /** Calculates the absolute position, given the size of the space that
  29675. it should go in.
  29676. This will work out any proportional distances and sizes relative to the
  29677. target rectangle, and will return the absolute position.
  29678. @see applyToComponent
  29679. */
  29680. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  29681. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  29682. */
  29683. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  29684. double& x,
  29685. double& y,
  29686. double& width,
  29687. double& height) const throw();
  29688. /** This sets the bounds of the given component to this position.
  29689. This is equivalent to writing:
  29690. @code
  29691. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  29692. @endcode
  29693. @see getRectangle, updateFromComponent
  29694. */
  29695. void applyToComponent (Component& comp) const throw();
  29696. /** Updates this object's co-ordinates to match the given rectangle.
  29697. This will set all co-ordinates based on the given rectangle, re-calculating
  29698. any proportional distances, and using the current anchor points.
  29699. So for example if the x co-ordinate mode is currently proportional, this will
  29700. re-calculate x based on the rectangle's relative position within the target
  29701. rectangle's width.
  29702. If the target rectangle's width or height are zero then it may not be possible
  29703. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  29704. will not be changed.
  29705. */
  29706. void updateFrom (const Rectangle& newPosition,
  29707. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29708. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  29709. */
  29710. void updateFromDouble (const double x, const double y,
  29711. const double width, const double height,
  29712. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29713. /** Updates this object's co-ordinates to match the bounds of this component.
  29714. This is equivalent to calling updateFrom() with the component's bounds and
  29715. it parent size.
  29716. If the component doesn't currently have a parent, then proportional co-ordinates
  29717. might not be updated because it would need to know the parent's size to do the
  29718. maths for this.
  29719. */
  29720. void updateFromComponent (const Component& comp) throw();
  29721. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  29722. enum AnchorPoint
  29723. {
  29724. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  29725. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  29726. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  29727. };
  29728. /** Specifies how an x or y co-ordinate should be interpreted. */
  29729. enum PositionMode
  29730. {
  29731. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  29732. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  29733. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  29734. proportionOfParentSize = 1 << 6 /**< The x or y co-ordinate specifies a proportion of the parent's width or height, measured from the parent's top or left. */
  29735. };
  29736. /** Specifies how the width or height should be interpreted. */
  29737. enum SizeMode
  29738. {
  29739. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  29740. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  29741. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  29742. };
  29743. /** Sets all options for all co-ordinates.
  29744. This requires a reference rectangle to be specified, because if you're changing any
  29745. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  29746. the co-ordinates, and will need to know the parent size so it can calculate this.
  29747. */
  29748. void setModes (const AnchorPoint xAnchorMode,
  29749. const PositionMode xPositionMode,
  29750. const AnchorPoint yAnchorMode,
  29751. const PositionMode yPositionMode,
  29752. const SizeMode widthMode,
  29753. const SizeMode heightMode,
  29754. const Rectangle& targetSpaceToBeRelativeTo) throw();
  29755. /** Returns the anchoring mode for the x co-ordinate.
  29756. To change any of the modes, use setModes().
  29757. */
  29758. AnchorPoint getAnchorPointX() const throw();
  29759. /** Returns the positioning mode for the x co-ordinate.
  29760. To change any of the modes, use setModes().
  29761. */
  29762. PositionMode getPositionModeX() const throw();
  29763. /** Returns the raw x co-ordinate.
  29764. If the x position mode is absolute, then this will be the absolute value. If it's
  29765. proportional, then this will be a fractional proportion, where 1.0 means the full
  29766. width of the parent space.
  29767. */
  29768. double getX() const throw() { return x; }
  29769. /** Sets the raw value of the x co-ordinate.
  29770. See getX() for the meaning of this value.
  29771. */
  29772. void setX (const double newX) throw() { x = newX; }
  29773. /** Returns the anchoring mode for the y co-ordinate.
  29774. To change any of the modes, use setModes().
  29775. */
  29776. AnchorPoint getAnchorPointY() const throw();
  29777. /** Returns the positioning mode for the y co-ordinate.
  29778. To change any of the modes, use setModes().
  29779. */
  29780. PositionMode getPositionModeY() const throw();
  29781. /** Returns the raw y co-ordinate.
  29782. If the y position mode is absolute, then this will be the absolute value. If it's
  29783. proportional, then this will be a fractional proportion, where 1.0 means the full
  29784. height of the parent space.
  29785. */
  29786. double getY() const throw() { return y; }
  29787. /** Sets the raw value of the y co-ordinate.
  29788. See getY() for the meaning of this value.
  29789. */
  29790. void setY (const double newY) throw() { y = newY; }
  29791. /** Returns the mode used to calculate the width.
  29792. To change any of the modes, use setModes().
  29793. */
  29794. SizeMode getWidthMode() const throw();
  29795. /** Returns the raw width value.
  29796. If the width mode is absolute, then this will be the absolute value. If the mode is
  29797. proportional, then this will be a fractional proportion, where 1.0 means the full
  29798. width of the parent space.
  29799. */
  29800. double getWidth() const throw() { return w; }
  29801. /** Sets the raw width value.
  29802. See getWidth() for the details about what this value means.
  29803. */
  29804. void setWidth (const double newWidth) throw() { w = newWidth; }
  29805. /** Returns the mode used to calculate the height.
  29806. To change any of the modes, use setModes().
  29807. */
  29808. SizeMode getHeightMode() const throw();
  29809. /** Returns the raw height value.
  29810. If the height mode is absolute, then this will be the absolute value. If the mode is
  29811. proportional, then this will be a fractional proportion, where 1.0 means the full
  29812. height of the parent space.
  29813. */
  29814. double getHeight() const throw() { return h; }
  29815. /** Sets the raw height value.
  29816. See getHeight() for the details about what this value means.
  29817. */
  29818. void setHeight (const double newHeight) throw() { h = newHeight; }
  29819. /** If the size and position are constance, and wouldn't be affected by changes
  29820. in the parent's size, then this will return true.
  29821. */
  29822. bool isPositionAbsolute() const throw();
  29823. /** Compares two objects. */
  29824. const bool operator== (const PositionedRectangle& other) const throw();
  29825. /** Compares two objects. */
  29826. const bool operator!= (const PositionedRectangle& other) const throw();
  29827. juce_UseDebuggingNewOperator
  29828. private:
  29829. double x, y, w, h;
  29830. uint8 xMode, yMode, wMode, hMode;
  29831. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  29832. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  29833. void decodePosString (const String& s, uint8& mode, double& value) throw();
  29834. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  29835. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  29836. const uint8 xMode, const uint8 wMode,
  29837. const int parentPos, const int parentSize) const throw();
  29838. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  29839. const uint8 xMode, const uint8 wMode,
  29840. const int parentPos, const int parentSize) const throw();
  29841. };
  29842. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  29843. /********* End of inlined file: juce_PositionedRectangle.h *********/
  29844. #endif
  29845. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  29846. #endif
  29847. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  29848. #endif
  29849. #ifndef __JUCE_IMAGE_JUCEHEADER__
  29850. #endif
  29851. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29852. /********* Start of inlined file: juce_ImageCache.h *********/
  29853. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  29854. #define __JUCE_IMAGECACHE_JUCEHEADER__
  29855. /**
  29856. A global cache of images that have been loaded from files or memory.
  29857. If you're loading an image and may need to use the image in more than one
  29858. place, this is used to allow the same image to be shared rather than loading
  29859. multiple copies into memory.
  29860. Another advantage is that after images are released, they will be kept in
  29861. memory for a few seconds before it is actually deleted, so if you're repeatedly
  29862. loading/deleting the same image, it'll reduce the chances of having to reload it
  29863. each time.
  29864. @see Image, ImageFileFormat
  29865. */
  29866. class JUCE_API ImageCache : private DeletedAtShutdown,
  29867. private Timer
  29868. {
  29869. public:
  29870. /** Loads an image from a file, (or just returns the image if it's already cached).
  29871. If the cache already contains an image that was loaded from this file,
  29872. that image will be returned. Otherwise, this method will try to load the
  29873. file, add it to the cache, and return it.
  29874. It's very important not to delete the image that is returned - instead use
  29875. the ImageCache::release() method.
  29876. Also, remember that the image returned is shared, so drawing into it might
  29877. affect other things that are using it!
  29878. @param file the file to try to load
  29879. @returns the image, or null if it there was an error loading it
  29880. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29881. */
  29882. static Image* getFromFile (const File& file);
  29883. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  29884. If the cache already contains an image that was loaded from this block of memory,
  29885. that image will be returned. Otherwise, this method will try to load the
  29886. file, add it to the cache, and return it.
  29887. It's very important not to delete the image that is returned - instead use
  29888. the ImageCache::release() method.
  29889. Also, remember that the image returned is shared, so drawing into it might
  29890. affect other things that are using it!
  29891. @param imageData the block of memory containing the image data
  29892. @param dataSize the data size in bytes
  29893. @returns the image, or null if it there was an error loading it
  29894. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  29895. */
  29896. static Image* getFromMemory (const void* imageData,
  29897. const int dataSize);
  29898. /** Releases an image that was previously created by the ImageCache.
  29899. If an image has been returned by the getFromFile() or getFromMemory() methods,
  29900. it mustn't be deleted directly, but should be released with this method
  29901. instead.
  29902. @see getFromFile, getFromMemory
  29903. */
  29904. static void release (Image* const imageToRelease);
  29905. /** Checks whether an image is in the cache or not.
  29906. @returns true if the image is currently in the cache
  29907. */
  29908. static bool isImageInCache (Image* const imageToLookFor);
  29909. /** Increments the reference-count for a cached image.
  29910. If the image isn't in the cache, this method won't do anything.
  29911. */
  29912. static void incReferenceCount (Image* const image);
  29913. /** Checks the cache for an image with a particular hashcode.
  29914. If there's an image in the cache with this hashcode, it will be returned,
  29915. otherwise it will return zero.
  29916. If an image is returned, it must be released with the release() method
  29917. when no longer needed, to maintain the correct reference counts.
  29918. @param hashCode the hash code that would have been associated with the
  29919. image by addImageToCache()
  29920. @see addImageToCache
  29921. */
  29922. static Image* getFromHashCode (const int64 hashCode);
  29923. /** Adds an image to the cache with a user-defined hash-code.
  29924. After calling this, responsibilty for deleting the image will be taken
  29925. by the ImageCache.
  29926. The image will be initially be given a reference count of 1, so call
  29927. the release() method to delete it.
  29928. @param image the image to add
  29929. @param hashCode the hash-code to associate with it
  29930. @see getFromHashCode
  29931. */
  29932. static void addImageToCache (Image* const image,
  29933. const int64 hashCode);
  29934. /** Changes the amount of time before an unused image will be removed from the cache.
  29935. By default this is about 5 seconds.
  29936. */
  29937. static void setCacheTimeout (const int millisecs);
  29938. juce_UseDebuggingNewOperator
  29939. private:
  29940. CriticalSection lock;
  29941. VoidArray images;
  29942. ImageCache() throw();
  29943. ImageCache (const ImageCache&);
  29944. const ImageCache& operator= (const ImageCache&);
  29945. ~ImageCache();
  29946. void timerCallback();
  29947. };
  29948. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  29949. /********* End of inlined file: juce_ImageCache.h *********/
  29950. #endif
  29951. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29952. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  29953. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29954. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  29955. /**
  29956. Represents a filter kernel to use in convoluting an image.
  29957. @see Image::applyConvolution
  29958. */
  29959. class JUCE_API ImageConvolutionKernel
  29960. {
  29961. public:
  29962. /** Creates an empty convulution kernel.
  29963. @param size the length of each dimension of the kernel, so e.g. if the size
  29964. is 5, it will create a 5x5 kernel
  29965. */
  29966. ImageConvolutionKernel (const int size) throw();
  29967. /** Destructor. */
  29968. ~ImageConvolutionKernel() throw();
  29969. /** Resets all values in the kernel to zero.
  29970. */
  29971. void clear() throw();
  29972. /** Sets the value of a specific cell in the kernel.
  29973. The x and y parameters must be in the range 0 < x < getKernelSize().
  29974. @see setOverallSum
  29975. */
  29976. void setKernelValue (const int x,
  29977. const int y,
  29978. const float value) throw();
  29979. /** Rescales all values in the kernel to make the total add up to a fixed value.
  29980. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  29981. */
  29982. void setOverallSum (const float desiredTotalSum) throw();
  29983. /** Multiplies all values in the kernel by a value. */
  29984. void rescaleAllValues (const float multiplier) throw();
  29985. /** Intialises the kernel for a gaussian blur.
  29986. @param blurRadius this may be larger or smaller than the kernel's actual
  29987. size but this will obviously be wasteful or clip at the
  29988. edges. Ideally the kernel should be just larger than
  29989. (blurRadius * 2).
  29990. */
  29991. void createGaussianBlur (const float blurRadius) throw();
  29992. /** Returns the size of the kernel.
  29993. E.g. if it's a 3x3 kernel, this returns 3.
  29994. */
  29995. int getKernelSize() const throw() { return size; }
  29996. /** Returns a 2-dimensional array of the kernel's values.
  29997. The size of each dimension of the array will be getKernelSize().
  29998. */
  29999. float** getValues() const throw() { return values; }
  30000. /** Applies the kernel to an image.
  30001. @param destImage the image that will receive the resultant convoluted pixels.
  30002. @param sourceImage an optional source image to read from - if this is 0, then the
  30003. destination image will be used as the source. If an image is
  30004. specified, it must be exactly the same size and type as the destination
  30005. image.
  30006. @param x the region of the image to apply the filter to
  30007. @param y the region of the image to apply the filter to
  30008. @param width the region of the image to apply the filter to
  30009. @param height the region of the image to apply the filter to
  30010. */
  30011. void applyToImage (Image& destImage,
  30012. const Image* sourceImage,
  30013. int x,
  30014. int y,
  30015. int width,
  30016. int height) const;
  30017. juce_UseDebuggingNewOperator
  30018. private:
  30019. float** values;
  30020. int size;
  30021. // no reason not to implement these one day..
  30022. ImageConvolutionKernel (const ImageConvolutionKernel&);
  30023. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  30024. };
  30025. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30026. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  30027. #endif
  30028. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30029. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  30030. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30031. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30032. /**
  30033. Base-class for codecs that can read and write image file formats such
  30034. as PNG, JPEG, etc.
  30035. This class also contains static methods to make it easy to load images
  30036. from files, streams or from memory.
  30037. @see Image, ImageCache
  30038. */
  30039. class JUCE_API ImageFileFormat
  30040. {
  30041. protected:
  30042. /** Creates an ImageFormat. */
  30043. ImageFileFormat() throw() {}
  30044. public:
  30045. /** Destructor. */
  30046. virtual ~ImageFileFormat() throw() {}
  30047. /** Returns a description of this file format.
  30048. E.g. "JPEG", "PNG"
  30049. */
  30050. virtual const String getFormatName() = 0;
  30051. /** Returns true if the given stream seems to contain data that this format
  30052. understands.
  30053. The format class should only read the first few bytes of the stream and sniff
  30054. for header bytes that it understands.
  30055. @see decodeImage
  30056. */
  30057. virtual bool canUnderstand (InputStream& input) = 0;
  30058. /** Tries to decode and return an image from the given stream.
  30059. This will be called for an image format after calling its canUnderStand() method
  30060. to see if it can handle the stream.
  30061. @param input the stream to read the data from. The stream will be positioned
  30062. at the start of the image data (but this may not necessarily
  30063. be position 0)
  30064. @returns the image that was decoded, or 0 if it fails. It's the
  30065. caller's responsibility to delete this image when no longer needed.
  30066. @see loadFrom
  30067. */
  30068. virtual Image* decodeImage (InputStream& input) = 0;
  30069. /** Attempts to write an image to a stream.
  30070. To specify extra information like encoding quality, there will be appropriate parameters
  30071. in the subclasses of the specific file types.
  30072. @returns true if it nothing went wrong.
  30073. */
  30074. virtual bool writeImageToStream (const Image& sourceImage,
  30075. OutputStream& destStream) = 0;
  30076. /** Tries the built-in decoders to see if it can find one to read this stream.
  30077. There are currently built-in decoders for PNG, JPEG and GIF formats.
  30078. The object that is returned should not be deleted by the caller.
  30079. @see canUnderstand, decodeImage, loadFrom
  30080. */
  30081. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  30082. /** Tries to load an image from a stream.
  30083. This will use the findImageFormatForStream() method to locate a suitable
  30084. codec, and use that to load the image.
  30085. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30086. caller's responsibility to delete this image when no longer needed.
  30087. */
  30088. static Image* loadFrom (InputStream& input);
  30089. /** Tries to load an image from a file.
  30090. This will use the findImageFormatForStream() method to locate a suitable
  30091. codec, and use that to load the image.
  30092. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30093. caller's responsibility to delete this image when no longer needed.
  30094. */
  30095. static Image* loadFrom (const File& file);
  30096. /** Tries to load an image from a block of raw image data.
  30097. This will use the findImageFormatForStream() method to locate a suitable
  30098. codec, and use that to load the image.
  30099. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30100. caller's responsibility to delete this image when no longer needed.
  30101. */
  30102. static Image* loadFrom (const void* rawData,
  30103. const int numBytesOfData);
  30104. };
  30105. /**
  30106. A type of ImageFileFormat for reading and writing PNG files.
  30107. @see ImageFileFormat, JPEGImageFormat
  30108. */
  30109. class PNGImageFormat : public ImageFileFormat
  30110. {
  30111. public:
  30112. PNGImageFormat() throw();
  30113. ~PNGImageFormat() throw();
  30114. const String getFormatName();
  30115. bool canUnderstand (InputStream& input);
  30116. Image* decodeImage (InputStream& input);
  30117. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30118. };
  30119. /**
  30120. A type of ImageFileFormat for reading and writing JPEG files.
  30121. @see ImageFileFormat, PNGImageFormat
  30122. */
  30123. class JPEGImageFormat : public ImageFileFormat
  30124. {
  30125. public:
  30126. JPEGImageFormat() throw();
  30127. ~JPEGImageFormat() throw();
  30128. /** Specifies the quality to be used when writing a JPEG file.
  30129. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  30130. any negative value is "default" quality
  30131. */
  30132. void setQuality (const float newQuality);
  30133. const String getFormatName();
  30134. bool canUnderstand (InputStream& input);
  30135. Image* decodeImage (InputStream& input);
  30136. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30137. private:
  30138. float quality;
  30139. };
  30140. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30141. /********* End of inlined file: juce_ImageFileFormat.h *********/
  30142. #endif
  30143. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30144. /********* Start of inlined file: juce_Drawable.h *********/
  30145. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30146. #define __JUCE_DRAWABLE_JUCEHEADER__
  30147. /**
  30148. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  30149. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30150. */
  30151. class JUCE_API Drawable
  30152. {
  30153. protected:
  30154. /** The base class can't be instantiated directly.
  30155. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30156. */
  30157. Drawable();
  30158. public:
  30159. /** Destructor. */
  30160. virtual ~Drawable();
  30161. /** Creates a deep copy of this Drawable object.
  30162. Use this to create a new copy of this and any sub-objects in the tree.
  30163. */
  30164. virtual Drawable* createCopy() const = 0;
  30165. /** Renders this Drawable object.
  30166. This is the main rendering method you should call to render a Drawable.
  30167. @see drawWithin
  30168. */
  30169. virtual void draw (Graphics& g,
  30170. const AffineTransform& transform = AffineTransform::identity) const = 0;
  30171. /** Renders the Drawable at a given offset within the Graphics context.
  30172. The co-ordinates passed-in are used to translate the object relative to its own
  30173. origin before drawing it - this is basically a quick way of saying:
  30174. @code
  30175. draw (g, AffineTransform::translation (x, y)).
  30176. @endcode
  30177. */
  30178. void drawAt (Graphics& g,
  30179. const float x,
  30180. const float y) const;
  30181. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  30182. changing its aspect-ratio.
  30183. The object can placed arbitrarily within the rectangle based on a Justification type,
  30184. and can either be made as big as possible, or just reduced to fit.
  30185. @param g the graphics context to render onto
  30186. @param destX top-left of the target rectangle to fit it into
  30187. @param destY top-left of the target rectangle to fit it into
  30188. @param destWidth size of the target rectangle to fit the image into
  30189. @param destHeight size of the target rectangle to fit the image into
  30190. @param placement defines the alignment and rescaling to use to fit
  30191. this object within the target rectangle.
  30192. */
  30193. void drawWithin (Graphics& g,
  30194. const int destX,
  30195. const int destY,
  30196. const int destWidth,
  30197. const int destHeight,
  30198. const RectanglePlacement& placement) const;
  30199. /** Returns the smallest rectangle that can contain this Drawable object.
  30200. Co-ordinates are relative to the object's own origin.
  30201. */
  30202. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  30203. /** Returns true if the given point is somewhere inside this Drawable.
  30204. Co-ordinates are relative to the object's own origin.
  30205. */
  30206. virtual bool hitTest (float x, float y) const = 0;
  30207. /** Returns the name given to this drawable.
  30208. @see setName
  30209. */
  30210. const String& getName() const throw() { return name; }
  30211. /** Assigns a name to this drawable. */
  30212. void setName (const String& newName) throw() { name = newName; }
  30213. /** Tries to turn some kind of image file into a drawable.
  30214. The data could be an image that the ImageFileFormat class understands, or it
  30215. could be SVG.
  30216. */
  30217. static Drawable* createFromImageData (const void* data, const int numBytes);
  30218. /** Tries to turn a stream containing some kind of image data into a drawable.
  30219. The data could be an image that the ImageFileFormat class understands, or it
  30220. could be SVG.
  30221. */
  30222. static Drawable* createFromImageDataStream (InputStream& dataSource);
  30223. /** Tries to turn a file containing some kind of image data into a drawable.
  30224. The data could be an image that the ImageFileFormat class understands, or it
  30225. could be SVG.
  30226. */
  30227. static Drawable* createFromImageFile (const File& file);
  30228. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  30229. into a Drawable tree.
  30230. The object returned must be deleted by the caller. If something goes wrong
  30231. while parsing, it may return 0.
  30232. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  30233. implementation, but it can return the basic vector objects.
  30234. */
  30235. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30236. juce_UseDebuggingNewOperator
  30237. private:
  30238. Drawable (const Drawable&);
  30239. const Drawable& operator= (const Drawable&);
  30240. String name;
  30241. };
  30242. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30243. /********* End of inlined file: juce_Drawable.h *********/
  30244. #endif
  30245. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30246. /********* Start of inlined file: juce_DrawableComposite.h *********/
  30247. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30248. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30249. /**
  30250. A drawable object which acts as a container for a set of other Drawables.
  30251. @see Drawable
  30252. */
  30253. class JUCE_API DrawableComposite : public Drawable
  30254. {
  30255. public:
  30256. /** Creates a composite Drawable.
  30257. */
  30258. DrawableComposite();
  30259. /** Destructor. */
  30260. virtual ~DrawableComposite();
  30261. /** Adds a new sub-drawable to this one.
  30262. This passes in a Drawable pointer for this object to look after. To add a copy
  30263. of a drawable, use the form of this method that takes a Drawable reference instead.
  30264. @param drawable the object to add - this will be deleted automatically
  30265. when no longer needed, so the caller mustn't keep any
  30266. pointers to it.
  30267. @param transform the transform to apply to this drawable when it's being
  30268. drawn
  30269. @param index where to insert it in the list of drawables. 0 is the back,
  30270. -1 is the front, or any value from 0 and getNumDrawables()
  30271. can be used
  30272. @see removeDrawable
  30273. */
  30274. void insertDrawable (Drawable* drawable,
  30275. const AffineTransform& transform = AffineTransform::identity,
  30276. const int index = -1);
  30277. /** Adds a new sub-drawable to this one.
  30278. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  30279. for this object to look after, use the form of this method that takes a Drawable
  30280. pointer instead.
  30281. @param drawable the object to add - an internal copy will be made of this object
  30282. @param transform the transform to apply to this drawable when it's being
  30283. drawn
  30284. @param index where to insert it in the list of drawables. 0 is the back,
  30285. -1 is the front, or any value from 0 and getNumDrawables()
  30286. can be used
  30287. @see removeDrawable
  30288. */
  30289. void insertDrawable (const Drawable& drawable,
  30290. const AffineTransform& transform = AffineTransform::identity,
  30291. const int index = -1);
  30292. /** Deletes one of the Drawable objects.
  30293. @param index the index of the drawable to delete, between 0
  30294. and (getNumDrawables() - 1).
  30295. @see insertDrawable, getNumDrawables
  30296. */
  30297. void removeDrawable (const int index);
  30298. /** Returns the number of drawables contained inside this one.
  30299. @see getDrawable
  30300. */
  30301. int getNumDrawables() const throw() { return drawables.size(); }
  30302. /** Returns one of the drawables that are contained in this one.
  30303. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  30304. to find it.
  30305. The pointer returned is managed by this object and will be deleted when no longer
  30306. needed, so be careful what you do with it.
  30307. @see getNumDrawables
  30308. */
  30309. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  30310. /** Returns the transform that applies to one of the drawables that are contained in this one.
  30311. The pointer returned is managed by this object and will be deleted when no longer
  30312. needed, so be careful what you do with it.
  30313. @see getNumDrawables
  30314. */
  30315. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  30316. /** Brings one of the Drawables to the front.
  30317. @param index the index of the drawable to move, between 0
  30318. and (getNumDrawables() - 1).
  30319. @see insertDrawable, getNumDrawables
  30320. */
  30321. void bringToFront (const int index);
  30322. /** @internal */
  30323. void draw (Graphics& g, const AffineTransform& transform) const;
  30324. /** @internal */
  30325. void getBounds (float& x, float& y, float& width, float& height) const;
  30326. /** @internal */
  30327. bool hitTest (float x, float y) const;
  30328. /** @internal */
  30329. Drawable* createCopy() const;
  30330. juce_UseDebuggingNewOperator
  30331. private:
  30332. OwnedArray <Drawable> drawables;
  30333. OwnedArray <AffineTransform> transforms;
  30334. DrawableComposite (const DrawableComposite&);
  30335. const DrawableComposite& operator= (const DrawableComposite&);
  30336. };
  30337. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30338. /********* End of inlined file: juce_DrawableComposite.h *********/
  30339. #endif
  30340. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30341. /********* Start of inlined file: juce_DrawableImage.h *********/
  30342. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30343. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30344. /**
  30345. A drawable object which is a bitmap image.
  30346. @see Drawable
  30347. */
  30348. class JUCE_API DrawableImage : public Drawable
  30349. {
  30350. public:
  30351. DrawableImage();
  30352. /** Destructor. */
  30353. virtual ~DrawableImage();
  30354. /** Sets the image that this drawable will render.
  30355. An internal copy is made of the image passed-in. If you want to provide an
  30356. image that this object can take charge of without needing to create a copy,
  30357. use the other setImage() method.
  30358. */
  30359. void setImage (const Image& imageToCopy);
  30360. /** Sets the image that this drawable will render.
  30361. An internal copy of this will not be made, so the caller mustn't delete
  30362. the image while it's still being used by this object.
  30363. A good way to use this is with the ImageCache - if you create an image
  30364. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30365. it'll be released neatly with its reference count being decreased.
  30366. @param imageToUse the image to render
  30367. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30368. then the image will be deleted when this object no longer
  30369. needs it - unless the image was created by the ImageCache,
  30370. in which case it will be released with ImageCache::release().
  30371. */
  30372. void setImage (Image* imageToUse,
  30373. const bool releaseWhenNotNeeded);
  30374. /** Returns the current image. */
  30375. Image* getImage() const throw() { return image; }
  30376. /** Clears (and possibly deletes) the currently set image. */
  30377. void clearImage();
  30378. /** Sets the opacity to use when drawing the image. */
  30379. void setOpacity (const float newOpacity);
  30380. /** Returns the image's opacity. */
  30381. float getOpacity() const throw() { return opacity; }
  30382. /** Sets a colour to draw over the image's alpha channel.
  30383. By default this is transparent so isn't drawn, but if you set a non-transparent
  30384. colour here, then it will be overlaid on the image, using the image's alpha
  30385. channel as a mask.
  30386. This is handy for doing things like darkening or lightening an image by overlaying
  30387. it with semi-transparent black or white.
  30388. */
  30389. void setOverlayColour (const Colour& newOverlayColour);
  30390. /** Returns the overlay colour. */
  30391. const Colour& getOverlayColour() const throw() { return overlayColour; }
  30392. /** @internal */
  30393. void draw (Graphics& g, const AffineTransform& transform) const;
  30394. /** @internal */
  30395. void getBounds (float& x, float& y, float& width, float& height) const;
  30396. /** @internal */
  30397. bool hitTest (float x, float y) const;
  30398. /** @internal */
  30399. Drawable* createCopy() const;
  30400. juce_UseDebuggingNewOperator
  30401. private:
  30402. Image* image;
  30403. bool canDeleteImage;
  30404. float opacity;
  30405. Colour overlayColour;
  30406. DrawableImage (const DrawableImage&);
  30407. const DrawableImage& operator= (const DrawableImage&);
  30408. };
  30409. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30410. /********* End of inlined file: juce_DrawableImage.h *********/
  30411. #endif
  30412. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30413. /********* Start of inlined file: juce_DrawablePath.h *********/
  30414. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30415. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  30416. /**
  30417. A drawable object which renders a filled or outlined shape.
  30418. @see Drawable
  30419. */
  30420. class JUCE_API DrawablePath : public Drawable
  30421. {
  30422. public:
  30423. /** Creates a DrawablePath.
  30424. */
  30425. DrawablePath();
  30426. /** Destructor. */
  30427. virtual ~DrawablePath();
  30428. /** Changes the path that will be drawn.
  30429. @see setSolidFill, setOutline
  30430. */
  30431. void setPath (const Path& newPath);
  30432. /** Returns the current path. */
  30433. const Path& getPath() const throw() { return path; }
  30434. /** Sets a colour to fill the path with.
  30435. This colour is used to fill the path - if you don't want the path to be
  30436. filled (e.g. if you're just drawing an outline), set this colour to be
  30437. transparent.
  30438. @see setPath, setOutline
  30439. */
  30440. void setSolidFill (const Colour& newColour);
  30441. /** Sets a custom brush to use to fill the path.
  30442. @see setSolidFill
  30443. */
  30444. void setFillBrush (const Brush& newBrush);
  30445. /** Returns the brush currently being used to fill the shape. */
  30446. Brush* getCurrentBrush() const throw() { return fillBrush; }
  30447. /** Changes the properties of the outline that will be drawn around the path.
  30448. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  30449. colour passed-in here will be used for it.
  30450. @see setPath, setSolidFill
  30451. */
  30452. void setOutline (const float thickness,
  30453. const Colour& outlineColour);
  30454. /** Changes the properties of the outline that will be drawn around the path.
  30455. If the stroke type has 0 thickness, no outline will be drawn.
  30456. @see setPath, setSolidFill
  30457. */
  30458. void setOutline (const PathStrokeType& strokeType,
  30459. const Brush& strokeBrush);
  30460. /** Returns the current outline style. */
  30461. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  30462. /** Returns the brush currently being used to draw the outline. */
  30463. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  30464. /** @internal */
  30465. void draw (Graphics& g, const AffineTransform& transform) const;
  30466. /** @internal */
  30467. void getBounds (float& x, float& y, float& width, float& height) const;
  30468. /** @internal */
  30469. bool hitTest (float x, float y) const;
  30470. /** @internal */
  30471. Drawable* createCopy() const;
  30472. juce_UseDebuggingNewOperator
  30473. private:
  30474. Path path, outline;
  30475. Brush* fillBrush;
  30476. Brush* strokeBrush;
  30477. PathStrokeType strokeType;
  30478. void updateOutline();
  30479. DrawablePath (const DrawablePath&);
  30480. const DrawablePath& operator= (const DrawablePath&);
  30481. };
  30482. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  30483. /********* End of inlined file: juce_DrawablePath.h *********/
  30484. #endif
  30485. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30486. /********* Start of inlined file: juce_DrawableText.h *********/
  30487. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30488. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30489. /**
  30490. A drawable object which renders a line of text.
  30491. @see Drawable
  30492. */
  30493. class JUCE_API DrawableText : public Drawable
  30494. {
  30495. public:
  30496. /** Creates a DrawableText object. */
  30497. DrawableText();
  30498. /** Destructor. */
  30499. virtual ~DrawableText();
  30500. /** Sets the block of text to render */
  30501. void setText (const GlyphArrangement& newText);
  30502. /** Sets a single line of text to render.
  30503. This is a convenient method of adding a single line - for
  30504. more complex text, use the setText() that takes a
  30505. GlyphArrangement instead.
  30506. */
  30507. void setText (const String& newText, const Font& fontToUse);
  30508. /** Returns the text arrangement that was set with setText(). */
  30509. const GlyphArrangement& getText() const throw() { return text; }
  30510. /** Sets the colour of the text. */
  30511. void setColour (const Colour& newColour);
  30512. /** Returns the current text colour. */
  30513. const Colour& getColour() const throw() { return colour; }
  30514. /** @internal */
  30515. void draw (Graphics& g, const AffineTransform& transform) const;
  30516. /** @internal */
  30517. void getBounds (float& x, float& y, float& width, float& height) const;
  30518. /** @internal */
  30519. bool hitTest (float x, float y) const;
  30520. /** @internal */
  30521. Drawable* createCopy() const;
  30522. juce_UseDebuggingNewOperator
  30523. private:
  30524. GlyphArrangement text;
  30525. Colour colour;
  30526. DrawableText (const DrawableText&);
  30527. const DrawableText& operator= (const DrawableText&);
  30528. };
  30529. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  30530. /********* End of inlined file: juce_DrawableText.h *********/
  30531. #endif
  30532. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  30533. #endif
  30534. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  30535. #endif
  30536. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  30537. #endif
  30538. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  30539. #endif
  30540. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30541. /********* Start of inlined file: juce_ArrowButton.h *********/
  30542. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  30543. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  30544. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  30545. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30546. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30547. /**
  30548. An effect filter that adds a drop-shadow behind the image's content.
  30549. (This will only work on images/components that aren't opaque, of course).
  30550. When added to a component, this effect will draw a soft-edged
  30551. shadow based on what gets drawn inside it. The shadow will also
  30552. be applied to the component's children.
  30553. For speed, this doesn't use a proper gaussian blur, but cheats by
  30554. using a simple bilinear filter. If you need a really high-quality
  30555. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  30556. @see Component::setComponentEffect
  30557. */
  30558. class JUCE_API DropShadowEffect : public ImageEffectFilter
  30559. {
  30560. public:
  30561. /** Creates a default drop-shadow effect.
  30562. To customise the shadow's appearance, use the setShadowProperties()
  30563. method.
  30564. */
  30565. DropShadowEffect();
  30566. /** Destructor. */
  30567. ~DropShadowEffect();
  30568. /** Sets up parameters affecting the shadow's appearance.
  30569. @param newRadius the (approximate) radius of the blur used
  30570. @param newOpacity the opacity with which the shadow is rendered
  30571. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  30572. component's contents
  30573. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  30574. component's contents
  30575. */
  30576. void setShadowProperties (const float newRadius,
  30577. const float newOpacity,
  30578. const int newShadowOffsetX,
  30579. const int newShadowOffsetY);
  30580. /** @internal */
  30581. void applyEffect (Image& sourceImage, Graphics& destContext);
  30582. juce_UseDebuggingNewOperator
  30583. private:
  30584. int offsetX, offsetY;
  30585. float radius, opacity;
  30586. };
  30587. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  30588. /********* End of inlined file: juce_DropShadowEffect.h *********/
  30589. /**
  30590. A button with an arrow in it.
  30591. @see Button
  30592. */
  30593. class JUCE_API ArrowButton : public Button
  30594. {
  30595. public:
  30596. /** Creates an ArrowButton.
  30597. @param buttonName the name to give the button
  30598. @param arrowDirection the direction the arrow should point in, where 0.0 is
  30599. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  30600. @param arrowColour the colour to use for the arrow
  30601. */
  30602. ArrowButton (const String& buttonName,
  30603. float arrowDirection,
  30604. const Colour& arrowColour);
  30605. /** Destructor. */
  30606. ~ArrowButton();
  30607. juce_UseDebuggingNewOperator
  30608. protected:
  30609. /** @internal */
  30610. void paintButton (Graphics& g,
  30611. bool isMouseOverButton,
  30612. bool isButtonDown);
  30613. /** @internal */
  30614. void buttonStateChanged();
  30615. private:
  30616. Colour colour;
  30617. DropShadowEffect shadow;
  30618. Path path;
  30619. int offset;
  30620. ArrowButton (const ArrowButton&);
  30621. const ArrowButton& operator= (const ArrowButton&);
  30622. };
  30623. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  30624. /********* End of inlined file: juce_ArrowButton.h *********/
  30625. #endif
  30626. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30627. #endif
  30628. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30629. /********* Start of inlined file: juce_DrawableButton.h *********/
  30630. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30631. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30632. /**
  30633. A button that displays a Drawable.
  30634. Up to three Drawable objects can be given to this button, to represent the
  30635. 'normal', 'over' and 'down' states.
  30636. @see Button
  30637. */
  30638. class JUCE_API DrawableButton : public Button
  30639. {
  30640. public:
  30641. enum ButtonStyle
  30642. {
  30643. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  30644. ImageRaw, /**< The button will just display the images in their normal size and position.
  30645. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  30646. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  30647. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  30648. };
  30649. /** Creates a DrawableButton.
  30650. After creating one of these, use setImages() to specify the drawables to use.
  30651. @param buttonName the name to give the component
  30652. @param buttonStyle the layout to use
  30653. @see ButtonStyle, setButtonStyle, setImages
  30654. */
  30655. DrawableButton (const String& buttonName,
  30656. const ButtonStyle buttonStyle);
  30657. /** Destructor. */
  30658. ~DrawableButton();
  30659. /** Sets up the images to draw for the various button states.
  30660. The button will keep its own internal copies of these drawables.
  30661. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  30662. will be made of the object passed-in if it is non-zero.
  30663. @param overImage the thing to draw for the button's 'over' state - if this is
  30664. zero, the button's normal image will be used when the mouse is
  30665. over it. An internal copy will be made of the object passed-in
  30666. if it is non-zero.
  30667. @param downImage the thing to draw for the button's 'down' state - if this is
  30668. zero, the 'over' image will be used instead (or the normal image
  30669. as a last resort). An internal copy will be made of the object
  30670. passed-in if it is non-zero.
  30671. @param disabledImage an image to draw when the button is disabled. If this is zero,
  30672. the normal image will be drawn with a reduced opacity instead.
  30673. An internal copy will be made of the object passed-in if it is
  30674. non-zero.
  30675. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  30676. state is 'on'. If this is 0, the normal image is used instead
  30677. @param overImageOn same as the overImage, but this is used when the button's toggle
  30678. state is 'on'. If this is 0, the normalImageOn is drawn instead
  30679. @param downImageOn same as the downImage, but this is used when the button's toggle
  30680. state is 'on'. If this is 0, the overImageOn is drawn instead
  30681. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  30682. state is 'on'. If this is 0, the normal image will be drawn instead
  30683. with a reduced opacity
  30684. */
  30685. void setImages (const Drawable* normalImage,
  30686. const Drawable* overImage = 0,
  30687. const Drawable* downImage = 0,
  30688. const Drawable* disabledImage = 0,
  30689. const Drawable* normalImageOn = 0,
  30690. const Drawable* overImageOn = 0,
  30691. const Drawable* downImageOn = 0,
  30692. const Drawable* disabledImageOn = 0);
  30693. /** Changes the button's style.
  30694. @see ButtonStyle
  30695. */
  30696. void setButtonStyle (const ButtonStyle newStyle);
  30697. /** Changes the button's background colours.
  30698. The toggledOffColour is the colour to use when the button's toggle state
  30699. is off, and toggledOnColour when it's on.
  30700. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  30701. used to fill the background of the component.
  30702. For an ImageOnButtonBackground style, the colour is used to draw the
  30703. button's lozenge shape and exactly how the colour's used will depend
  30704. on the LookAndFeel.
  30705. */
  30706. void setBackgroundColours (const Colour& toggledOffColour,
  30707. const Colour& toggledOnColour);
  30708. /** Returns the current background colour being used.
  30709. @see setBackgroundColour
  30710. */
  30711. const Colour& getBackgroundColour() const throw();
  30712. /** Gives the button an optional amount of space around the edge of the drawable.
  30713. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  30714. ones on a button background. If the button is too small for the given gap, a
  30715. smaller gap will be used.
  30716. By default there's a gap of about 3 pixels.
  30717. */
  30718. void setEdgeIndent (const int numPixelsIndent);
  30719. /** Returns the image that the button is currently displaying. */
  30720. const Drawable* getCurrentImage() const throw();
  30721. const Drawable* getNormalImage() const throw();
  30722. const Drawable* getOverImage() const throw();
  30723. const Drawable* getDownImage() const throw();
  30724. juce_UseDebuggingNewOperator
  30725. protected:
  30726. /** @internal */
  30727. void paintButton (Graphics& g,
  30728. bool isMouseOverButton,
  30729. bool isButtonDown);
  30730. private:
  30731. ButtonStyle style;
  30732. Drawable* normalImage;
  30733. Drawable* overImage;
  30734. Drawable* downImage;
  30735. Drawable* disabledImage;
  30736. Drawable* normalImageOn;
  30737. Drawable* overImageOn;
  30738. Drawable* downImageOn;
  30739. Drawable* disabledImageOn;
  30740. Colour backgroundOff, backgroundOn;
  30741. int edgeIndent;
  30742. void deleteImages();
  30743. DrawableButton (const DrawableButton&);
  30744. const DrawableButton& operator= (const DrawableButton&);
  30745. };
  30746. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30747. /********* End of inlined file: juce_DrawableButton.h *********/
  30748. #endif
  30749. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30750. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30751. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30752. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30753. /**
  30754. A button showing an underlined weblink, that will launch the link
  30755. when it's clicked.
  30756. @see Button
  30757. */
  30758. class JUCE_API HyperlinkButton : public Button
  30759. {
  30760. public:
  30761. /** Creates a HyperlinkButton.
  30762. @param linkText the text that will be displayed in the button - this is
  30763. also set as the Component's name, but the text can be
  30764. changed later with the Button::getButtonText() method
  30765. @param linkURL the URL to launch when the user clicks the button
  30766. */
  30767. HyperlinkButton (const String& linkText,
  30768. const URL& linkURL);
  30769. /** Destructor. */
  30770. ~HyperlinkButton();
  30771. /** Changes the font to use for the text.
  30772. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30773. to match the size of the component.
  30774. */
  30775. void setFont (const Font& newFont,
  30776. const bool resizeToMatchComponentHeight,
  30777. const Justification& justificationType = Justification::horizontallyCentred);
  30778. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30779. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30780. methods.
  30781. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30782. */
  30783. enum ColourIds
  30784. {
  30785. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30786. };
  30787. /** Changes the URL that the button will trigger. */
  30788. void setURL (const URL& newURL) throw();
  30789. /** Returns the URL that the button will trigger. */
  30790. const URL& getURL() const throw() { return url; }
  30791. /** Resizes the button horizontally to fit snugly around the text.
  30792. This won't affect the button's height.
  30793. */
  30794. void changeWidthToFitText();
  30795. juce_UseDebuggingNewOperator
  30796. protected:
  30797. /** @internal */
  30798. void clicked();
  30799. /** @internal */
  30800. void colourChanged();
  30801. /** @internal */
  30802. void paintButton (Graphics& g,
  30803. bool isMouseOverButton,
  30804. bool isButtonDown);
  30805. private:
  30806. URL url;
  30807. Font font;
  30808. bool resizeFont;
  30809. Justification justification;
  30810. const Font getFontToUse() const;
  30811. HyperlinkButton (const HyperlinkButton&);
  30812. const HyperlinkButton& operator= (const HyperlinkButton&);
  30813. };
  30814. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30815. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30816. #endif
  30817. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30818. /********* Start of inlined file: juce_ImageButton.h *********/
  30819. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30820. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30821. /**
  30822. As the title suggests, this is a button containing an image.
  30823. The colour and transparency of the image can be set to vary when the
  30824. button state changes.
  30825. @see Button, ShapeButton, TextButton
  30826. */
  30827. class JUCE_API ImageButton : public Button
  30828. {
  30829. public:
  30830. /** Creates an ImageButton.
  30831. Use setImage() to specify the image to use. The colours and opacities that
  30832. are specified here can be changed later using setDrawingOptions().
  30833. @param name the name to give the component
  30834. */
  30835. ImageButton (const String& name);
  30836. /** Destructor. */
  30837. ~ImageButton();
  30838. /** Sets up the images to draw in various states.
  30839. Important! Bear in mind that if you pass the same image in for more than one of
  30840. these parameters, this button will delete it (or release from the ImageCache)
  30841. multiple times!
  30842. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30843. resized to the same dimensions as the normal image
  30844. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30845. button when the button's size changes
  30846. @param preserveImageProportions if true then any rescaling of the image to fit
  30847. the button will keep the image's x and y proportions
  30848. correct - i.e. it won't distort its shape, although
  30849. this might create gaps around the edges
  30850. @param normalImage the image to use when the button is in its normal state. The
  30851. image passed in will be deleted (or released if it
  30852. was created by the ImageCache class) when the
  30853. button no longer needs it.
  30854. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30855. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30856. normal image - if this colour is transparent, no overlay
  30857. will be drawn. The overlay will be drawn over the top of the
  30858. image, so you can basically add a solid or semi-transparent
  30859. colour to the image to brighten or darken it
  30860. @param overImage the image to use when the mouse is over the button. If
  30861. you want to use the same image as was set in the normalImage
  30862. parameter, this value can be 0. As for normalImage, it
  30863. will be deleted or released by the button when no longer
  30864. needed
  30865. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30866. is over the button
  30867. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30868. image when the mouse is over - if this colour is transparent,
  30869. no overlay will be drawn
  30870. @param downImage an image to use when the button is pressed down. If set
  30871. to zero, the 'over' image will be drawn instead (or the
  30872. normal image if there isn't an 'over' image either). This
  30873. image will be deleted or released by the button when no
  30874. longer needed
  30875. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30876. is pressed
  30877. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  30878. image when the button is pressed down - if this colour is
  30879. transparent, no overlay will be drawn
  30880. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  30881. whenever it's inside the button's bounding rectangle. If
  30882. set to values higher than 0, the mouse will only be
  30883. considered to be over the image when the value of the
  30884. image's alpha channel at that position is greater than
  30885. this level.
  30886. */
  30887. void setImages (const bool resizeButtonNowToFitThisImage,
  30888. const bool rescaleImagesWhenButtonSizeChanges,
  30889. const bool preserveImageProportions,
  30890. Image* const normalImage,
  30891. const float imageOpacityWhenNormal,
  30892. const Colour& overlayColourWhenNormal,
  30893. Image* const overImage,
  30894. const float imageOpacityWhenOver,
  30895. const Colour& overlayColourWhenOver,
  30896. Image* const downImage,
  30897. const float imageOpacityWhenDown,
  30898. const Colour& overlayColourWhenDown,
  30899. const float hitTestAlphaThreshold = 0.0f);
  30900. /** Returns the currently set 'normal' image. */
  30901. Image* getNormalImage() const throw();
  30902. /** Returns the image that's drawn when the mouse is over the button.
  30903. If an 'over' image has been set, this will return it; otherwise it'll
  30904. just return the normal image.
  30905. */
  30906. Image* getOverImage() const throw();
  30907. /** Returns the image that's drawn when the button is held down.
  30908. If a 'down' image has been set, this will return it; otherwise it'll
  30909. return the 'over' image or normal image, depending on what's available.
  30910. */
  30911. Image* getDownImage() const throw();
  30912. juce_UseDebuggingNewOperator
  30913. protected:
  30914. /** @internal */
  30915. bool hitTest (int x, int y);
  30916. /** @internal */
  30917. void paintButton (Graphics& g,
  30918. bool isMouseOverButton,
  30919. bool isButtonDown);
  30920. private:
  30921. bool scaleImageToFit, preserveProportions;
  30922. unsigned char alphaThreshold;
  30923. int imageX, imageY, imageW, imageH;
  30924. Image* normalImage;
  30925. Image* overImage;
  30926. Image* downImage;
  30927. float normalOpacity, overOpacity, downOpacity;
  30928. Colour normalOverlay, overOverlay, downOverlay;
  30929. Image* getCurrentImage() const;
  30930. void deleteImages();
  30931. ImageButton (const ImageButton&);
  30932. const ImageButton& operator= (const ImageButton&);
  30933. };
  30934. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  30935. /********* End of inlined file: juce_ImageButton.h *********/
  30936. #endif
  30937. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30938. /********* Start of inlined file: juce_ShapeButton.h *********/
  30939. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30940. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  30941. /**
  30942. A button that contains a filled shape.
  30943. @see Button, ImageButton, TextButton, ArrowButton
  30944. */
  30945. class JUCE_API ShapeButton : public Button
  30946. {
  30947. public:
  30948. /** Creates a ShapeButton.
  30949. @param name a name to give the component - see Component::setName()
  30950. @param normalColour the colour to fill the shape with when the mouse isn't over
  30951. @param overColour the colour to use when the mouse is over the shape
  30952. @param downColour the colour to use when the button is in the pressed-down state
  30953. */
  30954. ShapeButton (const String& name,
  30955. const Colour& normalColour,
  30956. const Colour& overColour,
  30957. const Colour& downColour);
  30958. /** Destructor. */
  30959. ~ShapeButton();
  30960. /** Sets the shape to use.
  30961. @param newShape the shape to use
  30962. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  30963. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  30964. the button is resized
  30965. @param hasDropShadow if true, the button will be given a drop-shadow effect
  30966. */
  30967. void setShape (const Path& newShape,
  30968. const bool resizeNowToFitThisShape,
  30969. const bool maintainShapeProportions,
  30970. const bool hasDropShadow);
  30971. /** Set the colours to use for drawing the shape.
  30972. @param normalColour the colour to fill the shape with when the mouse isn't over
  30973. @param overColour the colour to use when the mouse is over the shape
  30974. @param downColour the colour to use when the button is in the pressed-down state
  30975. */
  30976. void setColours (const Colour& normalColour,
  30977. const Colour& overColour,
  30978. const Colour& downColour);
  30979. /** Sets up an outline to draw around the shape.
  30980. @param outlineColour the colour to use
  30981. @param outlineStrokeWidth the thickness of line to draw
  30982. */
  30983. void setOutline (const Colour& outlineColour,
  30984. const float outlineStrokeWidth);
  30985. juce_UseDebuggingNewOperator
  30986. protected:
  30987. /** @internal */
  30988. void paintButton (Graphics& g,
  30989. bool isMouseOverButton,
  30990. bool isButtonDown);
  30991. private:
  30992. Colour normalColour, overColour, downColour, outlineColour;
  30993. DropShadowEffect shadow;
  30994. Path shape;
  30995. bool maintainShapeProportions;
  30996. float outlineWidth;
  30997. ShapeButton (const ShapeButton&);
  30998. const ShapeButton& operator= (const ShapeButton&);
  30999. };
  31000. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  31001. /********* End of inlined file: juce_ShapeButton.h *********/
  31002. #endif
  31003. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  31004. #endif
  31005. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31006. /********* Start of inlined file: juce_ToggleButton.h *********/
  31007. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31008. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31009. /**
  31010. A button that can be toggled on/off.
  31011. All buttons can be toggle buttons, but this lets you create one of the
  31012. standard ones which has a tick-box and a text label next to it.
  31013. @see Button, DrawableButton, TextButton
  31014. */
  31015. class JUCE_API ToggleButton : public Button
  31016. {
  31017. public:
  31018. /** Creates a ToggleButton.
  31019. @param buttonText the text to put in the button (the component's name is also
  31020. initially set to this string, but these can be changed later
  31021. using the setName() and setButtonText() methods)
  31022. */
  31023. ToggleButton (const String& buttonText);
  31024. /** Destructor. */
  31025. ~ToggleButton();
  31026. /** Resizes the button to fit neatly around its current text.
  31027. The button's height won't be affected, only its width.
  31028. */
  31029. void changeWidthToFitText();
  31030. /** A set of colour IDs to use to change the colour of various aspects of the button.
  31031. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31032. methods.
  31033. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31034. */
  31035. enum ColourIds
  31036. {
  31037. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  31038. };
  31039. juce_UseDebuggingNewOperator
  31040. protected:
  31041. /** @internal */
  31042. void paintButton (Graphics& g,
  31043. bool isMouseOverButton,
  31044. bool isButtonDown);
  31045. /** @internal */
  31046. void colourChanged();
  31047. private:
  31048. ToggleButton (const ToggleButton&);
  31049. const ToggleButton& operator= (const ToggleButton&);
  31050. };
  31051. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31052. /********* End of inlined file: juce_ToggleButton.h *********/
  31053. #endif
  31054. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31055. /********* Start of inlined file: juce_ToolbarButton.h *********/
  31056. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31057. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31058. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  31059. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31060. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31061. /********* Start of inlined file: juce_Toolbar.h *********/
  31062. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  31063. #define __JUCE_TOOLBAR_JUCEHEADER__
  31064. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  31065. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31066. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31067. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  31068. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31069. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31070. /**
  31071. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  31072. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  31073. derive your component from this class, and make sure that it is somewhere inside a
  31074. DragAndDropContainer component.
  31075. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31076. the operating system onto your component, you don't need any of these classes: instead
  31077. see the FileDragAndDropTarget class.
  31078. @see DragAndDropContainer, FileDragAndDropTarget
  31079. */
  31080. class JUCE_API DragAndDropTarget
  31081. {
  31082. public:
  31083. /** Destructor. */
  31084. virtual ~DragAndDropTarget() {}
  31085. /** Callback to check whether this target is interested in the type of object being
  31086. dragged.
  31087. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31088. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31089. @returns true if this component wants to receive the other callbacks regarging this
  31090. type of object; if it returns false, no other callbacks will be made.
  31091. */
  31092. virtual bool isInterestedInDragSource (const String& sourceDescription,
  31093. Component* sourceComponent) = 0;
  31094. /** Callback to indicate that something is being dragged over this component.
  31095. This gets called when the user moves the mouse into this component while dragging
  31096. something.
  31097. Use this callback as a trigger to make your component repaint itself to give the
  31098. user feedback about whether the item can be dropped here or not.
  31099. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31100. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31101. @param x the mouse x position, relative to this component
  31102. @param y the mouse y position, relative to this component
  31103. @see itemDragExit
  31104. */
  31105. virtual void itemDragEnter (const String& sourceDescription,
  31106. Component* sourceComponent,
  31107. int x,
  31108. int y);
  31109. /** Callback to indicate that the user is dragging something over this component.
  31110. This gets called when the user moves the mouse over this component while dragging
  31111. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  31112. this lets you know what happens in-between.
  31113. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31114. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31115. @param x the mouse x position, relative to this component
  31116. @param y the mouse y position, relative to this component
  31117. */
  31118. virtual void itemDragMove (const String& sourceDescription,
  31119. Component* sourceComponent,
  31120. int x,
  31121. int y);
  31122. /** Callback to indicate that something has been dragged off the edge of this component.
  31123. This gets called when the user moves the mouse out of this component while dragging
  31124. something.
  31125. If you've used itemDragEnter() to repaint your component and give feedback, use this
  31126. as a signal to repaint it in its normal state.
  31127. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31128. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31129. @see itemDragEnter
  31130. */
  31131. virtual void itemDragExit (const String& sourceDescription,
  31132. Component* sourceComponent);
  31133. /** Callback to indicate that the user has dropped something onto this component.
  31134. When the user drops an item this get called, and you can use the description to
  31135. work out whether your object wants to deal with it or not.
  31136. Note that after this is called, the itemDragExit method may not be called, so you should
  31137. clean up in here if there's anything you need to do when the drag finishes.
  31138. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31139. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31140. @param x the mouse x position, relative to this component
  31141. @param y the mouse y position, relative to this component
  31142. */
  31143. virtual void itemDropped (const String& sourceDescription,
  31144. Component* sourceComponent,
  31145. int x,
  31146. int y) = 0;
  31147. /** Overriding this allows the target to tell the drag container whether to
  31148. draw the drag image while the cursor is over it.
  31149. By default it returns true, but if you return false, then the normal drag
  31150. image will not be shown when the cursor is over this target.
  31151. */
  31152. virtual bool shouldDrawDragImageWhenOver();
  31153. };
  31154. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31155. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  31156. /**
  31157. Enables drag-and-drop behaviour for a component and all its sub-components.
  31158. For a component to be able to make or receive drag-and-drop events, one of its parent
  31159. components must derive from this class. It's probably best for the top-level
  31160. component to implement it.
  31161. Then to start a drag operation, any sub-component can just call the startDragging()
  31162. method, and this object will take over, tracking the mouse and sending appropriate
  31163. callbacks to any child components derived from DragAndDropTarget which the mouse
  31164. moves over.
  31165. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31166. the operating system onto your component, you don't need any of these classes: you can do this
  31167. simply by overriding Component::filesDropped().
  31168. @see DragAndDropTarget
  31169. */
  31170. class JUCE_API DragAndDropContainer
  31171. {
  31172. public:
  31173. /** Creates a DragAndDropContainer.
  31174. The object that derives from this class must also be a Component.
  31175. */
  31176. DragAndDropContainer();
  31177. /** Destructor. */
  31178. virtual ~DragAndDropContainer();
  31179. /** Begins a drag-and-drop operation.
  31180. This starts a drag-and-drop operation - call it when the user drags the
  31181. mouse in your drag-source component, and this object will track mouse
  31182. movements until the user lets go of the mouse button, and will send
  31183. appropriate messages to DragAndDropTarget objects that the mouse moves
  31184. over.
  31185. findParentDragContainerFor() is a handy method to call to find the
  31186. drag container to use for a component.
  31187. @param sourceDescription a string to use as the description of the thing being
  31188. dragged - this will be passed to the objects that might be
  31189. dropped-onto so they can decide if they want to handle it or
  31190. not
  31191. @param sourceComponent the component that is being dragged
  31192. @param dragImage the image to drag around underneath the mouse. If this is
  31193. zero, a snapshot of the sourceComponent will be used instead. An
  31194. image passed-in will be deleted by this object when no longer
  31195. needed.
  31196. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  31197. window, and can be dragged to DragAndDropTargets that are the
  31198. children of components other than this one.
  31199. */
  31200. void startDragging (const String& sourceDescription,
  31201. Component* sourceComponent,
  31202. Image* dragImage = 0,
  31203. const bool allowDraggingToOtherJuceWindows = false);
  31204. /** Returns true if something is currently being dragged. */
  31205. bool isDragAndDropActive() const;
  31206. /** Returns the description of the thing that's currently being dragged.
  31207. If nothing's being dragged, this will return an empty string, otherwise it's the
  31208. string that was passed into startDragging().
  31209. @see startDragging
  31210. */
  31211. const String getCurrentDragDescription() const;
  31212. /** Utility to find the DragAndDropContainer for a given Component.
  31213. This will search up this component's parent hierarchy looking for the first
  31214. parent component which is a DragAndDropContainer.
  31215. It's useful when a component wants to call startDragging but doesn't know
  31216. the DragAndDropContainer it should to use.
  31217. Obviously this may return 0 if it doesn't find a suitable component.
  31218. */
  31219. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  31220. /** This performs a synchronous drag-and-drop of a set of files to some external
  31221. application.
  31222. You can call this function in response to a mouseDrag callback, and it will
  31223. block, running its own internal message loop and tracking the mouse, while it
  31224. uses a native operating system drag-and-drop operation to move or copy some
  31225. files to another application.
  31226. @param files a list of filenames to drag
  31227. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  31228. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  31229. @returns true if the files were successfully dropped somewhere, or false if it
  31230. was interrupted
  31231. @see performExternalDragDropOfText
  31232. */
  31233. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  31234. /** This performs a synchronous drag-and-drop of a block of text to some external
  31235. application.
  31236. You can call this function in response to a mouseDrag callback, and it will
  31237. block, running its own internal message loop and tracking the mouse, while it
  31238. uses a native operating system drag-and-drop operation to move or copy some
  31239. text to another application.
  31240. @param text the text to copy
  31241. @returns true if the text was successfully dropped somewhere, or false if it
  31242. was interrupted
  31243. @see performExternalDragDropOfFiles
  31244. */
  31245. static bool performExternalDragDropOfText (const String& text);
  31246. juce_UseDebuggingNewOperator
  31247. protected:
  31248. /** Override this if you want to be able to perform an external drag a set of files
  31249. when the user drags outside of this container component.
  31250. This method will be called when a drag operation moves outside the Juce-based window,
  31251. and if you want it to then perform a file drag-and-drop, add the filenames you want
  31252. to the array passed in, and return true.
  31253. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  31254. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  31255. @param files on return, the filenames you want to drag
  31256. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  31257. it must make a copy of them (see the performExternalDragDropOfFiles()
  31258. method)
  31259. @see performExternalDragDropOfFiles
  31260. */
  31261. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  31262. Component* dragSourceComponent,
  31263. StringArray& files,
  31264. bool& canMoveFiles);
  31265. private:
  31266. friend class DragImageComponent;
  31267. Component* dragImageComponent;
  31268. String currentDragDesc;
  31269. };
  31270. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31271. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31272. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31273. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31274. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31275. /**
  31276. Animates a set of components, moving it to a new position.
  31277. To use this, create a ComponentAnimator, and use its animateComponent() method
  31278. to tell it to move components to destination positions. Any number of
  31279. components can be animated by one ComponentAnimator object (if you've got a
  31280. lot of components to move, it's much more efficient to share a single animator
  31281. than to have many animators running at once).
  31282. You'll need to make sure the animator object isn't deleted before it finishes
  31283. moving the components.
  31284. */
  31285. class JUCE_API ComponentAnimator : private Timer
  31286. {
  31287. public:
  31288. /** Creates a ComponentAnimator. */
  31289. ComponentAnimator();
  31290. /** Destructor. */
  31291. ~ComponentAnimator();
  31292. /** Starts a component moving from its current position to a specified position.
  31293. If the component is already in the middle of an animation, that will be abandoned,
  31294. and a new animation will begin, moving the component from its current location.
  31295. The start and end speed parameters let you apply some acceleration to the component's
  31296. movement.
  31297. @param component the component to move
  31298. @param finalPosition the destination position and size to move it to
  31299. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31300. to arrive at its destination
  31301. @param startSpeed a value to indicate the relative start speed of the
  31302. animation. If this is 0, the component will start
  31303. by accelerating from rest; higher values mean that it
  31304. will have an initial speed greater than zero. If the
  31305. value if greater than 1, it will decelerate towards the
  31306. middle of its journey. To move the component at a constant
  31307. rate for its entire animation, set both the start and
  31308. end speeds to 1.0
  31309. @param endSpeed a relative speed at which the component should be moving
  31310. when the animation finishes. If this is 0, the component
  31311. will decelerate to a standstill at its final position; higher
  31312. values mean the component will still be moving when it stops.
  31313. To move the component at a constant rate for its entire
  31314. animation, set both the start and end speeds to 1.0
  31315. */
  31316. void animateComponent (Component* const component,
  31317. const Rectangle& finalPosition,
  31318. const int millisecondsToSpendMoving,
  31319. const double startSpeed = 1.0,
  31320. const double endSpeed = 1.0);
  31321. /** Stops a component if it's currently being animated.
  31322. If moveComponentToItsFinalPosition is true, then the component will
  31323. be immediately moved to its destination position and size. If false, it will be
  31324. left in whatever location it currently occupies.
  31325. */
  31326. void cancelAnimation (Component* const component,
  31327. const bool moveComponentToItsFinalPosition);
  31328. /** Clears all of the active animations.
  31329. If moveComponentsToTheirFinalPositions is true, all the components will
  31330. be immediately set to their final positions. If false, they will be
  31331. left in whatever locations they currently occupy.
  31332. */
  31333. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31334. /** Returns the destination position for a component.
  31335. If the component is being animated, this will return the target position that
  31336. was specified when animateComponent() was called.
  31337. If the specified component isn't currently being animated, this method will just
  31338. return its current position.
  31339. */
  31340. const Rectangle getComponentDestination (Component* const component);
  31341. juce_UseDebuggingNewOperator
  31342. private:
  31343. VoidArray tasks;
  31344. uint32 lastTime;
  31345. void* findTaskFor (Component* const component) const;
  31346. void timerCallback();
  31347. };
  31348. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31349. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31350. class ToolbarItemComponent;
  31351. class ToolbarItemFactory;
  31352. class MissingItemsComponent;
  31353. /**
  31354. A toolbar component.
  31355. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31356. and looks after their order and layout.
  31357. Items (icon buttons or other custom components) are added to a toolbar using a
  31358. ToolbarItemFactory - each type of item is given a unique ID number, and a
  31359. toolbar might contain more than one instance of a particular item type.
  31360. Toolbars can be interactively customised, allowing the user to drag the items
  31361. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  31362. component as a source of new items.
  31363. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  31364. */
  31365. class JUCE_API Toolbar : public Component,
  31366. public DragAndDropContainer,
  31367. public DragAndDropTarget,
  31368. private ButtonListener
  31369. {
  31370. public:
  31371. /** Creates an empty toolbar component.
  31372. To add some icons or other components to your toolbar, you'll need to
  31373. create a ToolbarItemFactory class that can create a suitable set of
  31374. ToolbarItemComponents.
  31375. @see ToolbarItemFactory, ToolbarItemComponents
  31376. */
  31377. Toolbar();
  31378. /** Destructor.
  31379. Any items on the bar will be deleted when the toolbar is deleted.
  31380. */
  31381. ~Toolbar();
  31382. /** Changes the bar's orientation.
  31383. @see isVertical
  31384. */
  31385. void setVertical (const bool shouldBeVertical);
  31386. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  31387. You can change the bar's orientation with setVertical().
  31388. */
  31389. bool isVertical() const throw() { return vertical; }
  31390. /** Returns the depth of the bar.
  31391. If the bar is horizontal, this will return its height; if it's vertical, it
  31392. will return its width.
  31393. @see getLength
  31394. */
  31395. int getThickness() const throw();
  31396. /** Returns the length of the bar.
  31397. If the bar is horizontal, this will return its width; if it's vertical, it
  31398. will return its height.
  31399. @see getThickness
  31400. */
  31401. int getLength() const throw();
  31402. /** Deletes all items from the bar.
  31403. */
  31404. void clear();
  31405. /** Adds an item to the toolbar.
  31406. The factory's ToolbarItemFactory::createItem() will be called by this method
  31407. to create the component that will actually be added to the bar.
  31408. The new item will be inserted at the specified index (if the index is -1, it
  31409. will be added to the right-hand or bottom end of the bar).
  31410. Once added, the component will be automatically deleted by this object when it
  31411. is no longer needed.
  31412. @see ToolbarItemFactory
  31413. */
  31414. void addItem (ToolbarItemFactory& factory,
  31415. const int itemId,
  31416. const int insertIndex = -1);
  31417. /** Deletes one of the items from the bar.
  31418. */
  31419. void removeToolbarItem (const int itemIndex);
  31420. /** Returns the number of items currently on the toolbar.
  31421. @see getItemId, getItemComponent
  31422. */
  31423. int getNumItems() const throw();
  31424. /** Returns the ID of the item with the given index.
  31425. If the index is less than zero or greater than the number of items,
  31426. this will return 0.
  31427. @see getNumItems
  31428. */
  31429. int getItemId (const int itemIndex) const throw();
  31430. /** Returns the component being used for the item with the given index.
  31431. If the index is less than zero or greater than the number of items,
  31432. this will return 0.
  31433. @see getNumItems
  31434. */
  31435. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  31436. /** Clears this toolbar and adds to it the default set of items that the specified
  31437. factory creates.
  31438. @see ToolbarItemFactory::getDefaultItemSet
  31439. */
  31440. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  31441. /** Options for the way items should be displayed.
  31442. @see setStyle, getStyle
  31443. */
  31444. enum ToolbarItemStyle
  31445. {
  31446. iconsOnly, /**< Means that the toolbar should just contain icons. */
  31447. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  31448. textOnly /**< Means that the toolbar only display text labels for each item. */
  31449. };
  31450. /** Returns the toolbar's current style.
  31451. @see ToolbarItemStyle, setStyle
  31452. */
  31453. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31454. /** Changes the toolbar's current style.
  31455. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  31456. */
  31457. void setStyle (const ToolbarItemStyle& newStyle);
  31458. /** Flags used by the showCustomisationDialog() method. */
  31459. enum CustomisationFlags
  31460. {
  31461. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  31462. show the "icons only" option on its choice of toolbar styles. */
  31463. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  31464. show the "icons with text" option on its choice of toolbar styles. */
  31465. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  31466. show the "text only" option on its choice of toolbar styles. */
  31467. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  31468. show a button to reset the toolbar to its default set of items. */
  31469. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  31470. };
  31471. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  31472. The dialog contains a ToolbarItemPalette and various controls for editing other
  31473. aspects of the toolbar. This method will block and run the dialog box modally,
  31474. returning when the user closes it.
  31475. The factory is used to determine the set of items that will be shown on the
  31476. palette.
  31477. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31478. enum.
  31479. @see ToolbarItemPalette
  31480. */
  31481. void showCustomisationDialog (ToolbarItemFactory& factory,
  31482. const int optionFlags = allCustomisationOptionsEnabled);
  31483. /** Turns on or off the toolbar's editing mode, in which its items can be
  31484. rearranged by the user.
  31485. (In most cases it's easier just to use showCustomisationDialog() instead of
  31486. trying to enable editing directly).
  31487. @see ToolbarItemPalette
  31488. */
  31489. void setEditingActive (const bool editingEnabled);
  31490. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31491. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31492. methods.
  31493. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31494. */
  31495. enum ColourIds
  31496. {
  31497. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31498. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31499. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31500. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31501. over them. */
  31502. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31503. held down on them. */
  31504. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31505. when the style is set to iconsWithText or textOnly. */
  31506. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31507. the customisation dialog is active and the mouse moves over them. */
  31508. };
  31509. /** Returns a string that represents the toolbar's current set of items.
  31510. This lets you later restore the same item layout using restoreFromString().
  31511. @see restoreFromString
  31512. */
  31513. const String toString() const;
  31514. /** Restores a set of items that was previously stored in a string by the toString()
  31515. method.
  31516. The factory object is used to create any item components that are needed.
  31517. @see toString
  31518. */
  31519. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31520. const String& savedVersion);
  31521. /** @internal */
  31522. void paint (Graphics& g);
  31523. /** @internal */
  31524. void resized();
  31525. /** @internal */
  31526. void buttonClicked (Button*);
  31527. /** @internal */
  31528. void mouseDown (const MouseEvent&);
  31529. /** @internal */
  31530. bool isInterestedInDragSource (const String&, Component*);
  31531. /** @internal */
  31532. void itemDragMove (const String&, Component*, int, int);
  31533. /** @internal */
  31534. void itemDragExit (const String&, Component*);
  31535. /** @internal */
  31536. void itemDropped (const String&, Component*, int, int);
  31537. /** @internal */
  31538. void updateAllItemPositions (const bool animate);
  31539. /** @internal */
  31540. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31541. juce_UseDebuggingNewOperator
  31542. private:
  31543. Button* missingItemsButton;
  31544. bool vertical, isEditingActive;
  31545. ToolbarItemStyle toolbarStyle;
  31546. ComponentAnimator animator;
  31547. friend class MissingItemsComponent;
  31548. Array <ToolbarItemComponent*> items;
  31549. friend class ItemDragAndDropOverlayComponent;
  31550. static const tchar* const toolbarDragDescriptor;
  31551. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31552. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31553. Toolbar (const Toolbar&);
  31554. const Toolbar& operator= (const Toolbar&);
  31555. };
  31556. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31557. /********* End of inlined file: juce_Toolbar.h *********/
  31558. class ItemDragAndDropOverlayComponent;
  31559. /**
  31560. A component that can be used as one of the items in a Toolbar.
  31561. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31562. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31563. class for further info about creating them.
  31564. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31565. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31566. calling the constructor, and override contentAreaChanged(), in which you can position
  31567. any sub-components you need to add.
  31568. To add basic buttons without writing a special subclass, have a look at the
  31569. ToolbarButton class.
  31570. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31571. */
  31572. class JUCE_API ToolbarItemComponent : public Button
  31573. {
  31574. public:
  31575. /** Constructor.
  31576. @param itemId the ID of the type of toolbar item which this represents
  31577. @param labelText the text to display if the toolbar's style is set to
  31578. Toolbar::iconsWithText or Toolbar::textOnly
  31579. @param isBeingUsedAsAButton set this to false if you don't want the button
  31580. to draw itself with button over/down states when the mouse
  31581. moves over it or clicks
  31582. */
  31583. ToolbarItemComponent (const int itemId,
  31584. const String& labelText,
  31585. const bool isBeingUsedAsAButton);
  31586. /** Destructor. */
  31587. ~ToolbarItemComponent();
  31588. /** Returns the item type ID that this component represents.
  31589. This value is in the constructor.
  31590. */
  31591. int getItemId() const throw() { return itemId; }
  31592. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31593. inside one.
  31594. */
  31595. Toolbar* getToolbar() const;
  31596. /** Returns true if this component is currently inside a toolbar which is vertical.
  31597. @see Toolbar::isVertical
  31598. */
  31599. bool isToolbarVertical() const;
  31600. /** Returns the current style setting of this item.
  31601. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31602. @see setStyle, Toolbar::getStyle
  31603. */
  31604. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31605. /** Changes the current style setting of this item.
  31606. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31607. by the toolbar that holds this item.
  31608. @see setStyle, Toolbar::setStyle
  31609. */
  31610. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31611. /** Returns the area of the component that should be used to display the button image or
  31612. other contents of the item.
  31613. This content area may change when the item's style changes, and may leave a space around the
  31614. edge of the component where the text label can be shown.
  31615. @see contentAreaChanged
  31616. */
  31617. const Rectangle getContentArea() const throw() { return contentArea; }
  31618. /** This method must return the size criteria for this item, based on a given toolbar
  31619. size and orientation.
  31620. The preferredSize, minSize and maxSize values must all be set by your implementation
  31621. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31622. toolbar, they refer to the item's height.
  31623. The preferredSize is the size that the component would like to be, and this must be
  31624. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31625. the same value.
  31626. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31627. Toolbar::getThickness().
  31628. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31629. vertically.
  31630. */
  31631. virtual bool getToolbarItemSizes (int toolbarThickness,
  31632. bool isToolbarVertical,
  31633. int& preferredSize,
  31634. int& minSize,
  31635. int& maxSize) = 0;
  31636. /** Your subclass should use this method to draw its content area.
  31637. The graphics object that is passed-in will have been clipped and had its origin
  31638. moved to fit the content area as specified get getContentArea(). The width and height
  31639. parameters are the width and height of the content area.
  31640. If the component you're writing isn't a button, you can just do nothing in this method.
  31641. */
  31642. virtual void paintButtonArea (Graphics& g,
  31643. int width, int height,
  31644. bool isMouseOver, bool isMouseDown) = 0;
  31645. /** Callback to indicate that the content area of this item has changed.
  31646. This might be because the component was resized, or because the style changed and
  31647. the space needed for the text label is different.
  31648. See getContentArea() for a description of what the area is.
  31649. */
  31650. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31651. /** Editing modes.
  31652. These are used by setEditingMode(), but will be rarely needed in user code.
  31653. */
  31654. enum ToolbarEditingMode
  31655. {
  31656. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31657. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31658. customisation mode, and the items can be dragged around. */
  31659. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31660. dragged onto a toolbar to add it to that bar.*/
  31661. };
  31662. /** Changes the editing mode of this component.
  31663. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31664. and is unlikely to be of much use in end-user-code.
  31665. */
  31666. void setEditingMode (const ToolbarEditingMode newMode);
  31667. /** Returns the current editing mode of this component.
  31668. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31669. and is unlikely to be of much use in end-user-code.
  31670. */
  31671. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31672. /** @internal */
  31673. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31674. /** @internal */
  31675. void resized();
  31676. juce_UseDebuggingNewOperator
  31677. private:
  31678. friend class Toolbar;
  31679. friend class ItemDragAndDropOverlayComponent;
  31680. const int itemId;
  31681. ToolbarEditingMode mode;
  31682. Toolbar::ToolbarItemStyle toolbarStyle;
  31683. Component* overlayComp;
  31684. int dragOffsetX, dragOffsetY;
  31685. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31686. Rectangle contentArea;
  31687. ToolbarItemComponent (const ToolbarItemComponent&);
  31688. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31689. };
  31690. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31691. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31692. /**
  31693. A type of button designed to go on a toolbar.
  31694. This simple button can have two Drawable objects specified - one for normal
  31695. use and another one (optionally) for the button's "on" state if it's a
  31696. toggle button.
  31697. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31698. */
  31699. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31700. {
  31701. public:
  31702. /** Creates a ToolbarButton.
  31703. @param itemId the ID for this toolbar item type. This is passed through to the
  31704. ToolbarItemComponent constructor
  31705. @param labelText the text to display on the button (if the toolbar is using a style
  31706. that shows text labels). This is passed through to the
  31707. ToolbarItemComponent constructor
  31708. @param normalImage a drawable object that the button should use as its icon. The object
  31709. that is passed-in here will be kept by this object and will be
  31710. deleted when no longer needed or when this button is deleted.
  31711. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31712. is in a toggled-on state (see the Button::getToggleState() method). If
  31713. 0 is passed-in here, then the normal image will be used instead, regardless
  31714. of the toggle state. The object that is passed-in here will be kept by
  31715. this object and will be deleted when no longer needed or when this button
  31716. is deleted.
  31717. */
  31718. ToolbarButton (const int itemId,
  31719. const String& labelText,
  31720. Drawable* const normalImage,
  31721. Drawable* const toggledOnImage);
  31722. /** Destructor. */
  31723. ~ToolbarButton();
  31724. /** @internal */
  31725. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31726. int& minSize, int& maxSize);
  31727. /** @internal */
  31728. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31729. /** @internal */
  31730. void contentAreaChanged (const Rectangle& newBounds);
  31731. juce_UseDebuggingNewOperator
  31732. private:
  31733. Drawable* const normalImage;
  31734. Drawable* const toggledOnImage;
  31735. ToolbarButton (const ToolbarButton&);
  31736. const ToolbarButton& operator= (const ToolbarButton&);
  31737. };
  31738. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31739. /********* End of inlined file: juce_ToolbarButton.h *********/
  31740. #endif
  31741. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31742. #endif
  31743. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31744. /********* Start of inlined file: juce_GlowEffect.h *********/
  31745. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  31746. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  31747. /**
  31748. A component effect that adds a coloured blur around the component's contents.
  31749. (This will only work on non-opaque components).
  31750. @see Component::setComponentEffect, DropShadowEffect
  31751. */
  31752. class JUCE_API GlowEffect : public ImageEffectFilter
  31753. {
  31754. public:
  31755. /** Creates a default 'glow' effect.
  31756. To customise its appearance, use the setGlowProperties() method.
  31757. */
  31758. GlowEffect();
  31759. /** Destructor. */
  31760. ~GlowEffect();
  31761. /** Sets the glow's radius and colour.
  31762. The radius is how large the blur should be, and the colour is
  31763. used to render it (for a less intense glow, lower the colour's
  31764. opacity).
  31765. */
  31766. void setGlowProperties (const float newRadius,
  31767. const Colour& newColour);
  31768. /** @internal */
  31769. void applyEffect (Image& sourceImage, Graphics& destContext);
  31770. juce_UseDebuggingNewOperator
  31771. private:
  31772. float radius;
  31773. Colour colour;
  31774. };
  31775. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  31776. /********* End of inlined file: juce_GlowEffect.h *********/
  31777. #endif
  31778. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  31779. #endif
  31780. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31781. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  31782. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31783. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31784. /**
  31785. An effect filter that reduces the image's opacity.
  31786. This can be used to make a component (and its child components) more
  31787. transparent.
  31788. @see Component::setComponentEffect
  31789. */
  31790. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  31791. {
  31792. public:
  31793. /** Creates the effect object.
  31794. The opacity of the component to which the effect is applied will be
  31795. scaled by the given factor (in the range 0 to 1.0f).
  31796. */
  31797. ReduceOpacityEffect (const float opacity = 1.0f);
  31798. /** Destructor. */
  31799. ~ReduceOpacityEffect();
  31800. /** Sets how much to scale the component's opacity.
  31801. @param newOpacity should be between 0 and 1.0f
  31802. */
  31803. void setOpacity (const float newOpacity);
  31804. /** @internal */
  31805. void applyEffect (Image& sourceImage, Graphics& destContext);
  31806. juce_UseDebuggingNewOperator
  31807. private:
  31808. float opacity;
  31809. };
  31810. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  31811. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  31812. #endif
  31813. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  31814. #endif
  31815. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  31816. #endif
  31817. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31818. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  31819. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31820. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  31821. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  31822. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31823. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31824. /**
  31825. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  31826. command in a ApplicationCommandManager.
  31827. Normally, you won't actually create a KeyPressMappingSet directly, because
  31828. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  31829. you'd create yourself an ApplicationCommandManager, and call its
  31830. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  31831. KeyPressMappingSet.
  31832. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  31833. to the top-level component for which you want to handle keystrokes. So for example:
  31834. @code
  31835. class MyMainWindow : public Component
  31836. {
  31837. ApplicationCommandManager* myCommandManager;
  31838. public:
  31839. MyMainWindow()
  31840. {
  31841. myCommandManager = new ApplicationCommandManager();
  31842. // first, make sure the command manager has registered all the commands that its
  31843. // targets can perform..
  31844. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  31845. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  31846. // this will use the command manager to initialise the KeyPressMappingSet with
  31847. // the default keypresses that were specified when the targets added their commands
  31848. // to the manager.
  31849. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  31850. // having set up the default key-mappings, you might now want to load the last set
  31851. // of mappings that the user configured.
  31852. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  31853. // Now tell our top-level window to send any keypresses that arrive to the
  31854. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  31855. addKeyListener (myCommandManager->getKeyMappings());
  31856. }
  31857. ...
  31858. }
  31859. @endcode
  31860. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  31861. register to be told when a command or mapping is added, removed, etc.
  31862. There's also a UI component called KeyMappingEditorComponent that can be used
  31863. to easily edit the key mappings.
  31864. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  31865. */
  31866. class JUCE_API KeyPressMappingSet : public KeyListener,
  31867. public ChangeBroadcaster,
  31868. public FocusChangeListener
  31869. {
  31870. public:
  31871. /** Creates a KeyPressMappingSet for a given command manager.
  31872. Normally, you won't actually create a KeyPressMappingSet directly, because
  31873. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  31874. best thing to do is to create your ApplicationCommandManager, and use the
  31875. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  31876. When a suitable keypress happens, the manager's invoke() method will be
  31877. used to invoke the appropriate command.
  31878. @see ApplicationCommandManager
  31879. */
  31880. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  31881. /** Creates an copy of a KeyPressMappingSet. */
  31882. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  31883. /** Destructor. */
  31884. ~KeyPressMappingSet();
  31885. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  31886. /** Returns a list of keypresses that are assigned to a particular command.
  31887. @param commandID the command's ID
  31888. */
  31889. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  31890. /** Assigns a keypress to a command.
  31891. If the keypress is already assigned to a different command, it will first be
  31892. removed from that command, to avoid it triggering multiple functions.
  31893. @param commandID the ID of the command that you want to add a keypress to. If
  31894. this is 0, the keypress will be removed from anything that it
  31895. was previously assigned to, but not re-assigned
  31896. @param newKeyPress the new key-press
  31897. @param insertIndex if this is less than zero, the key will be appended to the
  31898. end of the list of keypresses; otherwise the new keypress will
  31899. be inserted into the existing list at this index
  31900. */
  31901. void addKeyPress (const CommandID commandID,
  31902. const KeyPress& newKeyPress,
  31903. int insertIndex = -1) throw();
  31904. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  31905. @see resetToDefaultMapping
  31906. */
  31907. void resetToDefaultMappings() throw();
  31908. /** Resets all key-mappings to the defaults for a particular command.
  31909. @see resetToDefaultMappings
  31910. */
  31911. void resetToDefaultMapping (const CommandID commandID) throw();
  31912. /** Removes all keypresses that are assigned to any commands. */
  31913. void clearAllKeyPresses() throw();
  31914. /** Removes all keypresses that are assigned to a particular command. */
  31915. void clearAllKeyPresses (const CommandID commandID) throw();
  31916. /** Removes one of the keypresses that are assigned to a command.
  31917. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  31918. which the keyPressIndex refers.
  31919. */
  31920. void removeKeyPress (const CommandID commandID,
  31921. const int keyPressIndex) throw();
  31922. /** Removes a keypress from any command that it may be assigned to.
  31923. */
  31924. void removeKeyPress (const KeyPress& keypress) throw();
  31925. /** Returns true if the given command is linked to this key. */
  31926. bool containsMapping (const CommandID commandID,
  31927. const KeyPress& keyPress) const throw();
  31928. /** Looks for a command that corresponds to a keypress.
  31929. @returns the UID of the command or 0 if none was found
  31930. */
  31931. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  31932. /** Tries to recreate the mappings from a previously stored state.
  31933. The XML passed in must have been created by the createXml() method.
  31934. If the stored state makes any reference to commands that aren't
  31935. currently available, these will be ignored.
  31936. If the set of mappings being loaded was a set of differences (using createXml (true)),
  31937. then this will call resetToDefaultMappings() and then merge the saved mappings
  31938. on top. If the saved set was created with createXml (false), then this method
  31939. will first clear all existing mappings and load the saved ones as a complete set.
  31940. @returns true if it manages to load the XML correctly
  31941. @see createXml
  31942. */
  31943. bool restoreFromXml (const XmlElement& xmlVersion);
  31944. /** Creates an XML representation of the current mappings.
  31945. This will produce a lump of XML that can be later reloaded using
  31946. restoreFromXml() to recreate the current mapping state.
  31947. The object that is returned must be deleted by the caller.
  31948. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  31949. will be saved into the XML. If it's true, then the XML will
  31950. only store the differences between the current mappings and
  31951. the default mappings you'd get from calling resetToDefaultMappings().
  31952. The advantage of saving a set of differences from the default is that
  31953. if you change the default mappings (in a new version of your app, for
  31954. example), then these will be merged into a user's saved preferences.
  31955. @see restoreFromXml
  31956. */
  31957. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  31958. /** @internal */
  31959. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  31960. /** @internal */
  31961. bool keyStateChanged (Component* originatingComponent);
  31962. /** @internal */
  31963. void globalFocusChanged (Component* focusedComponent);
  31964. juce_UseDebuggingNewOperator
  31965. private:
  31966. ApplicationCommandManager* commandManager;
  31967. struct CommandMapping
  31968. {
  31969. CommandID commandID;
  31970. Array <KeyPress> keypresses;
  31971. bool wantsKeyUpDownCallbacks;
  31972. };
  31973. OwnedArray <CommandMapping> mappings;
  31974. struct KeyPressTime
  31975. {
  31976. KeyPress key;
  31977. uint32 timeWhenPressed;
  31978. };
  31979. OwnedArray <KeyPressTime> keysDown;
  31980. void handleMessage (const Message& message);
  31981. void invokeCommand (const CommandID commandID,
  31982. const KeyPress& keyPress,
  31983. const bool isKeyDown,
  31984. const int millisecsSinceKeyPressed,
  31985. Component* const originatingComponent) const;
  31986. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  31987. };
  31988. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  31989. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  31990. /********* Start of inlined file: juce_TreeView.h *********/
  31991. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  31992. #define __JUCE_TREEVIEW_JUCEHEADER__
  31993. class TreeView;
  31994. /**
  31995. An item in a treeview.
  31996. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  31997. own sub-items.
  31998. To implement an item that contains sub-items, override the itemOpennessChanged()
  31999. method so that when it is opened, it adds the new sub-items to itself using the
  32000. addSubItem method. Depending on the nature of the item it might choose to only
  32001. do this the first time it's opened, or it might want to refresh itself each time.
  32002. It also has the option of deleting its sub-items when it is closed, or leaving them
  32003. in place.
  32004. */
  32005. class JUCE_API TreeViewItem
  32006. {
  32007. public:
  32008. /** Constructor. */
  32009. TreeViewItem();
  32010. /** Destructor. */
  32011. virtual ~TreeViewItem();
  32012. /** Returns the number of sub-items that have been added to this item.
  32013. Note that this doesn't mean much if the node isn't open.
  32014. @see getSubItem, mightContainSubItems, addSubItem
  32015. */
  32016. int getNumSubItems() const throw();
  32017. /** Returns one of the item's sub-items.
  32018. Remember that the object returned might get deleted at any time when its parent
  32019. item is closed or refreshed, depending on the nature of the items you're using.
  32020. @see getNumSubItems
  32021. */
  32022. TreeViewItem* getSubItem (const int index) const throw();
  32023. /** Removes any sub-items. */
  32024. void clearSubItems();
  32025. /** Adds a sub-item.
  32026. @param newItem the object to add to the item's sub-item list. Once added, these can be
  32027. found using getSubItem(). When the items are later removed with
  32028. removeSubItem() (or when this item is deleted), they will be deleted.
  32029. @param insertPosition the index which the new item should have when it's added. If this
  32030. value is less than 0, the item will be added to the end of the list.
  32031. */
  32032. void addSubItem (TreeViewItem* const newItem,
  32033. const int insertPosition = -1);
  32034. /** Removes one of the sub-items.
  32035. @param index the item to remove
  32036. @param deleteItem if true, the item that is removed will also be deleted.
  32037. */
  32038. void removeSubItem (const int index,
  32039. const bool deleteItem = true);
  32040. /** Returns the TreeView to which this item belongs. */
  32041. TreeView* getOwnerView() const throw() { return ownerView; }
  32042. /** Returns the item within which this item is contained. */
  32043. TreeViewItem* getParentItem() const throw() { return parentItem; }
  32044. /** True if this item is currently open in the treeview. */
  32045. bool isOpen() const throw();
  32046. /** Opens or closes the item.
  32047. When opened or closed, the item's itemOpennessChanged() method will be called,
  32048. and a subclass should use this callback to create and add any sub-items that
  32049. it needs to.
  32050. @see itemOpennessChanged, mightContainSubItems
  32051. */
  32052. void setOpen (const bool shouldBeOpen);
  32053. /** True if this item is currently selected.
  32054. Use this when painting the node, to decide whether to draw it as selected or not.
  32055. */
  32056. bool isSelected() const throw();
  32057. /** Selects or deselects the item.
  32058. This will cause a callback to itemSelectionChanged()
  32059. */
  32060. void setSelected (const bool shouldBeSelected,
  32061. const bool deselectOtherItemsFirst);
  32062. /** Returns the rectangle that this item occupies.
  32063. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  32064. top-left of the TreeView comp, so this will depend on the scroll-position of
  32065. the tree. If false, it is relative to the top-left of the topmost item in the
  32066. tree (so this would be unaffected by scrolling the view).
  32067. */
  32068. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  32069. /** Sends a signal to the treeview to make it refresh itself.
  32070. Call this if your items have changed and you want the tree to update to reflect
  32071. this.
  32072. */
  32073. void treeHasChanged() const throw();
  32074. /** Sends a repaint message to redraw just this item.
  32075. Note that you should only call this if you want to repaint a superficial change. If
  32076. you're altering the tree's nodes, you should instead call treeHasChanged().
  32077. */
  32078. void repaintItem() const;
  32079. /** Returns the row number of this item in the tree.
  32080. The row number of an item will change according to which items are open.
  32081. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  32082. */
  32083. int getRowNumberInTree() const throw();
  32084. /** Changes whether lines are drawn to connect any sub-items to this item.
  32085. By default, line-drawing is turned on.
  32086. */
  32087. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  32088. /** Tells the tree whether this item can potentially be opened.
  32089. If your item could contain sub-items, this should return true; if it returns
  32090. false then the tree will not try to open the item. This determines whether or
  32091. not the item will be drawn with a 'plus' button next to it.
  32092. */
  32093. virtual bool mightContainSubItems() = 0;
  32094. /** Returns a string to uniquely identify this item.
  32095. If you're planning on using the TreeView::getOpennessState() method, then
  32096. these strings will be used to identify which nodes are open. The string
  32097. should be unique amongst the item's sibling items, but it's ok for there
  32098. to be duplicates at other levels of the tree.
  32099. If you're not going to store the state, then it's ok not to bother implementing
  32100. this method.
  32101. */
  32102. virtual const String getUniqueName() const;
  32103. /** Called when an item is opened or closed.
  32104. When setOpen() is called and the item has specified that it might
  32105. have sub-items with the mightContainSubItems() method, this method
  32106. is called to let the item create or manage its sub-items.
  32107. So when this is called with isNowOpen set to true (i.e. when the item is being
  32108. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  32109. refresh its sub-item list.
  32110. When this is called with isNowOpen set to false, the subclass might want
  32111. to use clearSubItems() to save on space, or it might choose to leave them,
  32112. depending on the nature of the tree.
  32113. You could also use this callback as a trigger to start a background process
  32114. which asynchronously creates sub-items and adds them, if that's more
  32115. appropriate for the task in hand.
  32116. @see mightContainSubItems
  32117. */
  32118. virtual void itemOpennessChanged (bool isNowOpen);
  32119. /** Must return the width required by this item.
  32120. If your item needs to have a particular width in pixels, return that value; if
  32121. you'd rather have it just fill whatever space is available in the treeview,
  32122. return -1.
  32123. If all your items return -1, no horizontal scrollbar will be shown, but if any
  32124. items have fixed widths and extend beyond the width of the treeview, a
  32125. scrollbar will appear.
  32126. Each item can be a different width, but if they change width, you should call
  32127. treeHasChanged() to update the tree.
  32128. */
  32129. virtual int getItemWidth() const { return -1; }
  32130. /** Must return the height required by this item.
  32131. This is the height in pixels that the item will take up. Items in the tree
  32132. can be different heights, but if they change height, you should call
  32133. treeHasChanged() to update the tree.
  32134. */
  32135. virtual int getItemHeight() const { return 20; }
  32136. /** Creates a component that will be used to represent this item.
  32137. You don't have to implement this method - if it returns 0 then no component
  32138. will be used for the item, and you can just draw it using the paintItem()
  32139. callback. But if you do return a component, it will be positioned in the
  32140. treeview so that it can be used to represent this item.
  32141. The component returned will be managed by the treeview, so always return
  32142. a new component, and don't keep a reference to it, as the treeview will
  32143. delete it later when it goes off the screen or is no longer needed. Also
  32144. bear in mind that if the component keeps a reference to the item that
  32145. created it, that item could be deleted before the component. Its position
  32146. and size will be completely managed by the tree, so don't attempt to move it
  32147. around.
  32148. Something you may want to do with your component is to give it a pointer to
  32149. the TreeView that created it. This is perfectly safe, and there's no danger
  32150. of it becoming a dangling pointer because the TreeView will always delete
  32151. the component before it is itself deleted.
  32152. As long as you stick to these rules you can return whatever kind of
  32153. component you like. It's most useful if you're doing things like drag-and-drop
  32154. of items, or want to use a Label component to edit item names, etc.
  32155. */
  32156. virtual Component* createItemComponent() { return 0; }
  32157. /** Draws the item's contents.
  32158. You can choose to either implement this method and draw each item, or you
  32159. can use createItemComponent() to create a component that will represent the
  32160. item.
  32161. If all you need in your tree is to be able to draw the items and detect when
  32162. the user selects or double-clicks one of them, it's probably enough to
  32163. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  32164. complicated interactions, you may need to use createItemComponent() instead.
  32165. @param g the graphics context to draw into
  32166. @param width the width of the area available for drawing
  32167. @param height the height of the area available for drawing
  32168. */
  32169. virtual void paintItem (Graphics& g, int width, int height);
  32170. /** Draws the item's open/close button.
  32171. If you don't implement this method, the default behaviour is to
  32172. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  32173. it for custom effects.
  32174. */
  32175. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  32176. /** Called when the user clicks on this item.
  32177. If you're using createItemComponent() to create a custom component for the
  32178. item, the mouse-clicks might not make it through to the treeview, but this
  32179. is how you find out about clicks when just drawing each item individually.
  32180. The associated mouse-event details are passed in, so you can find out about
  32181. which button, where it was, etc.
  32182. @see itemDoubleClicked
  32183. */
  32184. virtual void itemClicked (const MouseEvent& e);
  32185. /** Called when the user double-clicks on this item.
  32186. If you're using createItemComponent() to create a custom component for the
  32187. item, the mouse-clicks might not make it through to the treeview, but this
  32188. is how you find out about clicks when just drawing each item individually.
  32189. The associated mouse-event details are passed in, so you can find out about
  32190. which button, where it was, etc.
  32191. If not overridden, the base class method here will open or close the item as
  32192. if the 'plus' button had been clicked.
  32193. @see itemClicked
  32194. */
  32195. virtual void itemDoubleClicked (const MouseEvent& e);
  32196. /** Called when the item is selected or deselected.
  32197. Use this if you want to do something special when the item's selectedness
  32198. changes. By default it'll get repainted when this happens.
  32199. */
  32200. virtual void itemSelectionChanged (bool isNowSelected);
  32201. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  32202. If this returns a non-empty name then when the user drags an item, the treeview will
  32203. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  32204. a drag-and-drop operation, using this string as the source description, with the treeview
  32205. itself as the source component.
  32206. If you need more complex drag-and-drop behaviour, you can use custom components for
  32207. the items, and use those to trigger the drag.
  32208. @see DragAndDropContainer::startDragging
  32209. */
  32210. virtual const String getDragSourceDescription();
  32211. juce_UseDebuggingNewOperator
  32212. private:
  32213. TreeView* ownerView;
  32214. TreeViewItem* parentItem;
  32215. OwnedArray <TreeViewItem> subItems;
  32216. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  32217. int uid;
  32218. bool selected : 1;
  32219. bool redrawNeeded : 1;
  32220. bool drawLinesInside : 1;
  32221. unsigned int openness : 2;
  32222. friend class TreeView;
  32223. friend class TreeViewContentComponent;
  32224. void updatePositions (int newY);
  32225. int getIndentX() const throw();
  32226. void setOwnerView (TreeView* const newOwner) throw();
  32227. void paintRecursively (Graphics& g, int width);
  32228. TreeViewItem* findItemRecursively (int y) throw();
  32229. TreeViewItem* getDeepestOpenParentItem() throw();
  32230. void restoreFromXml (const XmlElement& e);
  32231. XmlElement* createXmlOpenness() const;
  32232. bool isLastOfSiblings() const throw();
  32233. TreeViewItem* getTopLevelItem() throw();
  32234. int getNumRows() const throw();
  32235. TreeViewItem* getItemOnRow (int index) throw();
  32236. void deselectAllRecursively();
  32237. int countSelectedItemsRecursively() const throw();
  32238. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  32239. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  32240. TreeViewItem (const TreeViewItem&);
  32241. const TreeViewItem& operator= (const TreeViewItem&);
  32242. };
  32243. /**
  32244. A tree-view component.
  32245. Use one of these to hold and display a structure of TreeViewItem objects.
  32246. */
  32247. class JUCE_API TreeView : public Component,
  32248. public SettableTooltipClient,
  32249. private AsyncUpdater
  32250. {
  32251. public:
  32252. /** Creates an empty treeview.
  32253. Once you've got a treeview component, you'll need to give it something to
  32254. display, using the setRootItem() method.
  32255. */
  32256. TreeView (const String& componentName = String::empty);
  32257. /** Destructor. */
  32258. ~TreeView();
  32259. /** Sets the item that is displayed in the treeview.
  32260. A tree has a single root item which contains as many sub-items as it needs. If
  32261. you want the tree to contain a number of root items, you should still use a single
  32262. root item above these, but hide it using setRootItemVisible().
  32263. You can pass in 0 to this method to clear the tree and remove its current root item.
  32264. The object passed in will not be deleted by the treeview, it's up to the caller
  32265. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  32266. this item until you've removed it from the tree, either by calling setRootItem (0),
  32267. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  32268. to delete it.
  32269. */
  32270. void setRootItem (TreeViewItem* const newRootItem);
  32271. /** Returns the tree's root item.
  32272. This will be the last object passed to setRootItem(), or 0 if none has been set.
  32273. */
  32274. TreeViewItem* getRootItem() const throw() { return rootItem; }
  32275. /** This will remove and delete the current root item.
  32276. It's a convenient way of deleting the item and calling setRootItem (0).
  32277. */
  32278. void deleteRootItem();
  32279. /** Changes whether the tree's root item is shown or not.
  32280. If the root item is hidden, only its sub-items will be shown in the treeview - this
  32281. lets you make the tree look as if it's got many root items. If it's hidden, this call
  32282. will also make sure the root item is open (otherwise the treeview would look empty).
  32283. */
  32284. void setRootItemVisible (const bool shouldBeVisible);
  32285. /** Returns true if the root item is visible.
  32286. @see setRootItemVisible
  32287. */
  32288. bool isRootItemVisible() const throw() { return rootItemVisible; }
  32289. /** Sets whether items are open or closed by default.
  32290. Normally, items are closed until the user opens them, but you can use this
  32291. to make them default to being open until explicitly closed.
  32292. @see areItemsOpenByDefault
  32293. */
  32294. void setDefaultOpenness (const bool isOpenByDefault);
  32295. /** Returns true if the tree's items default to being open.
  32296. @see setDefaultOpenness
  32297. */
  32298. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  32299. /** This sets a flag to indicate that the tree can be used for multi-selection.
  32300. You can always select multiple items internally by calling the
  32301. TreeViewItem::setSelected() method, but this flag indicates whether the user
  32302. is allowed to multi-select by clicking on the tree.
  32303. By default it is disabled.
  32304. @see isMultiSelectEnabled
  32305. */
  32306. void setMultiSelectEnabled (const bool canMultiSelect);
  32307. /** Returns whether multi-select has been enabled for the tree.
  32308. @see setMultiSelectEnabled
  32309. */
  32310. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  32311. /** Sets a flag to indicate whether to hide the open/close buttons.
  32312. @see areOpenCloseButtonsVisible
  32313. */
  32314. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  32315. /** Returns whether open/close buttons are shown.
  32316. @see setOpenCloseButtonsVisible
  32317. */
  32318. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  32319. /** Deselects any items that are currently selected. */
  32320. void clearSelectedItems();
  32321. /** Returns the number of items that are currently selected.
  32322. @see getSelectedItem, clearSelectedItems
  32323. */
  32324. int getNumSelectedItems() const throw();
  32325. /** Returns one of the selected items in the tree.
  32326. @param index the index, 0 to (getNumSelectedItems() - 1)
  32327. */
  32328. TreeViewItem* getSelectedItem (const int index) const throw();
  32329. /** Returns the number of rows the tree is using.
  32330. This will depend on which items are open.
  32331. @see TreeViewItem::getRowNumberInTree()
  32332. */
  32333. int getNumRowsInTree() const;
  32334. /** Returns the item on a particular row of the tree.
  32335. If the index is out of range, this will return 0.
  32336. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  32337. */
  32338. TreeViewItem* getItemOnRow (int index) const;
  32339. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  32340. void scrollToKeepItemVisible (TreeViewItem* item);
  32341. /** Returns the treeview's Viewport object. */
  32342. Viewport* getViewport() const throw() { return viewport; }
  32343. /** Returns the number of pixels by which each nested level of the tree is indented.
  32344. @see setIndentSize
  32345. */
  32346. int getIndentSize() const throw() { return indentSize; }
  32347. /** Changes the distance by which each nested level of the tree is indented.
  32348. @see getIndentSize
  32349. */
  32350. void setIndentSize (const int newIndentSize);
  32351. /** Saves the current state of open/closed nodes so it can be restored later.
  32352. This takes a snapshot of which nodes have been explicitly opened or closed,
  32353. and records it as XML. To identify node objects it uses the
  32354. TreeViewItem::getUniqueName() method to create named paths. This
  32355. means that the same state of open/closed nodes can be restored to a
  32356. completely different instance of the tree, as long as it contains nodes
  32357. whose unique names are the same.
  32358. The caller is responsible for deleting the object that is returned.
  32359. @param alsoIncludeScrollPosition if this is true, the state will also
  32360. include information about where the
  32361. tree has been scrolled to vertically,
  32362. so this can also be restored
  32363. @see restoreOpennessState
  32364. */
  32365. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  32366. /** Restores a previously saved arrangement of open/closed nodes.
  32367. This will try to restore a snapshot of the tree's state that was created by
  32368. the getOpennessState() method. If any of the nodes named in the original
  32369. XML aren't present in this tree, they will be ignored.
  32370. @see getOpennessState
  32371. */
  32372. void restoreOpennessState (const XmlElement& newState);
  32373. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  32374. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32375. methods.
  32376. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32377. */
  32378. enum ColourIds
  32379. {
  32380. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  32381. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  32382. };
  32383. /** @internal */
  32384. void paint (Graphics& g);
  32385. /** @internal */
  32386. void resized();
  32387. /** @internal */
  32388. bool keyPressed (const KeyPress& key);
  32389. /** @internal */
  32390. void colourChanged();
  32391. juce_UseDebuggingNewOperator
  32392. private:
  32393. friend class TreeViewItem;
  32394. friend class TreeViewContentComponent;
  32395. Viewport* viewport;
  32396. CriticalSection nodeAlterationLock;
  32397. TreeViewItem* rootItem;
  32398. int indentSize;
  32399. bool defaultOpenness : 1;
  32400. bool needsRecalculating : 1;
  32401. bool rootItemVisible : 1;
  32402. bool multiSelectEnabled : 1;
  32403. bool openCloseButtonsVisible : 1;
  32404. void itemsChanged() throw();
  32405. void handleAsyncUpdate();
  32406. void moveSelectedRow (int delta);
  32407. void updateButtonUnderMouse (const MouseEvent& e);
  32408. TreeView (const TreeView&);
  32409. const TreeView& operator= (const TreeView&);
  32410. };
  32411. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  32412. /********* End of inlined file: juce_TreeView.h *********/
  32413. /**
  32414. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  32415. object.
  32416. @see KeyPressMappingSet
  32417. */
  32418. class JUCE_API KeyMappingEditorComponent : public Component,
  32419. public TreeViewItem,
  32420. public ChangeListener,
  32421. private ButtonListener
  32422. {
  32423. public:
  32424. /** Creates a KeyMappingEditorComponent.
  32425. @param mappingSet this is the set of mappings to display and
  32426. edit. Make sure the mappings object is not
  32427. deleted before this component!
  32428. @param showResetToDefaultButton if true, then at the bottom of the
  32429. list, the component will include a 'reset to
  32430. defaults' button.
  32431. */
  32432. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  32433. const bool showResetToDefaultButton);
  32434. /** Destructor. */
  32435. virtual ~KeyMappingEditorComponent();
  32436. /** Sets up the colours to use for parts of the component.
  32437. @param mainBackground colour to use for most of the background
  32438. @param textColour colour to use for the text
  32439. */
  32440. void setColours (const Colour& mainBackground,
  32441. const Colour& textColour);
  32442. /** Returns the KeyPressMappingSet that this component is acting upon.
  32443. */
  32444. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  32445. /** Can be overridden if some commands need to be excluded from the list.
  32446. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  32447. method to decide what to return, but you can override it to handle special cases.
  32448. */
  32449. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  32450. /** Can be overridden to indicate that some commands are shown as read-only.
  32451. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  32452. method to decide what to return, but you can override it to handle special cases.
  32453. */
  32454. virtual bool isCommandReadOnly (const CommandID commandID);
  32455. /** This can be overridden to let you change the format of the string used
  32456. to describe a keypress.
  32457. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  32458. keys that are triggered by something else externally. If you override the
  32459. method, be sure to let the base class's method handle keys you're not
  32460. interested in.
  32461. */
  32462. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  32463. /** @internal */
  32464. void parentHierarchyChanged();
  32465. /** @internal */
  32466. void resized();
  32467. /** @internal */
  32468. void changeListenerCallback (void*);
  32469. /** @internal */
  32470. bool mightContainSubItems();
  32471. /** @internal */
  32472. const String getUniqueName() const;
  32473. /** @internal */
  32474. void buttonClicked (Button* button);
  32475. juce_UseDebuggingNewOperator
  32476. private:
  32477. KeyPressMappingSet* mappings;
  32478. TreeView* tree;
  32479. friend class KeyMappingTreeViewItem;
  32480. friend class KeyCategoryTreeViewItem;
  32481. friend class KeyMappingItemComponent;
  32482. friend class KeyMappingChangeButton;
  32483. Colour backgroundColour, textColour;
  32484. TextButton* resetButton;
  32485. void assignNewKey (const CommandID commandID, int index);
  32486. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  32487. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  32488. };
  32489. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32490. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  32491. #endif
  32492. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  32493. #endif
  32494. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32495. #endif
  32496. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  32497. #endif
  32498. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32499. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  32500. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32501. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32502. /********* Start of inlined file: juce_MenuBarModel.h *********/
  32503. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32504. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  32505. class MenuBarModel;
  32506. /**
  32507. A class to receive callbacks when a MenuBarModel changes.
  32508. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  32509. */
  32510. class JUCE_API MenuBarModelListener
  32511. {
  32512. public:
  32513. /** Destructor. */
  32514. virtual ~MenuBarModelListener() {}
  32515. /** This callback is made when items are changed in the menu bar model.
  32516. */
  32517. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  32518. /** This callback is made when an application command is invoked that
  32519. is represented by one of the items in the menu bar model.
  32520. */
  32521. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  32522. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  32523. };
  32524. /**
  32525. A class for controlling MenuBar components.
  32526. This class is used to tell a MenuBar what menus to show, and to respond
  32527. to a menu being selected.
  32528. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  32529. */
  32530. class JUCE_API MenuBarModel : private AsyncUpdater,
  32531. private ApplicationCommandManagerListener
  32532. {
  32533. public:
  32534. MenuBarModel() throw();
  32535. /** Destructor. */
  32536. virtual ~MenuBarModel();
  32537. /** Call this when some of your menu items have changed.
  32538. This method will cause a callback to any MenuBarListener objects that
  32539. are registered with this model.
  32540. If this model is displaying items from an ApplicationCommandManager, you
  32541. can use the setApplicationCommandManagerToWatch() method to cause
  32542. change messages to be sent automatically when the ApplicationCommandManager
  32543. is changed.
  32544. @see addListener, removeListener, MenuBarListener
  32545. */
  32546. void menuItemsChanged();
  32547. /** Tells the menu bar to listen to the specified command manager, and to update
  32548. itself when the commands change.
  32549. This will also allow it to flash a menu name when a command from that menu
  32550. is invoked using a keystroke.
  32551. */
  32552. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  32553. /** Registers a listener for callbacks when the menu items in this model change.
  32554. The listener object will get callbacks when this object's menuItemsChanged()
  32555. method is called.
  32556. @see removeListener
  32557. */
  32558. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  32559. /** Removes a listener.
  32560. @see addListener
  32561. */
  32562. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  32563. /** This method must return a list of the names of the menus. */
  32564. virtual const StringArray getMenuBarNames() = 0;
  32565. /** This should return the popup menu to display for a given top-level menu.
  32566. @param topLevelMenuIndex the index of the top-level menu to show
  32567. @param menuName the name of the top-level menu item to show
  32568. */
  32569. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  32570. const String& menuName) = 0;
  32571. /** This is called when a menu item has been clicked on.
  32572. @param menuItemID the item ID of the PopupMenu item that was selected
  32573. @param topLevelMenuIndex the index of the top-level menu from which the item was
  32574. chosen (just in case you've used duplicate ID numbers
  32575. on more than one of the popup menus)
  32576. */
  32577. virtual void menuItemSelected (int menuItemID,
  32578. int topLevelMenuIndex) = 0;
  32579. #if JUCE_MAC || DOXYGEN
  32580. /** MAC ONLY - Sets the model that is currently being shown as the main
  32581. menu bar at the top of the screen on the Mac.
  32582. You can pass 0 to stop the current model being displayed. Be careful
  32583. not to delete a model while it is being used.
  32584. An optional extra menu can be specified, containing items to add to the top of
  32585. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  32586. an apple, it's the one next to it, with your application's name at the top
  32587. and the services menu etc on it). When one of these items is selected, the
  32588. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  32589. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  32590. object then newMenuBarModel must be non-null.
  32591. */
  32592. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  32593. const PopupMenu* extraAppleMenuItems = 0) throw();
  32594. /** MAC ONLY - Returns the menu model that is currently being shown as
  32595. the main menu bar.
  32596. */
  32597. static MenuBarModel* getMacMainMenu() throw();
  32598. #endif
  32599. /** @internal */
  32600. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  32601. /** @internal */
  32602. void applicationCommandListChanged();
  32603. /** @internal */
  32604. void handleAsyncUpdate();
  32605. juce_UseDebuggingNewOperator
  32606. private:
  32607. ApplicationCommandManager* manager;
  32608. SortedSet <void*> listeners;
  32609. MenuBarModel (const MenuBarModel&);
  32610. const MenuBarModel& operator= (const MenuBarModel&);
  32611. };
  32612. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  32613. /********* End of inlined file: juce_MenuBarModel.h *********/
  32614. /**
  32615. A menu bar component.
  32616. @see MenuBarModel
  32617. */
  32618. class JUCE_API MenuBarComponent : public Component,
  32619. private MenuBarModelListener,
  32620. private Timer
  32621. {
  32622. public:
  32623. /** Creates a menu bar.
  32624. @param model the model object to use to control this bar. You can
  32625. pass 0 into this if you like, and set the model later
  32626. using the setModel() method
  32627. */
  32628. MenuBarComponent (MenuBarModel* const model);
  32629. /** Destructor. */
  32630. ~MenuBarComponent();
  32631. /** Changes the model object to use to control the bar.
  32632. This can be 0, in which case the bar will be empty. Don't delete the object
  32633. that is passed-in while it's still being used by this MenuBar.
  32634. */
  32635. void setModel (MenuBarModel* const newModel);
  32636. /** Pops up one of the menu items.
  32637. This lets you manually open one of the menus - it could be triggered by a
  32638. key shortcut, for example.
  32639. */
  32640. void showMenu (const int menuIndex);
  32641. /** @internal */
  32642. void paint (Graphics& g);
  32643. /** @internal */
  32644. void resized();
  32645. /** @internal */
  32646. void mouseEnter (const MouseEvent& e);
  32647. /** @internal */
  32648. void mouseExit (const MouseEvent& e);
  32649. /** @internal */
  32650. void mouseDown (const MouseEvent& e);
  32651. /** @internal */
  32652. void mouseDrag (const MouseEvent& e);
  32653. /** @internal */
  32654. void mouseUp (const MouseEvent& e);
  32655. /** @internal */
  32656. void mouseMove (const MouseEvent& e);
  32657. /** @internal */
  32658. void inputAttemptWhenModal();
  32659. /** @internal */
  32660. void handleCommandMessage (int commandId);
  32661. /** @internal */
  32662. bool keyPressed (const KeyPress& key);
  32663. /** @internal */
  32664. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  32665. /** @internal */
  32666. void menuCommandInvoked (MenuBarModel* menuBarModel,
  32667. const ApplicationCommandTarget::InvocationInfo& info);
  32668. juce_UseDebuggingNewOperator
  32669. private:
  32670. MenuBarModel* model;
  32671. StringArray menuNames;
  32672. Array <int> xPositions;
  32673. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  32674. int lastMouseX, lastMouseY;
  32675. bool inModalState;
  32676. Component* currentPopup;
  32677. int getItemAt (int x, int y);
  32678. void updateItemUnderMouse (const int x, const int y);
  32679. void hideCurrentMenu();
  32680. void timerCallback();
  32681. void repaintMenuItem (int index);
  32682. MenuBarComponent (const MenuBarComponent&);
  32683. const MenuBarComponent& operator= (const MenuBarComponent&);
  32684. };
  32685. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  32686. /********* End of inlined file: juce_MenuBarComponent.h *********/
  32687. #endif
  32688. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  32689. #endif
  32690. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  32691. #endif
  32692. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  32693. #endif
  32694. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32695. /********* Start of inlined file: juce_ComponentDragger.h *********/
  32696. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32697. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32698. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32699. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32700. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32701. /**
  32702. A class that imposes restrictions on a Component's size or position.
  32703. This is used by classes such as ResizableCornerComponent,
  32704. ResizableBorderComponent and ResizableWindow.
  32705. The base class can impose some basic size and position limits, but you can
  32706. also subclass this for custom uses.
  32707. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  32708. */
  32709. class JUCE_API ComponentBoundsConstrainer
  32710. {
  32711. public:
  32712. /** When first created, the object will not impose any restrictions on the components. */
  32713. ComponentBoundsConstrainer() throw();
  32714. /** Destructor. */
  32715. virtual ~ComponentBoundsConstrainer();
  32716. /** Imposes a minimum width limit. */
  32717. void setMinimumWidth (const int minimumWidth) throw();
  32718. /** Returns the current minimum width. */
  32719. int getMinimumWidth() const throw() { return minW; }
  32720. /** Imposes a maximum width limit. */
  32721. void setMaximumWidth (const int maximumWidth) throw();
  32722. /** Returns the current maximum width. */
  32723. int getMaximumWidth() const throw() { return maxW; }
  32724. /** Imposes a minimum height limit. */
  32725. void setMinimumHeight (const int minimumHeight) throw();
  32726. /** Returns the current minimum height. */
  32727. int getMinimumHeight() const throw() { return minH; }
  32728. /** Imposes a maximum height limit. */
  32729. void setMaximumHeight (const int maximumHeight) throw();
  32730. /** Returns the current maximum height. */
  32731. int getMaximumHeight() const throw() { return maxH; }
  32732. /** Imposes a minimum width and height limit. */
  32733. void setMinimumSize (const int minimumWidth,
  32734. const int minimumHeight) throw();
  32735. /** Imposes a maximum width and height limit. */
  32736. void setMaximumSize (const int maximumWidth,
  32737. const int maximumHeight) throw();
  32738. /** Set all the maximum and minimum dimensions. */
  32739. void setSizeLimits (const int minimumWidth,
  32740. const int minimumHeight,
  32741. const int maximumWidth,
  32742. const int maximumHeight) throw();
  32743. /** Sets the amount by which the component is allowed to go off-screen.
  32744. The values indicate how many pixels must remain on-screen when dragged off
  32745. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  32746. when the component goes off the top of the screen, its y-position will be
  32747. clipped so that there are always at least 10 pixels on-screen. In other words,
  32748. the lowest y-position it can take would be (10 - the component's height).
  32749. If you pass 0 or less for one of these amounts, the component is allowed
  32750. to move beyond that edge completely, with no restrictions at all.
  32751. If you pass a very large number (i.e. larger that the dimensions of the
  32752. component itself), then the component won't be allowed to overlap that
  32753. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  32754. the component will bump into the left side of the screen and go no further.
  32755. */
  32756. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  32757. const int minimumWhenOffTheLeft,
  32758. const int minimumWhenOffTheBottom,
  32759. const int minimumWhenOffTheRight) throw();
  32760. /** Specifies a width-to-height ratio that the resizer should always maintain.
  32761. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  32762. will always be maintained as this multiple of the height.
  32763. @see setResizeLimits
  32764. */
  32765. void setFixedAspectRatio (const double widthOverHeight) throw();
  32766. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  32767. If no aspect ratio is being enforced, this will return 0.
  32768. */
  32769. double getFixedAspectRatio() const throw();
  32770. /** This callback changes the given co-ordinates to impose whatever the current
  32771. constraints are set to be.
  32772. @param x the x position that should be examined and adjusted
  32773. @param y the y position that should be examined and adjusted
  32774. @param w the width that should be examined and adjusted
  32775. @param h the height that should be examined and adjusted
  32776. @param previousBounds the component's current size
  32777. @param limits the region in which the component can be positioned
  32778. @param isStretchingTop whether the top edge of the component is being resized
  32779. @param isStretchingLeft whether the left edge of the component is being resized
  32780. @param isStretchingBottom whether the bottom edge of the component is being resized
  32781. @param isStretchingRight whether the right edge of the component is being resized
  32782. */
  32783. virtual void checkBounds (int& x, int& y, int& w, int& h,
  32784. const Rectangle& previousBounds,
  32785. const Rectangle& limits,
  32786. const bool isStretchingTop,
  32787. const bool isStretchingLeft,
  32788. const bool isStretchingBottom,
  32789. const bool isStretchingRight);
  32790. /** This callback happens when the resizer is about to start dragging. */
  32791. virtual void resizeStart();
  32792. /** This callback happens when the resizer has finished dragging. */
  32793. virtual void resizeEnd();
  32794. /** Checks the given bounds, and then sets the component to the corrected size. */
  32795. void setBoundsForComponent (Component* const component,
  32796. int x, int y, int w, int h,
  32797. const bool isStretchingTop,
  32798. const bool isStretchingLeft,
  32799. const bool isStretchingBottom,
  32800. const bool isStretchingRight);
  32801. /** Called by setBoundsForComponent() to apply a new constrained size to a
  32802. component.
  32803. By default this just calls setBounds(), but it virtual in case it's needed for
  32804. extremely cunning purposes.
  32805. */
  32806. virtual void applyBoundsToComponent (Component* component,
  32807. int x, int y, int w, int h);
  32808. juce_UseDebuggingNewOperator
  32809. private:
  32810. int minW, maxW, minH, maxH;
  32811. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  32812. double aspectRatio;
  32813. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  32814. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  32815. };
  32816. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  32817. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  32818. /**
  32819. An object to take care of the logic for dragging components around with the mouse.
  32820. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  32821. then in your mouseDrag() callback, call dragComponent().
  32822. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  32823. to limit the component's position and keep it on-screen.
  32824. e.g. @code
  32825. class MyDraggableComp
  32826. {
  32827. ComponentDragger myDragger;
  32828. void mouseDown (const MouseEvent& e)
  32829. {
  32830. myDragger.startDraggingComponent (this, 0);
  32831. }
  32832. void mouseDrag (const MouseEvent& e)
  32833. {
  32834. myDragger.dragComponent (this, e);
  32835. }
  32836. };
  32837. @endcode
  32838. */
  32839. class JUCE_API ComponentDragger
  32840. {
  32841. public:
  32842. /** Creates a ComponentDragger. */
  32843. ComponentDragger();
  32844. /** Destructor. */
  32845. virtual ~ComponentDragger();
  32846. /** Call this from your component's mouseDown() method, to prepare for dragging.
  32847. @param componentToDrag the component that you want to drag
  32848. @param constrainer a constrainer object to use to keep the component
  32849. from going offscreen
  32850. @see dragComponent
  32851. */
  32852. void startDraggingComponent (Component* const componentToDrag,
  32853. ComponentBoundsConstrainer* constrainer);
  32854. /** Call this from your mouseDrag() callback to move the component.
  32855. This will move the component, but will first check the validity of the
  32856. component's new position using the checkPosition() method, which you
  32857. can override if you need to enforce special positioning limits on the
  32858. component.
  32859. @param componentToDrag the component that you want to drag
  32860. @param e the current mouse-drag event
  32861. @see dragComponent
  32862. */
  32863. void dragComponent (Component* const componentToDrag,
  32864. const MouseEvent& e);
  32865. juce_UseDebuggingNewOperator
  32866. private:
  32867. ComponentBoundsConstrainer* constrainer;
  32868. int originalX, originalY;
  32869. };
  32870. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  32871. /********* End of inlined file: juce_ComponentDragger.h *********/
  32872. #endif
  32873. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32874. #endif
  32875. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32876. #endif
  32877. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32878. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  32879. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32880. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32881. /**
  32882. Components derived from this class can have files dropped onto them by an external application.
  32883. @see DragAndDropContainer
  32884. */
  32885. class JUCE_API FileDragAndDropTarget
  32886. {
  32887. public:
  32888. /** Destructor. */
  32889. virtual ~FileDragAndDropTarget() {}
  32890. /** Callback to check whether this target is interested in the set of files being offered.
  32891. Note that this will be called repeatedly when the user is dragging the mouse around over your
  32892. component, so don't do anything time-consuming in here, like opening the files to have a look
  32893. inside them!
  32894. @param files the set of (absolute) pathnames of the files that the user is dragging
  32895. @returns true if this component wants to receive the other callbacks regarging this
  32896. type of object; if it returns false, no other callbacks will be made.
  32897. */
  32898. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  32899. /** Callback to indicate that some files are being dragged over this component.
  32900. This gets called when the user moves the mouse into this component while dragging.
  32901. Use this callback as a trigger to make your component repaint itself to give the
  32902. user feedback about whether the files can be dropped here or not.
  32903. @param files the set of (absolute) pathnames of the files that the user is dragging
  32904. @param x the mouse x position, relative to this component
  32905. @param y the mouse y position, relative to this component
  32906. */
  32907. virtual void fileDragEnter (const StringArray& files, int x, int y);
  32908. /** Callback to indicate that the user is dragging some files over this component.
  32909. This gets called when the user moves the mouse over this component while dragging.
  32910. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32911. this lets you know what happens in-between.
  32912. @param files the set of (absolute) pathnames of the files that the user is dragging
  32913. @param x the mouse x position, relative to this component
  32914. @param y the mouse y position, relative to this component
  32915. */
  32916. virtual void fileDragMove (const StringArray& files, int x, int y);
  32917. /** Callback to indicate that the mouse has moved away from this component.
  32918. This gets called when the user moves the mouse out of this component while dragging
  32919. the files.
  32920. If you've used fileDragEnter() to repaint your component and give feedback, use this
  32921. as a signal to repaint it in its normal state.
  32922. @param files the set of (absolute) pathnames of the files that the user is dragging
  32923. */
  32924. virtual void fileDragExit (const StringArray& files);
  32925. /** Callback to indicate that the user has dropped the files onto this component.
  32926. When the user drops the files, this get called, and you can use the files in whatever
  32927. way is appropriate.
  32928. Note that after this is called, the fileDragExit method may not be called, so you should
  32929. clean up in here if there's anything you need to do when the drag finishes.
  32930. @param files the set of (absolute) pathnames of the files that the user is dragging
  32931. @param x the mouse x position, relative to this component
  32932. @param y the mouse y position, relative to this component
  32933. */
  32934. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  32935. };
  32936. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  32937. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  32938. #endif
  32939. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32940. /********* Start of inlined file: juce_LassoComponent.h *********/
  32941. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32942. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  32943. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  32944. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32945. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  32946. /** Manages a list of selectable items.
  32947. Use one of these to keep a track of things that the user has highlighted, like
  32948. icons or things in a list.
  32949. The class is templated so that you can use it to hold either a set of pointers
  32950. to objects, or a set of ID numbers or handles, for cases where each item may
  32951. not always have a corresponding object.
  32952. To be informed when items are selected/deselected, register a ChangeListener with
  32953. this object.
  32954. @see SelectableObject
  32955. */
  32956. template <class SelectableItemType>
  32957. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  32958. {
  32959. public:
  32960. /** Creates an empty set. */
  32961. SelectedItemSet()
  32962. {
  32963. }
  32964. /** Creates a set based on an array of items. */
  32965. SelectedItemSet (const Array <SelectableItemType>& items)
  32966. : selectedItems (items)
  32967. {
  32968. }
  32969. /** Creates a copy of another set. */
  32970. SelectedItemSet (const SelectedItemSet& other)
  32971. : selectedItems (other.selectedItems)
  32972. {
  32973. }
  32974. /** Creates a copy of another set. */
  32975. const SelectedItemSet& operator= (const SelectedItemSet& other)
  32976. {
  32977. if (selectedItems != other.selectedItems)
  32978. {
  32979. selectedItems = other.selectedItems;
  32980. changed();
  32981. }
  32982. return *this;
  32983. }
  32984. /** Destructor. */
  32985. ~SelectedItemSet()
  32986. {
  32987. }
  32988. /** Clears any other currently selected items, and selects this item.
  32989. If this item is already the only thing selected, no change notification
  32990. will be sent out.
  32991. @see addToSelection, addToSelectionBasedOnModifiers
  32992. */
  32993. void selectOnly (SelectableItemType item)
  32994. {
  32995. if (isSelected (item))
  32996. {
  32997. for (int i = selectedItems.size(); --i >= 0;)
  32998. {
  32999. if (selectedItems.getUnchecked(i) != item)
  33000. {
  33001. deselect (selectedItems.getUnchecked(i));
  33002. i = jmin (i, selectedItems.size());
  33003. }
  33004. }
  33005. }
  33006. else
  33007. {
  33008. deselectAll();
  33009. changed();
  33010. selectedItems.add (item);
  33011. itemSelected (item);
  33012. }
  33013. }
  33014. /** Selects an item.
  33015. If the item is already selected, no change notification will be sent out.
  33016. @see selectOnly, addToSelectionBasedOnModifiers
  33017. */
  33018. void addToSelection (SelectableItemType item)
  33019. {
  33020. if (! isSelected (item))
  33021. {
  33022. changed();
  33023. selectedItems.add (item);
  33024. itemSelected (item);
  33025. }
  33026. }
  33027. /** Selects or deselects an item.
  33028. This will use the modifier keys to decide whether to deselect other items
  33029. first.
  33030. So if the shift key is held down, the item will be added without deselecting
  33031. anything (same as calling addToSelection() )
  33032. If no modifiers are down, the current selection will be cleared first (same
  33033. as calling selectOnly() )
  33034. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  33035. so it'll be added to the set unless it's already there, in which case it'll be
  33036. deselected.
  33037. If the items that you're selecting can also be dragged, you may need to use the
  33038. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  33039. subtleties of this kind of usage.
  33040. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  33041. */
  33042. void addToSelectionBasedOnModifiers (SelectableItemType item,
  33043. const ModifierKeys& modifiers)
  33044. {
  33045. if (modifiers.isShiftDown())
  33046. {
  33047. addToSelection (item);
  33048. }
  33049. else if (modifiers.isCommandDown())
  33050. {
  33051. if (isSelected (item))
  33052. deselect (item);
  33053. else
  33054. addToSelection (item);
  33055. }
  33056. else
  33057. {
  33058. selectOnly (item);
  33059. }
  33060. }
  33061. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  33062. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  33063. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  33064. makes it easy to handle multiple-selection of sets of objects that can also
  33065. be dragged.
  33066. For example, if you have several items already selected, and you click on
  33067. one of them (without dragging), then you'd expect this to deselect the other, and
  33068. just select the item you clicked on. But if you had clicked on this item and
  33069. dragged it, you'd have expected them all to stay selected.
  33070. When you call this method, you'll need to store the boolean result, because the
  33071. addToSelectionOnMouseUp() method will need to be know this value.
  33072. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  33073. */
  33074. bool addToSelectionOnMouseDown (SelectableItemType item,
  33075. const ModifierKeys& modifiers)
  33076. {
  33077. if (isSelected (item))
  33078. {
  33079. return ! modifiers.isPopupMenu();
  33080. }
  33081. else
  33082. {
  33083. addToSelectionBasedOnModifiers (item, modifiers);
  33084. return false;
  33085. }
  33086. }
  33087. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  33088. Call this during a mouseUp callback, when you have previously called the
  33089. addToSelectionOnMouseDown() method during your mouseDown event.
  33090. See addToSelectionOnMouseDown() for more info
  33091. @param item the item to select (or deselect)
  33092. @param modifiers the modifiers from the mouse-up event
  33093. @param wasItemDragged true if your item was dragged during the mouse click
  33094. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  33095. back from the addToSelectionOnMouseDown() call that you
  33096. should have made during the matching mouseDown event
  33097. */
  33098. void addToSelectionOnMouseUp (SelectableItemType item,
  33099. const ModifierKeys& modifiers,
  33100. const bool wasItemDragged,
  33101. const bool resultOfMouseDownSelectMethod)
  33102. {
  33103. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  33104. addToSelectionBasedOnModifiers (item, modifiers);
  33105. }
  33106. /** Deselects an item. */
  33107. void deselect (SelectableItemType item)
  33108. {
  33109. const int i = selectedItems.indexOf (item);
  33110. if (i >= 0)
  33111. {
  33112. changed();
  33113. itemDeselected (selectedItems.remove (i));
  33114. }
  33115. }
  33116. /** Deselects all items. */
  33117. void deselectAll()
  33118. {
  33119. if (selectedItems.size() > 0)
  33120. {
  33121. changed();
  33122. for (int i = selectedItems.size(); --i >= 0;)
  33123. {
  33124. itemDeselected (selectedItems.remove (i));
  33125. i = jmin (i, selectedItems.size());
  33126. }
  33127. }
  33128. }
  33129. /** Returns the number of currently selected items.
  33130. @see getSelectedItem
  33131. */
  33132. int getNumSelected() const throw()
  33133. {
  33134. return selectedItems.size();
  33135. }
  33136. /** Returns one of the currently selected items.
  33137. Returns 0 if the index is out-of-range.
  33138. @see getNumSelected
  33139. */
  33140. SelectableItemType getSelectedItem (const int index) const throw()
  33141. {
  33142. return selectedItems [index];
  33143. }
  33144. /** True if this item is currently selected. */
  33145. bool isSelected (const SelectableItemType item) const throw()
  33146. {
  33147. return selectedItems.contains (item);
  33148. }
  33149. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  33150. /** Can be overridden to do special handling when an item is selected.
  33151. For example, if the item is an object, you might want to call it and tell
  33152. it that it's being selected.
  33153. */
  33154. virtual void itemSelected (SelectableItemType item) {}
  33155. /** Can be overridden to do special handling when an item is deselected.
  33156. For example, if the item is an object, you might want to call it and tell
  33157. it that it's being deselected.
  33158. */
  33159. virtual void itemDeselected (SelectableItemType item) {}
  33160. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  33161. */
  33162. void changed (const bool synchronous = false)
  33163. {
  33164. if (synchronous)
  33165. sendSynchronousChangeMessage (this);
  33166. else
  33167. sendChangeMessage (this);
  33168. }
  33169. juce_UseDebuggingNewOperator
  33170. private:
  33171. Array <SelectableItemType> selectedItems;
  33172. };
  33173. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33174. /********* End of inlined file: juce_SelectedItemSet.h *********/
  33175. /**
  33176. A class used by the LassoComponent to manage the things that it selects.
  33177. This allows the LassoComponent to find out which items are within the lasso,
  33178. and to change the list of selected items.
  33179. @see LassoComponent, SelectedItemSet
  33180. */
  33181. template <class SelectableItemType>
  33182. class LassoSource
  33183. {
  33184. public:
  33185. /** Destructor. */
  33186. virtual ~LassoSource() {}
  33187. /** Returns the set of items that lie within a given lassoable region.
  33188. Your implementation of this method must find all the relevent items that lie
  33189. within the given rectangle. and add them to the itemsFound array.
  33190. The co-ordinates are relative to the top-left of the lasso component's parent
  33191. component. (i.e. they are the same as the size and position of the lasso
  33192. component itself).
  33193. */
  33194. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  33195. int x, int y, int width, int height) = 0;
  33196. /** Returns the SelectedItemSet that the lasso should update.
  33197. This set will be continuously updated by the LassoComponent as it gets
  33198. dragged around, so make sure that you've got a ChangeListener attached to
  33199. the set so that your UI objects will know when the selection changes and
  33200. be able to update themselves appropriately.
  33201. */
  33202. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  33203. };
  33204. /**
  33205. A component that acts as a rectangular selection region, which you drag with
  33206. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  33207. To use one of these:
  33208. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  33209. component, and call its beginLasso() method, giving it a
  33210. suitable LassoSource object that it can use to find out which items are in
  33211. the active area.
  33212. - Each time your parent component gets a mouseDrag event, call dragLasso()
  33213. to update the lasso's position - it will use its LassoSource to calculate and
  33214. update the current selection.
  33215. - After the drag has finished and you get a mouseUp callback, you should call
  33216. endLasso() to clean up. This will make the lasso component invisible, and you
  33217. can remove it from the parent component, or delete it.
  33218. The class takes into account the modifier keys that are being held down while
  33219. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  33220. be added to the original selection; if ctrl or command is pressed, they will be
  33221. xor'ed with any previously selected items.
  33222. @see LassoSource, SelectedItemSet
  33223. */
  33224. template <class SelectableItemType>
  33225. class LassoComponent : public Component
  33226. {
  33227. public:
  33228. /** Creates a Lasso component.
  33229. The fill colour is used to fill the lasso'ed rectangle, and the outline
  33230. colour is used to draw a line around its edge.
  33231. */
  33232. LassoComponent (const int outlineThickness_ = 1)
  33233. : source (0),
  33234. outlineThickness (outlineThickness_)
  33235. {
  33236. }
  33237. /** Destructor. */
  33238. ~LassoComponent()
  33239. {
  33240. }
  33241. /** Call this in your mouseDown event, to initialise a drag.
  33242. Pass in a suitable LassoSource object which the lasso will use to find
  33243. the items and change the selection.
  33244. After using this method to initialise the lasso, repeatedly call dragLasso()
  33245. in your component's mouseDrag callback.
  33246. @see dragLasso, endLasso, LassoSource
  33247. */
  33248. void beginLasso (const MouseEvent& e,
  33249. LassoSource <SelectableItemType>* const lassoSource)
  33250. {
  33251. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  33252. jassert (lassoSource != 0); // the source can't be null!
  33253. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  33254. source = lassoSource;
  33255. if (lassoSource != 0)
  33256. originalSelection = lassoSource->getLassoSelection().getItemArray();
  33257. setSize (0, 0);
  33258. }
  33259. /** Call this in your mouseDrag event, to update the lasso's position.
  33260. This must be repeatedly calling when the mouse is dragged, after you've
  33261. first initialised the lasso with beginLasso().
  33262. This method takes into account the modifier keys that are being held down, so
  33263. if shift is pressed, then the lassoed items will be added to any that were
  33264. previously selected; if ctrl or command is pressed, then they will be xor'ed
  33265. with previously selected items.
  33266. @see beginLasso, endLasso
  33267. */
  33268. void dragLasso (const MouseEvent& e)
  33269. {
  33270. if (source != 0)
  33271. {
  33272. const int x1 = e.getMouseDownX();
  33273. const int y1 = e.getMouseDownY();
  33274. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  33275. setVisible (true);
  33276. Array <SelectableItemType> itemsInLasso;
  33277. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  33278. if (e.mods.isShiftDown())
  33279. {
  33280. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  33281. itemsInLasso.addArray (originalSelection);
  33282. }
  33283. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  33284. {
  33285. Array <SelectableItemType> originalMinusNew (originalSelection);
  33286. originalMinusNew.removeValuesIn (itemsInLasso);
  33287. itemsInLasso.removeValuesIn (originalSelection);
  33288. itemsInLasso.addArray (originalMinusNew);
  33289. }
  33290. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  33291. }
  33292. }
  33293. /** Call this in your mouseUp event, after the lasso has been dragged.
  33294. @see beginLasso, dragLasso
  33295. */
  33296. void endLasso()
  33297. {
  33298. source = 0;
  33299. originalSelection.clear();
  33300. setVisible (false);
  33301. }
  33302. /** A set of colour IDs to use to change the colour of various aspects of the label.
  33303. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33304. methods.
  33305. Note that you can also use the constants from TextEditor::ColourIds to change the
  33306. colour of the text editor that is opened when a label is editable.
  33307. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33308. */
  33309. enum ColourIds
  33310. {
  33311. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  33312. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  33313. };
  33314. /** @internal */
  33315. void paint (Graphics& g)
  33316. {
  33317. g.fillAll (findColour (lassoFillColourId));
  33318. g.setColour (findColour (lassoOutlineColourId));
  33319. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33320. // this suggests that you've left a lasso comp lying around after the
  33321. // mouse drag has finished.. Be careful to call endLasso() when you get a
  33322. // mouse-up event.
  33323. jassert (isMouseButtonDownAnywhere());
  33324. }
  33325. /** @internal */
  33326. bool hitTest (int x, int y) { return false; }
  33327. juce_UseDebuggingNewOperator
  33328. private:
  33329. Array <SelectableItemType> originalSelection;
  33330. LassoSource <SelectableItemType>* source;
  33331. int outlineThickness;
  33332. };
  33333. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33334. /********* End of inlined file: juce_LassoComponent.h *********/
  33335. #endif
  33336. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  33337. #endif
  33338. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  33339. #endif
  33340. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33341. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  33342. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33343. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33344. /**
  33345. Monitors a component for mouse activity, and triggers a callback
  33346. when the mouse hovers in one place for a specified length of time.
  33347. To use a hover-detector, just create one and call its setHoverComponent()
  33348. method to start it watching a component. You can call setHoverComponent (0)
  33349. to make it inactive.
  33350. (Be careful not to delete a component that's being monitored without first
  33351. stopping or deleting the hover detector).
  33352. */
  33353. class JUCE_API MouseHoverDetector
  33354. {
  33355. public:
  33356. /** Creates a hover detector.
  33357. Initially the object is inactive, and you need to tell it which component
  33358. to monitor, using the setHoverComponent() method.
  33359. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  33360. needs to stay still before the mouseHovered() method
  33361. is invoked. You can change this setting later with
  33362. the setHoverTimeMillisecs() method
  33363. */
  33364. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  33365. /** Destructor. */
  33366. virtual ~MouseHoverDetector();
  33367. /** Changes the time for which the mouse has to stay still before it's considered
  33368. to be hovering.
  33369. */
  33370. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  33371. /** Changes the component that's being monitored for hovering.
  33372. Be careful not to delete a component that's being monitored without first
  33373. stopping or deleting the hover detector.
  33374. */
  33375. void setHoverComponent (Component* const newSourceComponent);
  33376. protected:
  33377. /** Called back when the mouse hovers.
  33378. After the mouse has stayed still over the component for the length of time
  33379. specified by setHoverTimeMillisecs(), this method will be invoked.
  33380. When the mouse is first moved after this callback has occurred, the
  33381. mouseMovedAfterHover() method will be called.
  33382. @param mouseX the mouse's X position relative to the component being monitored
  33383. @param mouseY the mouse's Y position relative to the component being monitored
  33384. */
  33385. virtual void mouseHovered (int mouseX,
  33386. int mouseY) = 0;
  33387. /** Called when the mouse is moved away after just having hovered. */
  33388. virtual void mouseMovedAfterHover() = 0;
  33389. private:
  33390. class JUCE_API HoverDetectorInternal : public MouseListener,
  33391. public Timer
  33392. {
  33393. public:
  33394. MouseHoverDetector* owner;
  33395. int lastX, lastY;
  33396. void timerCallback();
  33397. void mouseEnter (const MouseEvent&);
  33398. void mouseExit (const MouseEvent&);
  33399. void mouseDown (const MouseEvent&);
  33400. void mouseUp (const MouseEvent&);
  33401. void mouseMove (const MouseEvent&);
  33402. void mouseWheelMove (const MouseEvent&, float, float);
  33403. } internalTimer;
  33404. friend class HoverDetectorInternal;
  33405. Component* source;
  33406. int hoverTimeMillisecs;
  33407. bool hasJustHovered;
  33408. void hoverTimerCallback();
  33409. void checkJustHoveredCallback();
  33410. };
  33411. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  33412. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  33413. #endif
  33414. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  33415. #endif
  33416. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  33417. #endif
  33418. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  33419. #endif
  33420. #ifndef __JUCE_LABEL_JUCEHEADER__
  33421. #endif
  33422. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33423. #endif
  33424. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33425. /********* Start of inlined file: juce_ProgressBar.h *********/
  33426. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33427. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  33428. /**
  33429. A progress bar component.
  33430. To use this, just create one and make it visible. It'll run its own timer
  33431. to keep an eye on a variable that you give it, and will automatically
  33432. redraw itself when the variable changes.
  33433. For an easy way of running a background task with a dialog box showing its
  33434. progress, see the ThreadWithProgressWindow class.
  33435. @see ThreadWithProgressWindow
  33436. */
  33437. class JUCE_API ProgressBar : public Component,
  33438. public SettableTooltipClient,
  33439. private Timer
  33440. {
  33441. public:
  33442. /** Creates a ProgressBar.
  33443. @param progress pass in a reference to a double that you're going to
  33444. update with your task's progress. The ProgressBar will
  33445. monitor the value of this variable and will redraw itself
  33446. when the value changes. The range is from 0 to 1.0. Obviously
  33447. you'd better be careful not to delete this variable while the
  33448. ProgressBar still exists!
  33449. */
  33450. ProgressBar (double& progress);
  33451. /** Destructor. */
  33452. ~ProgressBar();
  33453. /** Turns the percentage display on or off.
  33454. By default this is on, and the progress bar will display a text string showing
  33455. its current percentage.
  33456. */
  33457. void setPercentageDisplay (const bool shouldDisplayPercentage);
  33458. /** Gives the progress bar a string to display inside it.
  33459. If you call this, it will turn off the percentage display.
  33460. @see setPercentageDisplay
  33461. */
  33462. void setTextToDisplay (const String& text);
  33463. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  33464. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33465. methods.
  33466. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33467. */
  33468. enum ColourIds
  33469. {
  33470. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  33471. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  33472. classes will probably use variations on this colour. */
  33473. };
  33474. juce_UseDebuggingNewOperator
  33475. protected:
  33476. /** @internal */
  33477. void paint (Graphics& g);
  33478. /** @internal */
  33479. void lookAndFeelChanged();
  33480. /** @internal */
  33481. void visibilityChanged();
  33482. /** @internal */
  33483. void colourChanged();
  33484. private:
  33485. double& progress;
  33486. double currentValue;
  33487. bool displayPercentage;
  33488. String displayedMessage, currentMessage;
  33489. void timerCallback();
  33490. ProgressBar (const ProgressBar&);
  33491. const ProgressBar& operator= (const ProgressBar&);
  33492. };
  33493. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  33494. /********* End of inlined file: juce_ProgressBar.h *********/
  33495. #endif
  33496. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33497. /********* Start of inlined file: juce_Slider.h *********/
  33498. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33499. #define __JUCE_SLIDER_JUCEHEADER__
  33500. /********* Start of inlined file: juce_SliderListener.h *********/
  33501. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33502. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  33503. class Slider;
  33504. /**
  33505. A class for receiving callbacks from a Slider.
  33506. To be told when a slider's value changes, you can register a SliderListener
  33507. object using Slider::addListener().
  33508. @see Slider::addListener, Slider::removeListener
  33509. */
  33510. class JUCE_API SliderListener
  33511. {
  33512. public:
  33513. /** Destructor. */
  33514. virtual ~SliderListener() {}
  33515. /** Called when the slider's value is changed.
  33516. This may be caused by dragging it, or by typing in its text entry box,
  33517. or by a call to Slider::setValue().
  33518. You can find out the new value using Slider::getValue().
  33519. @see Slider::valueChanged
  33520. */
  33521. virtual void sliderValueChanged (Slider* slider) = 0;
  33522. /** Called when the slider is about to be dragged.
  33523. This is called when a drag begins, then it's followed by multiple calls
  33524. to sliderValueChanged(), and then sliderDragEnded() is called after the
  33525. user lets go.
  33526. @see sliderDragEnded, Slider::startedDragging
  33527. */
  33528. virtual void sliderDragStarted (Slider* slider);
  33529. /** Called after a drag operation has finished.
  33530. @see sliderDragStarted, Slider::stoppedDragging
  33531. */
  33532. virtual void sliderDragEnded (Slider* slider);
  33533. };
  33534. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  33535. /********* End of inlined file: juce_SliderListener.h *********/
  33536. /**
  33537. A slider control for changing a value.
  33538. The slider can be horizontal, vertical, or rotary, and can optionally have
  33539. a text-box inside it to show an editable display of the current value.
  33540. To use it, create a Slider object and use the setSliderStyle() method
  33541. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  33542. To define the values that it can be set to, see the setRange() and setValue() methods.
  33543. There are also lots of custom tweaks you can do by subclassing and overriding
  33544. some of the virtual methods, such as changing the scaling, changing the format of
  33545. the text display, custom ways of limiting the values, etc.
  33546. You can register SliderListeners with a slider, which will be informed when the value
  33547. changes, or a subclass can override valueChanged() to be informed synchronously.
  33548. @see SliderListener
  33549. */
  33550. class JUCE_API Slider : public Component,
  33551. public SettableTooltipClient,
  33552. private AsyncUpdater,
  33553. private ButtonListener,
  33554. private LabelListener
  33555. {
  33556. public:
  33557. /** Creates a slider.
  33558. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  33559. setRange(), etc.
  33560. */
  33561. Slider (const String& componentName);
  33562. /** Destructor. */
  33563. ~Slider();
  33564. /** The types of slider available.
  33565. @see setSliderStyle, setRotaryParameters
  33566. */
  33567. enum SliderStyle
  33568. {
  33569. LinearHorizontal, /**< A traditional horizontal slider. */
  33570. LinearVertical, /**< A traditional vertical slider. */
  33571. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  33572. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  33573. @see setRotaryParameters */
  33574. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  33575. @see setRotaryParameters */
  33576. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  33577. @see setRotaryParameters */
  33578. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  33579. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33580. @see setMinValue, setMaxValue */
  33581. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33582. @see setMinValue, setMaxValue */
  33583. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  33584. value, with the current value being somewhere between them.
  33585. @see setMinValue, setMaxValue */
  33586. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  33587. value, with the current value being somewhere between them.
  33588. @see setMinValue, setMaxValue */
  33589. };
  33590. /** Changes the type of slider interface being used.
  33591. @param newStyle the type of interface
  33592. @see setRotaryParameters, setVelocityBasedMode,
  33593. */
  33594. void setSliderStyle (const SliderStyle newStyle);
  33595. /** Returns the slider's current style.
  33596. @see setSliderStyle
  33597. */
  33598. SliderStyle getSliderStyle() const throw() { return style; }
  33599. /** Changes the properties of a rotary slider.
  33600. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  33601. the slider's minimum value is represented
  33602. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  33603. the slider's maximum value is represented. This must be
  33604. greater than startAngleRadians
  33605. @param stopAtEnd if true, then when the slider is dragged around past the
  33606. minimum or maximum, it'll stop there; if false, it'll wrap
  33607. back to the opposite value
  33608. */
  33609. void setRotaryParameters (const float startAngleRadians,
  33610. const float endAngleRadians,
  33611. const bool stopAtEnd);
  33612. /** Sets the distance the mouse has to move to drag the slider across
  33613. the full extent of its range.
  33614. This only applies when in modes like RotaryHorizontalDrag, where it's using
  33615. relative mouse movements to adjust the slider.
  33616. */
  33617. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  33618. /** Changes the way the the mouse is used when dragging the slider.
  33619. If true, this will turn on velocity-sensitive dragging, so that
  33620. the faster the mouse moves, the bigger the movement to the slider. This
  33621. helps when making accurate adjustments if the slider's range is quite large.
  33622. If false, the slider will just try to snap to wherever the mouse is.
  33623. */
  33624. void setVelocityBasedMode (const bool isVelocityBased) throw();
  33625. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  33626. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  33627. or if you're holding down ctrl.
  33628. @param sensitivity higher values than 1.0 increase the range of acceleration used
  33629. @param threshold the minimum number of pixels that the mouse needs to move for it
  33630. to be treated as a movement
  33631. @param offset values greater than 0.0 increase the minimum speed that will be used when
  33632. the threshold is reached
  33633. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  33634. key to toggle velocity-sensitive mode
  33635. */
  33636. void setVelocityModeParameters (const double sensitivity = 1.0,
  33637. const int threshold = 1,
  33638. const double offset = 0.0,
  33639. const bool userCanPressKeyToSwapMode = true) throw();
  33640. /** Sets up a skew factor to alter the way values are distributed.
  33641. You may want to use a range of values on the slider where more accuracy
  33642. is required towards one end of the range, so this will logarithmically
  33643. spread the values across the length of the slider.
  33644. If the factor is < 1.0, the lower end of the range will fill more of the
  33645. slider's length; if the factor is > 1.0, the upper end of the range
  33646. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  33647. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  33648. method instead.
  33649. @see getSkewFactor, setSkewFactorFromMidPoint
  33650. */
  33651. void setSkewFactor (const double factor) throw();
  33652. /** Sets up a skew factor to alter the way values are distributed.
  33653. This allows you to specify the slider value that should appear in the
  33654. centre of the slider's visible range.
  33655. @see setSkewFactor, getSkewFactor
  33656. */
  33657. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  33658. /** Returns the current skew factor.
  33659. See setSkewFactor for more info.
  33660. @see setSkewFactor, setSkewFactorFromMidPoint
  33661. */
  33662. double getSkewFactor() const throw() { return skewFactor; }
  33663. /** Used by setIncDecButtonsMode().
  33664. */
  33665. enum IncDecButtonMode
  33666. {
  33667. incDecButtonsNotDraggable,
  33668. incDecButtonsDraggable_AutoDirection,
  33669. incDecButtonsDraggable_Horizontal,
  33670. incDecButtonsDraggable_Vertical
  33671. };
  33672. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  33673. can be dragged on the buttons to drag the values.
  33674. By default this is turned off. When enabled, clicking on the buttons still works
  33675. them as normal, but by holding down the mouse on a button and dragging it a little
  33676. distance, it flips into a mode where the value can be dragged. The drag direction can
  33677. either be set explicitly to be vertical or horizontal, or can be set to
  33678. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  33679. are side-by-side or above each other.
  33680. */
  33681. void setIncDecButtonsMode (const IncDecButtonMode mode);
  33682. /** The position of the slider's text-entry box.
  33683. @see setTextBoxStyle
  33684. */
  33685. enum TextEntryBoxPosition
  33686. {
  33687. NoTextBox, /**< Doesn't display a text box. */
  33688. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  33689. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  33690. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  33691. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  33692. };
  33693. /** Changes the location and properties of the text-entry box.
  33694. @param newPosition where it should go (or NoTextBox to not have one at all)
  33695. @param isReadOnly if true, it's a read-only display
  33696. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  33697. room for the slider as well!
  33698. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  33699. room for the slider as well!
  33700. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  33701. */
  33702. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  33703. const bool isReadOnly,
  33704. const int textEntryBoxWidth,
  33705. const int textEntryBoxHeight);
  33706. /** Returns the status of the text-box.
  33707. @see setTextBoxStyle
  33708. */
  33709. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  33710. /** Returns the width used for the text-box.
  33711. @see setTextBoxStyle
  33712. */
  33713. int getTextBoxWidth() const throw() { return textBoxWidth; }
  33714. /** Returns the height used for the text-box.
  33715. @see setTextBoxStyle
  33716. */
  33717. int getTextBoxHeight() const throw() { return textBoxHeight; }
  33718. /** Makes the text-box editable.
  33719. By default this is true, and the user can enter values into the textbox,
  33720. but it can be turned off if that's not suitable.
  33721. @see setTextBoxStyle, getValueFromText, getTextFromValue
  33722. */
  33723. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  33724. /** Returns true if the text-box is read-only.
  33725. @see setTextBoxStyle
  33726. */
  33727. bool isTextBoxEditable() const throw() { return editableText; }
  33728. /** If the text-box is editable, this will give it the focus so that the user can
  33729. type directly into it.
  33730. This is basically the effect as the user clicking on it.
  33731. */
  33732. void showTextBox();
  33733. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  33734. focus away from it.
  33735. @param discardCurrentEditorContents if true, the slider's value will be left
  33736. unchanged; if false, the current contents of the
  33737. text editor will be used to set the slider position
  33738. before it is hidden.
  33739. */
  33740. void hideTextBox (const bool discardCurrentEditorContents);
  33741. /** Changes the slider's current value.
  33742. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33743. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33744. want to handle it.
  33745. @param newValue the new value to set - this will be restricted by the
  33746. minimum and maximum range, and will be snapped to the
  33747. nearest interval if one has been set
  33748. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33749. any SliderListeners or the valueChanged() method
  33750. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33751. synchronously; if false, it will be asynchronous
  33752. */
  33753. void setValue (double newValue,
  33754. const bool sendUpdateMessage = true,
  33755. const bool sendMessageSynchronously = false);
  33756. /** Returns the slider's current value. */
  33757. double getValue() const throw();
  33758. /** Sets the limits that the slider's value can take.
  33759. @param newMinimum the lowest value allowed
  33760. @param newMaximum the highest value allowed
  33761. @param newInterval the steps in which the value is allowed to increase - if this
  33762. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  33763. */
  33764. void setRange (const double newMinimum,
  33765. const double newMaximum,
  33766. const double newInterval = 0);
  33767. /** Returns the current maximum value.
  33768. @see setRange
  33769. */
  33770. double getMaximum() const throw() { return maximum; }
  33771. /** Returns the current minimum value.
  33772. @see setRange
  33773. */
  33774. double getMinimum() const throw() { return minimum; }
  33775. /** Returns the current step-size for values.
  33776. @see setRange
  33777. */
  33778. double getInterval() const throw() { return interval; }
  33779. /** For a slider with two or three thumbs, this returns the lower of its values.
  33780. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33781. A slider with three values also uses the normal getValue() and setValue() methods to
  33782. control the middle value.
  33783. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33784. */
  33785. double getMinValue() const throw();
  33786. /** For a slider with two or three thumbs, this sets the lower of its values.
  33787. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33788. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33789. want to handle it.
  33790. @param newValue the new value to set - this will be restricted by the
  33791. minimum and maximum range, and the max value (in a two-value
  33792. slider) or the mid value (in a three-value slider), and
  33793. will be snapped to the nearest interval if one has been set.
  33794. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33795. any SliderListeners or the valueChanged() method
  33796. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33797. synchronously; if false, it will be asynchronous
  33798. @see getMinValue, setMaxValue, setValue
  33799. */
  33800. void setMinValue (double newValue,
  33801. const bool sendUpdateMessage = true,
  33802. const bool sendMessageSynchronously = false);
  33803. /** For a slider with two or three thumbs, this returns the higher of its values.
  33804. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33805. A slider with three values also uses the normal getValue() and setValue() methods to
  33806. control the middle value.
  33807. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33808. */
  33809. double getMaxValue() const throw();
  33810. /** For a slider with two or three thumbs, this sets the lower of its values.
  33811. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33812. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33813. want to handle it.
  33814. @param newValue the new value to set - this will be restricted by the
  33815. minimum and maximum range, and the max value (in a two-value
  33816. slider) or the mid value (in a three-value slider), and
  33817. will be snapped to the nearest interval if one has been set.
  33818. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33819. any SliderListeners or the valueChanged() method
  33820. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33821. synchronously; if false, it will be asynchronous
  33822. @see getMaxValue, setMinValue, setValue
  33823. */
  33824. void setMaxValue (double newValue,
  33825. const bool sendUpdateMessage = true,
  33826. const bool sendMessageSynchronously = false);
  33827. /** Adds a listener to be called when this slider's value changes. */
  33828. void addListener (SliderListener* const listener) throw();
  33829. /** Removes a previously-registered listener. */
  33830. void removeListener (SliderListener* const listener) throw();
  33831. /** This lets you choose whether double-clicking moves the slider to a given position.
  33832. By default this is turned off, but it's handy if you want a double-click to act
  33833. as a quick way of resetting a slider. Just pass in the value you want it to
  33834. go to when double-clicked.
  33835. @see getDoubleClickReturnValue
  33836. */
  33837. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  33838. const double valueToSetOnDoubleClick) throw();
  33839. /** Returns the values last set by setDoubleClickReturnValue() method.
  33840. Sets isEnabled to true if double-click is enabled, and returns the value
  33841. that was set.
  33842. @see setDoubleClickReturnValue
  33843. */
  33844. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  33845. /** Tells the slider whether to keep sending change messages while the user
  33846. is dragging the slider.
  33847. If set to true, a change message will only be sent when the user has
  33848. dragged the slider and let go. If set to false (the default), then messages
  33849. will be continuously sent as they drag it while the mouse button is still
  33850. held down.
  33851. */
  33852. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  33853. /** This lets you change whether the slider thumb jumps to the mouse position
  33854. when you click.
  33855. By default, this is true. If it's false, then the slider moves with relative
  33856. motion when you drag it.
  33857. This only applies to linear bars, and won't affect two- or three- value
  33858. sliders.
  33859. */
  33860. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  33861. /** If enabled, this gives the slider a pop-up bubble which appears while the
  33862. slider is being dragged.
  33863. This can be handy if your slider doesn't have a text-box, so that users can
  33864. see the value just when they're changing it.
  33865. If you pass a component as the parentComponentToUse parameter, the pop-up
  33866. bubble will be added as a child of that component when it's needed. If you
  33867. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  33868. transparent window, so if you're using an OS that can't do transparent windows
  33869. you'll have to add it to a parent component instead).
  33870. */
  33871. void setPopupDisplayEnabled (const bool isEnabled,
  33872. Component* const parentComponentToUse) throw();
  33873. /** If this is set to true, then right-clicking on the slider will pop-up
  33874. a menu to let the user change the way it works.
  33875. By default this is turned off, but when turned on, the menu will include
  33876. things like velocity sensitivity, and for rotary sliders, whether they
  33877. use a linear or rotary mouse-drag to move them.
  33878. */
  33879. void setPopupMenuEnabled (const bool menuEnabled) throw();
  33880. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  33881. By default it's enabled.
  33882. */
  33883. void setScrollWheelEnabled (const bool enabled) throw();
  33884. /** Returns a number to indicate which thumb is currently being dragged by the
  33885. mouse.
  33886. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  33887. the maximum-value thumb, or -1 if none is currently down.
  33888. */
  33889. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  33890. /** Callback to indicate that the user is about to start dragging the slider.
  33891. @see SliderListener::sliderDragStarted
  33892. */
  33893. virtual void startedDragging();
  33894. /** Callback to indicate that the user has just stopped dragging the slider.
  33895. @see SliderListener::sliderDragEnded
  33896. */
  33897. virtual void stoppedDragging();
  33898. /** Callback to indicate that the user has just moved the slider.
  33899. @see SliderListener::sliderValueChanged
  33900. */
  33901. virtual void valueChanged();
  33902. /** Callback to indicate that the user has just moved the slider.
  33903. Note - the valueChanged() method has changed its format and now no longer has
  33904. any parameters. Update your code to use the new version.
  33905. This version has been left here with an int as its return value to cause
  33906. a syntax error if you've got existing code that uses the old version.
  33907. */
  33908. virtual int valueChanged (double) { jassertfalse; return 0; }
  33909. /** Subclasses can override this to convert a text string to a value.
  33910. When the user enters something into the text-entry box, this method is
  33911. called to convert it to a value.
  33912. The default routine just tries to convert it to a double.
  33913. @see getTextFromValue
  33914. */
  33915. virtual double getValueFromText (const String& text);
  33916. /** Turns the slider's current value into a text string.
  33917. Subclasses can override this to customise the formatting of the text-entry box.
  33918. The default implementation just turns the value into a string, using
  33919. a number of decimal places based on the range interval. If a suffix string
  33920. has been set using setTextValueSuffix(), this will be appended to the text.
  33921. @see getValueFromText
  33922. */
  33923. virtual const String getTextFromValue (double value);
  33924. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  33925. a string.
  33926. This is used by the default implementation of getTextFromValue(), and is just
  33927. appended to the numeric value. For more advanced formatting, you can override
  33928. getTextFromValue() and do something else.
  33929. */
  33930. void setTextValueSuffix (const String& suffix);
  33931. /** Allows a user-defined mapping of distance along the slider to its value.
  33932. The default implementation for this performs the skewing operation that
  33933. can be set up in the setSkewFactor() method. Override it if you need
  33934. some kind of custom mapping instead, but make sure you also implement the
  33935. inverse function in valueToProportionOfLength().
  33936. @param proportion a value 0 to 1.0, indicating a distance along the slider
  33937. @returns the slider value that is represented by this position
  33938. @see valueToProportionOfLength
  33939. */
  33940. virtual double proportionOfLengthToValue (double proportion);
  33941. /** Allows a user-defined mapping of value to the position of the slider along its length.
  33942. The default implementation for this performs the skewing operation that
  33943. can be set up in the setSkewFactor() method. Override it if you need
  33944. some kind of custom mapping instead, but make sure you also implement the
  33945. inverse function in proportionOfLengthToValue().
  33946. @param value a valid slider value, between the range of values specified in
  33947. setRange()
  33948. @returns a value 0 to 1.0 indicating the distance along the slider that
  33949. represents this value
  33950. @see proportionOfLengthToValue
  33951. */
  33952. virtual double valueToProportionOfLength (double value);
  33953. /** Returns the X or Y coordinate of a value along the slider's length.
  33954. If the slider is horizontal, this will be the X coordinate of the given
  33955. value, relative to the left of the slider. If it's vertical, then this will
  33956. be the Y coordinate, relative to the top of the slider.
  33957. If the slider is rotary, this will throw an assertion and return 0. If the
  33958. value is out-of-range, it will be constrained to the length of the slider.
  33959. */
  33960. float getPositionOfValue (const double value);
  33961. /** This can be overridden to allow the slider to snap to user-definable values.
  33962. If overridden, it will be called when the user tries to move the slider to
  33963. a given position, and allows a subclass to sanity-check this value, possibly
  33964. returning a different value to use instead.
  33965. @param attemptedValue the value the user is trying to enter
  33966. @param userIsDragging true if the user is dragging with the mouse; false if
  33967. they are entering the value using the text box
  33968. @returns the value to use instead
  33969. */
  33970. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  33971. /** This can be called to force the text box to update its contents.
  33972. (Not normally needed, as this is done automatically).
  33973. */
  33974. void updateText();
  33975. /** True if the slider moves horizontally. */
  33976. bool isHorizontal() const throw();
  33977. /** True if the slider moves vertically. */
  33978. bool isVertical() const throw();
  33979. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  33980. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33981. methods.
  33982. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33983. */
  33984. enum ColourIds
  33985. {
  33986. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  33987. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  33988. and feel class how this is used. */
  33989. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  33990. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  33991. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  33992. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  33993. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  33994. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  33995. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  33996. };
  33997. juce_UseDebuggingNewOperator
  33998. protected:
  33999. /** @internal */
  34000. void labelTextChanged (Label*);
  34001. /** @internal */
  34002. void paint (Graphics& g);
  34003. /** @internal */
  34004. void resized();
  34005. /** @internal */
  34006. void mouseDown (const MouseEvent& e);
  34007. /** @internal */
  34008. void mouseUp (const MouseEvent& e);
  34009. /** @internal */
  34010. void mouseDrag (const MouseEvent& e);
  34011. /** @internal */
  34012. void mouseDoubleClick (const MouseEvent& e);
  34013. /** @internal */
  34014. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34015. /** @internal */
  34016. void modifierKeysChanged (const ModifierKeys& modifiers);
  34017. /** @internal */
  34018. void buttonClicked (Button* button);
  34019. /** @internal */
  34020. void lookAndFeelChanged();
  34021. /** @internal */
  34022. void enablementChanged();
  34023. /** @internal */
  34024. void focusOfChildComponentChanged (FocusChangeType cause);
  34025. /** @internal */
  34026. void handleAsyncUpdate();
  34027. /** @internal */
  34028. void colourChanged();
  34029. private:
  34030. SortedSet <void*> listeners;
  34031. double currentValue, valueMin, valueMax;
  34032. double minimum, maximum, interval, doubleClickReturnValue;
  34033. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34034. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34035. int velocityModeThreshold;
  34036. float rotaryStart, rotaryEnd;
  34037. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34038. int sliderRegionStart, sliderRegionSize;
  34039. int sliderBeingDragged;
  34040. int pixelsForFullDragExtent;
  34041. Rectangle sliderRect;
  34042. String textSuffix;
  34043. SliderStyle style;
  34044. TextEntryBoxPosition textBoxPos;
  34045. int textBoxWidth, textBoxHeight;
  34046. IncDecButtonMode incDecButtonMode;
  34047. bool editableText : 1, doubleClickToValue : 1;
  34048. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34049. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34050. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34051. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34052. Font font;
  34053. Label* valueBox;
  34054. Button* incButton;
  34055. Button* decButton;
  34056. Component* popupDisplay;
  34057. Component* parentForPopupDisplay;
  34058. float getLinearSliderPos (const double value);
  34059. void restoreMouseIfHidden();
  34060. void sendDragStart();
  34061. void sendDragEnd();
  34062. double constrainedValue (double value) const throw();
  34063. void triggerChangeMessage (const bool synchronous);
  34064. bool incDecDragDirectionIsHorizontal() const throw();
  34065. Slider (const Slider&);
  34066. const Slider& operator= (const Slider&);
  34067. };
  34068. #endif // __JUCE_SLIDER_JUCEHEADER__
  34069. /********* End of inlined file: juce_Slider.h *********/
  34070. #endif
  34071. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34072. #endif
  34073. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34074. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  34075. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34076. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34077. class TableHeaderComponent;
  34078. /**
  34079. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  34080. You can register one of these objects for table events using TableHeaderComponent::addListener()
  34081. and TableHeaderComponent::removeListener().
  34082. @see TableHeaderComponent
  34083. */
  34084. class JUCE_API TableHeaderListener
  34085. {
  34086. public:
  34087. TableHeaderListener() {}
  34088. /** Destructor. */
  34089. virtual ~TableHeaderListener() {}
  34090. /** This is called when some of the table's columns are added, removed, hidden,
  34091. or rearranged.
  34092. */
  34093. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  34094. /** This is called when one or more of the table's columns are resized.
  34095. */
  34096. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  34097. /** This is called when the column by which the table should be sorted is changed.
  34098. */
  34099. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  34100. /** This is called when the user begins or ends dragging one of the columns around.
  34101. When the user starts dragging a column, this is called with the ID of that
  34102. column. When they finish dragging, it is called again with 0 as the ID.
  34103. */
  34104. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  34105. int columnIdNowBeingDragged);
  34106. };
  34107. /**
  34108. A component that displays a strip of column headings for a table, and allows these
  34109. to be resized, dragged around, etc.
  34110. This is just the component that goes at the top of a table. You can use it
  34111. directly for custom components, or to create a simple table, use the
  34112. TableListBox class.
  34113. To use one of these, create it and use addColumn() to add all the columns that you need.
  34114. Each column must be given a unique ID number that's used to refer to it.
  34115. @see TableListBox, TableHeaderListener
  34116. */
  34117. class JUCE_API TableHeaderComponent : public Component,
  34118. private AsyncUpdater
  34119. {
  34120. public:
  34121. /** Creates an empty table header.
  34122. */
  34123. TableHeaderComponent();
  34124. /** Destructor. */
  34125. ~TableHeaderComponent();
  34126. /** A combination of these flags are passed into the addColumn() method to specify
  34127. the properties of a column.
  34128. */
  34129. enum ColumnPropertyFlags
  34130. {
  34131. visible = 1, /**< If this is set, the column will be shown; if not, it will be hidden until the user enables it with the pop-up menu. */
  34132. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  34133. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  34134. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  34135. sortable = 16, /**< If this is set, then clicking on the column header will set it to be the sort column, and clicking again will reverse the order. */
  34136. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  34137. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  34138. /** This set of default flags is used as the default parameter value in addColumn(). */
  34139. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  34140. /** A quick way of combining flags for a column that's not resizable. */
  34141. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  34142. /** A quick way of combining flags for a column that's not resizable or sortable. */
  34143. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  34144. /** A quick way of combining flags for a column that's not sortable. */
  34145. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  34146. };
  34147. /** Adds a column to the table.
  34148. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  34149. registered listeners.
  34150. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  34151. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  34152. a unique ID. This is used to identify the column later on, after the user may have
  34153. changed the order that they appear in
  34154. @param width the initial width of the column, in pixels
  34155. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  34156. if the 'resizable' flag is specified for this column
  34157. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  34158. if the 'resizable' flag is specified for this column
  34159. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  34160. properties of this column
  34161. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  34162. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  34163. all columns, not just the index amongst those that are currently visible
  34164. */
  34165. void addColumn (const String& columnName,
  34166. const int columnId,
  34167. const int width,
  34168. const int minimumWidth = 30,
  34169. const int maximumWidth = -1,
  34170. const int propertyFlags = defaultFlags,
  34171. const int insertIndex = -1);
  34172. /** Removes a column with the given ID.
  34173. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  34174. registered listeners.
  34175. */
  34176. void removeColumn (const int columnIdToRemove);
  34177. /** Deletes all columns from the table.
  34178. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  34179. registered listeners.
  34180. */
  34181. void removeAllColumns();
  34182. /** Returns the number of columns in the table.
  34183. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  34184. return the total number of columns, including hidden ones.
  34185. @see isColumnVisible
  34186. */
  34187. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  34188. /** Returns the name for a column.
  34189. @see setColumnName
  34190. */
  34191. const String getColumnName (const int columnId) const throw();
  34192. /** Changes the name of a column. */
  34193. void setColumnName (const int columnId, const String& newName);
  34194. /** Moves a column to a different index in the table.
  34195. @param columnId the column to move
  34196. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  34197. */
  34198. void moveColumn (const int columnId, int newVisibleIndex);
  34199. /** Changes the width of a column.
  34200. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  34201. */
  34202. void setColumnWidth (const int columnId, const int newWidth);
  34203. /** Shows or hides a column.
  34204. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  34205. @see isColumnVisible
  34206. */
  34207. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  34208. /** Returns true if this column is currently visible.
  34209. @see setColumnVisible
  34210. */
  34211. bool isColumnVisible (const int columnId) const;
  34212. /** Changes the column which is the sort column.
  34213. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  34214. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  34215. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  34216. @see getSortColumnId, isSortedForwards, reSortTable
  34217. */
  34218. void setSortColumnId (const int columnId, const bool sortForwards);
  34219. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  34220. @see setSortColumnId, isSortedForwards
  34221. */
  34222. int getSortColumnId() const throw();
  34223. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  34224. @see setSortColumnId
  34225. */
  34226. bool isSortedForwards() const throw();
  34227. /** Triggers a re-sort of the table according to the current sort-column.
  34228. If you modifiy the table's contents, you can call this to signal that the table needs
  34229. to be re-sorted.
  34230. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  34231. tableSortOrderChanged() method of any listeners).
  34232. */
  34233. void reSortTable();
  34234. /** Returns the total width of all the visible columns in the table.
  34235. */
  34236. int getTotalWidth() const throw();
  34237. /** Returns the index of a given column.
  34238. If there's no such column ID, this will return -1.
  34239. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  34240. otherwise it'll return the index amongst all the columns, including any hidden ones.
  34241. */
  34242. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  34243. /** Returns the ID of the column at a given index.
  34244. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  34245. otherwise it'll count it amongst all the columns, including any hidden ones.
  34246. If the index is out-of-range, it'll return 0.
  34247. */
  34248. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  34249. /** Returns the rectangle containing of one of the columns.
  34250. The index is an index from 0 to the number of columns that are currently visible (hidden
  34251. ones are not counted). It returns a rectangle showing the position of the column relative
  34252. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  34253. */
  34254. const Rectangle getColumnPosition (const int index) const throw();
  34255. /** Finds the column ID at a given x-position in the component.
  34256. If there is a column at this point this returns its ID, or if not, it will return 0.
  34257. */
  34258. int getColumnIdAtX (const int xToFind) const throw();
  34259. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  34260. entire width of the component.
  34261. By default this is disabled. Turning it on also means that when resizing a column, those
  34262. on the right will be squashed to fit.
  34263. */
  34264. void setStretchToFitActive (const bool shouldStretchToFit);
  34265. /** Returns true if stretch-to-fit has been enabled.
  34266. @see setStretchToFitActive
  34267. */
  34268. bool isStretchToFitActive() const throw();
  34269. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34270. specified width, keeping their relative proportions the same.
  34271. If the minimum widths of the columns are too wide to fit into this space, it may
  34272. actually end up wider.
  34273. */
  34274. void resizeAllColumnsToFit (int targetTotalWidth);
  34275. /** Enables or disables the pop-up menu.
  34276. The default menu allows the user to show or hide columns. You can add custom
  34277. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34278. By default the menu is enabled.
  34279. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34280. */
  34281. void setPopupMenuActive (const bool hasMenu);
  34282. /** Returns true if the pop-up menu is enabled.
  34283. @see setPopupMenuActive
  34284. */
  34285. bool isPopupMenuActive() const throw();
  34286. /** Returns a string that encapsulates the table's current layout.
  34287. This can be restored later using restoreFromString(). It saves the order of
  34288. the columns, the currently-sorted column, and the widths.
  34289. @see restoreFromString
  34290. */
  34291. const String toString() const;
  34292. /** Restores the state of the table, based on a string previously created with
  34293. toString().
  34294. @see toString
  34295. */
  34296. void restoreFromString (const String& storedVersion);
  34297. /** Adds a listener to be informed about things that happen to the header. */
  34298. void addListener (TableHeaderListener* const newListener) throw();
  34299. /** Removes a previously-registered listener. */
  34300. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  34301. /** This can be overridden to handle a mouse-click on one of the column headers.
  34302. The default implementation will use this click to call getSortColumnId() and
  34303. change the sort order.
  34304. */
  34305. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34306. /** This can be overridden to add custom items to the pop-up menu.
  34307. If you override this, you should call the superclass's method to add its
  34308. column show/hide items, if you want them on the menu as well.
  34309. Then to handle the result, override reactToMenuItem().
  34310. @see reactToMenuItem
  34311. */
  34312. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  34313. /** Override this to handle any custom items that you have added to the
  34314. pop-up menu with an addMenuItems() override.
  34315. If the menuReturnId isn't one of your own custom menu items, you'll need to
  34316. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  34317. handle the items that it had added.
  34318. @see addMenuItems
  34319. */
  34320. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  34321. /** @internal */
  34322. void paint (Graphics& g);
  34323. /** @internal */
  34324. void resized();
  34325. /** @internal */
  34326. void mouseMove (const MouseEvent&);
  34327. /** @internal */
  34328. void mouseEnter (const MouseEvent&);
  34329. /** @internal */
  34330. void mouseExit (const MouseEvent&);
  34331. /** @internal */
  34332. void mouseDown (const MouseEvent&);
  34333. /** @internal */
  34334. void mouseDrag (const MouseEvent&);
  34335. /** @internal */
  34336. void mouseUp (const MouseEvent&);
  34337. /** @internal */
  34338. const MouseCursor getMouseCursor();
  34339. juce_UseDebuggingNewOperator
  34340. private:
  34341. struct ColumnInfo
  34342. {
  34343. String name;
  34344. int id, propertyFlags, width, minimumWidth, maximumWidth;
  34345. double lastDeliberateWidth;
  34346. bool isVisible() const throw();
  34347. };
  34348. OwnedArray <ColumnInfo> columns;
  34349. Array <TableHeaderListener*> listeners;
  34350. Component* dragOverlayComp;
  34351. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  34352. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  34353. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  34354. ColumnInfo* getInfoForId (const int columnId) const throw();
  34355. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  34356. void sendColumnsChanged();
  34357. void handleAsyncUpdate();
  34358. void beginDrag (const MouseEvent&);
  34359. void endDrag (const int finalIndex);
  34360. int getResizeDraggerAt (const int mouseX) const throw();
  34361. void updateColumnUnderMouse (int x, int y);
  34362. void showColumnChooserMenu (const int);
  34363. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  34364. TableHeaderComponent (const TableHeaderComponent&);
  34365. const TableHeaderComponent operator= (const TableHeaderComponent&);
  34366. };
  34367. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34368. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  34369. #endif
  34370. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34371. /********* Start of inlined file: juce_TableListBox.h *********/
  34372. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34373. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  34374. /**
  34375. One of these is used by a TableListBox as the data model for the table's contents.
  34376. The virtual methods that you override in this class take care of drawing the
  34377. table cells, and reacting to events.
  34378. @see TableListBox
  34379. */
  34380. class JUCE_API TableListBoxModel
  34381. {
  34382. public:
  34383. TableListBoxModel() {}
  34384. /** Destructor. */
  34385. virtual ~TableListBoxModel() {}
  34386. /** This must return the number of rows currently in the table.
  34387. If the number of rows changes, you must call TableListBox::updateContent() to
  34388. cause it to refresh the list.
  34389. */
  34390. virtual int getNumRows() = 0;
  34391. /** This must draw the background behind one of the rows in the table.
  34392. The graphics context has its origin at the row's top-left, and your method
  34393. should fill the area specified by the width and height parameters.
  34394. */
  34395. virtual void paintRowBackground (Graphics& g,
  34396. int rowNumber,
  34397. int width, int height,
  34398. bool rowIsSelected) = 0;
  34399. /** This must draw one of the cells.
  34400. The graphics context's origin will already be set to the top-left of the cell,
  34401. whose size is specified by (width, height).
  34402. */
  34403. virtual void paintCell (Graphics& g,
  34404. int rowNumber,
  34405. int columnId,
  34406. int width, int height,
  34407. bool rowIsSelected) = 0;
  34408. /** This is used to create or update a custom component to go in a cell.
  34409. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  34410. and handle mouse clicks with cellClicked().
  34411. This method will be called whenever a custom component might need to be updated - e.g.
  34412. when the table is changed, or TableListBox::updateContent() is called.
  34413. If you don't need a custom component for the specified cell, then return 0.
  34414. If you do want a custom component, and the existingComponentToUpdate is null, then
  34415. this method must create a new component suitable for the cell, and return it.
  34416. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34417. by this method. In this case, the method must either update it to make sure it's correctly representing
  34418. the given cell (which may be different from the one that the component was created for), or it can
  34419. delete this component and return a new one.
  34420. */
  34421. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  34422. Component* existingComponentToUpdate);
  34423. /** This callback is made when the user clicks on one of the cells in the table.
  34424. The mouse event's coordinates will be relative to the entire table row.
  34425. @see cellDoubleClicked, backgroundClicked
  34426. */
  34427. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  34428. /** This callback is made when the user clicks on one of the cells in the table.
  34429. The mouse event's coordinates will be relative to the entire table row.
  34430. @see cellClicked, backgroundClicked
  34431. */
  34432. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  34433. /** This can be overridden to react to the user double-clicking on a part of the list where
  34434. there are no rows.
  34435. @see cellClicked
  34436. */
  34437. virtual void backgroundClicked();
  34438. /** This callback is made when the table's sort order is changed.
  34439. This could be because the user has clicked a column header, or because the
  34440. TableHeaderComponent::setSortColumnId() method was called.
  34441. If you implement this, your method should re-sort the table using the given
  34442. column as the key.
  34443. */
  34444. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  34445. /** Returns the best width for one of the columns.
  34446. If you implement this method, you should measure the width of all the items
  34447. in this column, and return the best size.
  34448. Returning 0 means that the column shouldn't be changed.
  34449. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  34450. */
  34451. virtual int getColumnAutoSizeWidth (int columnId);
  34452. /** Override this to be informed when rows are selected or deselected.
  34453. @see ListBox::selectedRowsChanged()
  34454. */
  34455. virtual void selectedRowsChanged (int lastRowSelected);
  34456. /** Override this to be informed when the delete key is pressed.
  34457. @see ListBox::deleteKeyPressed()
  34458. */
  34459. virtual void deleteKeyPressed (int lastRowSelected);
  34460. /** Override this to be informed when the return key is pressed.
  34461. @see ListBox::returnKeyPressed()
  34462. */
  34463. virtual void returnKeyPressed (int lastRowSelected);
  34464. /** Override this to be informed when the list is scrolled.
  34465. This might be caused by the user moving the scrollbar, or by programmatic changes
  34466. to the list position.
  34467. */
  34468. virtual void listWasScrolled();
  34469. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  34470. If this returns a non-empty name then when the user drags a row, the table will try to
  34471. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  34472. drag-and-drop operation, using this string as the source description, and the listbox
  34473. itself as the source component.
  34474. @see DragAndDropContainer::startDragging
  34475. */
  34476. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34477. };
  34478. /**
  34479. A table of cells, using a TableHeaderComponent as its header.
  34480. This component makes it easy to create a table by providing a TableListBoxModel as
  34481. the data source.
  34482. @see TableListBoxModel, TableHeaderComponent
  34483. */
  34484. class JUCE_API TableListBox : public ListBox,
  34485. private ListBoxModel,
  34486. private TableHeaderListener
  34487. {
  34488. public:
  34489. /** Creates a TableListBox.
  34490. The model pointer passed-in can be null, in which case you can set it later
  34491. with setModel().
  34492. */
  34493. TableListBox (const String& componentName,
  34494. TableListBoxModel* const model);
  34495. /** Destructor. */
  34496. ~TableListBox();
  34497. /** Changes the TableListBoxModel that is being used for this table.
  34498. */
  34499. void setModel (TableListBoxModel* const newModel);
  34500. /** Returns the model currently in use. */
  34501. TableListBoxModel* getModel() const throw() { return model; }
  34502. /** Returns the header component being used in this table. */
  34503. TableHeaderComponent* getHeader() const throw() { return header; }
  34504. /** Changes the height of the table header component.
  34505. @see getHeaderHeight
  34506. */
  34507. void setHeaderHeight (const int newHeight);
  34508. /** Returns the height of the table header.
  34509. @see setHeaderHeight
  34510. */
  34511. int getHeaderHeight() const throw();
  34512. /** Resizes a column to fit its contents.
  34513. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  34514. and applies that to the column.
  34515. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  34516. */
  34517. void autoSizeColumn (const int columnId);
  34518. /** Calls autoSizeColumn() for all columns in the table. */
  34519. void autoSizeAllColumns();
  34520. /** Enables or disables the auto size options on the popup menu.
  34521. By default, these are enabled.
  34522. */
  34523. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  34524. /** True if the auto-size options should be shown on the menu.
  34525. @see setAutoSizeMenuOptionsShown
  34526. */
  34527. bool isAutoSizeMenuOptionShown() const throw();
  34528. /** Returns the position of one of the cells in the table.
  34529. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  34530. the table component's top-left. The row number isn't checked to see if it's
  34531. in-range, but the column ID must exist or this will return an empty rectangle.
  34532. If relativeToComponentTopLeft is false, the co-ords are relative to the
  34533. top-left of the table's top-left cell.
  34534. */
  34535. const Rectangle getCellPosition (const int columnId,
  34536. const int rowNumber,
  34537. const bool relativeToComponentTopLeft) const;
  34538. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  34539. @see ListBox::scrollToEnsureRowIsOnscreen
  34540. */
  34541. void scrollToEnsureColumnIsOnscreen (const int columnId);
  34542. /** @internal */
  34543. int getNumRows();
  34544. /** @internal */
  34545. void paintListBoxItem (int, Graphics&, int, int, bool);
  34546. /** @internal */
  34547. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  34548. /** @internal */
  34549. void selectedRowsChanged (int lastRowSelected);
  34550. /** @internal */
  34551. void deleteKeyPressed (int currentSelectedRow);
  34552. /** @internal */
  34553. void returnKeyPressed (int currentSelectedRow);
  34554. /** @internal */
  34555. void backgroundClicked();
  34556. /** @internal */
  34557. void listWasScrolled();
  34558. /** @internal */
  34559. void tableColumnsChanged (TableHeaderComponent*);
  34560. /** @internal */
  34561. void tableColumnsResized (TableHeaderComponent*);
  34562. /** @internal */
  34563. void tableSortOrderChanged (TableHeaderComponent*);
  34564. /** @internal */
  34565. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  34566. /** @internal */
  34567. void resized();
  34568. juce_UseDebuggingNewOperator
  34569. private:
  34570. TableHeaderComponent* header;
  34571. TableListBoxModel* model;
  34572. int columnIdNowBeingDragged;
  34573. bool autoSizeOptionsShown;
  34574. void updateColumnComponents() const;
  34575. TableListBox (const TableListBox&);
  34576. const TableListBox& operator= (const TableListBox&);
  34577. };
  34578. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  34579. /********* End of inlined file: juce_TableListBox.h *********/
  34580. #endif
  34581. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  34582. #endif
  34583. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  34584. #endif
  34585. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  34586. #endif
  34587. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34588. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  34589. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34590. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34591. /**
  34592. A factory object which can create ToolbarItemComponent objects.
  34593. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  34594. that it can create.
  34595. Each type of item is identified by a unique ID, and multiple instances of an
  34596. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  34597. bars).
  34598. @see Toolbar, ToolbarItemComponent, ToolbarButton
  34599. */
  34600. class JUCE_API ToolbarItemFactory
  34601. {
  34602. public:
  34603. ToolbarItemFactory();
  34604. /** Destructor. */
  34605. virtual ~ToolbarItemFactory();
  34606. /** A set of reserved item ID values, used for the built-in item types.
  34607. */
  34608. enum SpecialItemIds
  34609. {
  34610. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  34611. can be placed between sets of items to break them into groups. */
  34612. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  34613. items.*/
  34614. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  34615. either side of it, filling any available space. */
  34616. };
  34617. /** Must return a list of the IDs for all the item types that this factory can create.
  34618. The ids should be added to the array that is passed-in.
  34619. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  34620. and the predefined IDs in the SpecialItemIds enum.
  34621. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  34622. to this list if you want your toolbar to be able to contain those items.
  34623. The list returned here is used by the ToolbarItemPalette class to obtain its list
  34624. of available items, and their order on the palette will reflect the order in which
  34625. they appear on this list.
  34626. @see ToolbarItemPalette
  34627. */
  34628. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  34629. /** Must return the set of items that should be added to a toolbar as its default set.
  34630. This method is used by Toolbar::addDefaultItems() to determine which items to
  34631. create.
  34632. The items that your method adds to the array that is passed-in will be added to the
  34633. toolbar in the same order. Items can appear in the list more than once.
  34634. */
  34635. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  34636. /** Must create an instance of one of the items that the factory lists in its
  34637. getAllToolbarItemIds() method.
  34638. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  34639. method, except for the built-in item types from the SpecialItemIds enum, which
  34640. are created internally by the toolbar code.
  34641. Try not to keep a pointer to the object that is returned, as it will be deleted
  34642. automatically by the toolbar, and remember that multiple instances of the same
  34643. item type are likely to exist at the same time.
  34644. */
  34645. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  34646. };
  34647. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34648. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  34649. #endif
  34650. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34651. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  34652. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34653. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34654. /**
  34655. A component containing a list of toolbar items, which the user can drag onto
  34656. a toolbar to add them.
  34657. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  34658. which automatically shows one of these in a dialog box with lots of extra controls.
  34659. @see Toolbar
  34660. */
  34661. class JUCE_API ToolbarItemPalette : public Component,
  34662. public DragAndDropContainer
  34663. {
  34664. public:
  34665. /** Creates a palette of items for a given factory, with the aim of adding them
  34666. to the specified toolbar.
  34667. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  34668. set of items that are shown in this palette.
  34669. The toolbar and factory must not be deleted while this object exists.
  34670. */
  34671. ToolbarItemPalette (ToolbarItemFactory& factory,
  34672. Toolbar* const toolbar);
  34673. /** Destructor. */
  34674. ~ToolbarItemPalette();
  34675. /** @internal */
  34676. void resized();
  34677. juce_UseDebuggingNewOperator
  34678. private:
  34679. ToolbarItemFactory& factory;
  34680. Toolbar* toolbar;
  34681. Viewport* viewport;
  34682. friend class Toolbar;
  34683. void replaceComponent (ToolbarItemComponent* const comp);
  34684. ToolbarItemPalette (const ToolbarItemPalette&);
  34685. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  34686. };
  34687. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34688. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  34689. #endif
  34690. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34691. #endif
  34692. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34693. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  34694. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34695. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34696. /**
  34697. A PropertyComponent that contains an on/off toggle button.
  34698. This type of property component can be used if you have a boolean value to
  34699. toggle on/off.
  34700. @see PropertyComponent
  34701. */
  34702. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  34703. private ButtonListener
  34704. {
  34705. public:
  34706. /** Creates a button component.
  34707. @param propertyName the property name to be passed to the PropertyComponent
  34708. @param buttonTextWhenTrue the text shown in the button when the value is true
  34709. @param buttonTextWhenFalse the text shown in the button when the value is false
  34710. */
  34711. BooleanPropertyComponent (const String& propertyName,
  34712. const String& buttonTextWhenTrue,
  34713. const String& buttonTextWhenFalse);
  34714. /** Destructor. */
  34715. ~BooleanPropertyComponent();
  34716. /** Called to change the state of the boolean value. */
  34717. virtual void setState (const bool newState) = 0;
  34718. /** Must return the current value of the property. */
  34719. virtual bool getState() const = 0;
  34720. /** @internal */
  34721. void paint (Graphics& g);
  34722. /** @internal */
  34723. void refresh();
  34724. /** @internal */
  34725. void buttonClicked (Button*);
  34726. juce_UseDebuggingNewOperator
  34727. private:
  34728. ToggleButton* button;
  34729. String onText, offText;
  34730. };
  34731. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  34732. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  34733. #endif
  34734. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34735. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  34736. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34737. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34738. /**
  34739. A PropertyComponent that contains a button.
  34740. This type of property component can be used if you need a button to trigger some
  34741. kind of action.
  34742. @see PropertyComponent
  34743. */
  34744. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  34745. private ButtonListener
  34746. {
  34747. public:
  34748. /** Creates a button component.
  34749. @param propertyName the property name to be passed to the PropertyComponent
  34750. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  34751. */
  34752. ButtonPropertyComponent (const String& propertyName,
  34753. const bool triggerOnMouseDown);
  34754. /** Destructor. */
  34755. ~ButtonPropertyComponent();
  34756. /** Called when the user clicks the button.
  34757. */
  34758. virtual void buttonClicked() = 0;
  34759. /** Returns the string that should be displayed in the button.
  34760. If you need to change this string, call refresh() to update the component.
  34761. */
  34762. virtual const String getButtonText() const = 0;
  34763. /** @internal */
  34764. void refresh();
  34765. /** @internal */
  34766. void buttonClicked (Button*);
  34767. juce_UseDebuggingNewOperator
  34768. private:
  34769. TextButton* button;
  34770. };
  34771. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  34772. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  34773. #endif
  34774. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34775. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  34776. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34777. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34778. /**
  34779. A PropertyComponent that shows its value as a combo box.
  34780. This type of property component contains a list of options and has a
  34781. combo box to choose one.
  34782. Your subclass's constructor must add some strings to the choices StringArray
  34783. and these are shown in the list.
  34784. The getIndex() method will be called to find out which option is the currently
  34785. selected one. If you call refresh() it will call getIndex() to check whether
  34786. the value has changed, and will update the combo box if needed.
  34787. If the user selects a different item from the list, setIndex() will be
  34788. called to let your class process this.
  34789. @see PropertyComponent, PropertyPanel
  34790. */
  34791. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  34792. private ComboBoxListener
  34793. {
  34794. public:
  34795. /** Creates the component.
  34796. Your subclass's constructor must add a list of options to the choices
  34797. member variable.
  34798. */
  34799. ChoicePropertyComponent (const String& propertyName);
  34800. /** Destructor. */
  34801. ~ChoicePropertyComponent();
  34802. /** Called when the user selects an item from the combo box.
  34803. Your subclass must use this callback to update the value that this component
  34804. represents. The index is the index of the chosen item in the choices
  34805. StringArray.
  34806. */
  34807. virtual void setIndex (const int newIndex) = 0;
  34808. /** Returns the index of the item that should currently be shown.
  34809. This is the index of the item in the choices StringArray that will be
  34810. shown.
  34811. */
  34812. virtual int getIndex() const = 0;
  34813. /** Returns the list of options. */
  34814. const StringArray& getChoices() const throw();
  34815. /** @internal */
  34816. void refresh();
  34817. /** @internal */
  34818. void comboBoxChanged (ComboBox*);
  34819. juce_UseDebuggingNewOperator
  34820. protected:
  34821. /** The list of options that will be shown in the combo box.
  34822. Your subclass must populate this array in its constructor. If any empty
  34823. strings are added, these will be replaced with horizontal separators (see
  34824. ComboBox::addSeparator() for more info).
  34825. */
  34826. StringArray choices;
  34827. private:
  34828. ComboBox* comboBox;
  34829. };
  34830. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  34831. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  34832. #endif
  34833. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  34834. #endif
  34835. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  34836. #endif
  34837. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34838. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  34839. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34840. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34841. /**
  34842. A PropertyComponent that shows its value as a slider.
  34843. @see PropertyComponent, Slider
  34844. */
  34845. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  34846. private SliderListener
  34847. {
  34848. public:
  34849. /** Creates the property component.
  34850. The ranges, interval and skew factor are passed to the Slider component.
  34851. If you need to customise the slider in other ways, your constructor can
  34852. access the slider member variable and change it directly.
  34853. */
  34854. SliderPropertyComponent (const String& propertyName,
  34855. const double rangeMin,
  34856. const double rangeMax,
  34857. const double interval,
  34858. const double skewFactor = 1.0);
  34859. /** Destructor. */
  34860. ~SliderPropertyComponent();
  34861. /** Called when the user moves the slider to change its value.
  34862. Your subclass must use this method to update whatever item this property
  34863. represents.
  34864. */
  34865. virtual void setValue (const double newValue) = 0;
  34866. /** Returns the value that the slider should show. */
  34867. virtual const double getValue() const = 0;
  34868. /** @internal */
  34869. void refresh();
  34870. /** @internal */
  34871. void changeListenerCallback (void*);
  34872. /** @internal */
  34873. void sliderValueChanged (Slider*);
  34874. juce_UseDebuggingNewOperator
  34875. protected:
  34876. /** The slider component being used in this component.
  34877. Your subclass has access to this in case it needs to customise it in some way.
  34878. */
  34879. Slider* slider;
  34880. };
  34881. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  34882. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  34883. #endif
  34884. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34885. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  34886. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34887. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34888. /**
  34889. A PropertyComponent that shows its value as editable text.
  34890. @see PropertyComponent
  34891. */
  34892. class JUCE_API TextPropertyComponent : public PropertyComponent
  34893. {
  34894. public:
  34895. /** Creates a text property component.
  34896. The maxNumChars is used to set the length of string allowable, and isMultiLine
  34897. sets whether the text editor allows carriage returns.
  34898. @see TextEditor
  34899. */
  34900. TextPropertyComponent (const String& propertyName,
  34901. const int maxNumChars,
  34902. const bool isMultiLine);
  34903. /** Destructor. */
  34904. ~TextPropertyComponent();
  34905. /** Called when the user edits the text.
  34906. Your subclass must use this callback to change the value of whatever item
  34907. this property component represents.
  34908. */
  34909. virtual void setText (const String& newText) = 0;
  34910. /** Returns the text that should be shown in the text editor.
  34911. */
  34912. virtual const String getText() const = 0;
  34913. /** @internal */
  34914. void refresh();
  34915. /** @internal */
  34916. void textWasEdited();
  34917. juce_UseDebuggingNewOperator
  34918. private:
  34919. Label* textEditor;
  34920. };
  34921. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  34922. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  34923. #endif
  34924. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  34925. #endif
  34926. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34927. #endif
  34928. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34929. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  34930. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34931. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34932. /** An object that watches for any movement of a component or any of its parent components.
  34933. This makes it easy to check when a component is moved relative to its top-level
  34934. peer window. The normal Component::moved() method is only called when a component
  34935. moves relative to its immediate parent, and sometimes you want to know if any of
  34936. components higher up the tree have moved (which of course will affect the overall
  34937. position of all their sub-components).
  34938. It also includes a callback that lets you know when the top-level peer is changed.
  34939. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  34940. because they need to keep their custom windows in the right place and respond to
  34941. changes in the peer.
  34942. */
  34943. class JUCE_API ComponentMovementWatcher : public ComponentListener
  34944. {
  34945. public:
  34946. /** Creates a ComponentMovementWatcher to watch a given target component. */
  34947. ComponentMovementWatcher (Component* const component);
  34948. /** Destructor. */
  34949. ~ComponentMovementWatcher();
  34950. /** This callback happens when the component that is being watched is moved
  34951. relative to its top-level peer window, or when it is resized.
  34952. */
  34953. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  34954. /** This callback happens when the component's top-level peer is changed.
  34955. */
  34956. virtual void componentPeerChanged() = 0;
  34957. juce_UseDebuggingNewOperator
  34958. /** @internal */
  34959. void componentParentHierarchyChanged (Component& component);
  34960. /** @internal */
  34961. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34962. private:
  34963. Component* const component;
  34964. ComponentPeer* lastPeer;
  34965. VoidArray registeredParentComps;
  34966. bool reentrant;
  34967. int lastX, lastY, lastWidth, lastHeight;
  34968. #ifdef JUCE_DEBUG
  34969. ComponentDeletionWatcher* deletionWatcher;
  34970. #endif
  34971. void unregister() throw();
  34972. void registerWithParentComps() throw();
  34973. ComponentMovementWatcher (const ComponentMovementWatcher&);
  34974. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  34975. };
  34976. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  34977. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  34978. #endif
  34979. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34980. /********* Start of inlined file: juce_GroupComponent.h *********/
  34981. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34982. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  34983. /**
  34984. A component that draws an outline around itself and has an optional title at
  34985. the top, for drawing an outline around a group of controls.
  34986. */
  34987. class JUCE_API GroupComponent : public Component
  34988. {
  34989. public:
  34990. /** Creates a GroupComponent.
  34991. @param componentName the name to give the component
  34992. @param labelText the text to show at the top of the outline
  34993. */
  34994. GroupComponent (const String& componentName,
  34995. const String& labelText);
  34996. /** Destructor. */
  34997. ~GroupComponent();
  34998. /** Changes the text that's shown at the top of the component. */
  34999. void setText (const String& newText) throw();
  35000. /** Returns the currently displayed text label. */
  35001. const String getText() const throw();
  35002. /** Sets the positioning of the text label.
  35003. (The default is Justification::left)
  35004. @see getTextLabelPosition
  35005. */
  35006. void setTextLabelPosition (const Justification& justification);
  35007. /** Returns the current text label position.
  35008. @see setTextLabelPosition
  35009. */
  35010. const Justification getTextLabelPosition() const throw() { return justification; }
  35011. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35012. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35013. methods.
  35014. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35015. */
  35016. enum ColourIds
  35017. {
  35018. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  35019. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  35020. };
  35021. /** @internal */
  35022. void paint (Graphics& g);
  35023. /** @internal */
  35024. void enablementChanged();
  35025. /** @internal */
  35026. void colourChanged();
  35027. private:
  35028. String text;
  35029. Justification justification;
  35030. GroupComponent (const GroupComponent&);
  35031. const GroupComponent& operator= (const GroupComponent&);
  35032. };
  35033. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35034. /********* End of inlined file: juce_GroupComponent.h *********/
  35035. #endif
  35036. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35037. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  35038. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35039. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35040. /********* Start of inlined file: juce_TabbedComponent.h *********/
  35041. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35042. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35043. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  35044. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35045. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35046. class TabbedButtonBar;
  35047. /** In a TabbedButtonBar, this component is used for each of the buttons.
  35048. If you want to create a TabbedButtonBar with custom tab components, derive
  35049. your component from this class, and override the TabbedButtonBar::createTabButton()
  35050. method to create it instead of the default one.
  35051. @see TabbedButtonBar
  35052. */
  35053. class JUCE_API TabBarButton : public Button
  35054. {
  35055. public:
  35056. /** Creates the tab button. */
  35057. TabBarButton (const String& name,
  35058. TabbedButtonBar* const ownerBar,
  35059. const int tabIndex);
  35060. /** Destructor. */
  35061. ~TabBarButton();
  35062. /** Chooses the best length for the tab, given the specified depth.
  35063. If the tab is horizontal, this should return its width, and the depth
  35064. specifies its height. If it's vertical, it should return the height, and
  35065. the depth is actually its width.
  35066. */
  35067. virtual int getBestTabLength (const int depth);
  35068. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35069. void clicked (const ModifierKeys& mods);
  35070. bool hitTest (int x, int y);
  35071. juce_UseDebuggingNewOperator
  35072. protected:
  35073. friend class TabbedButtonBar;
  35074. TabbedButtonBar* const owner;
  35075. int tabIndex, overlapPixels;
  35076. DropShadowEffect shadow;
  35077. /** Returns an area of the component that's safe to draw in.
  35078. This deals with the orientation of the tabs, which affects which side is
  35079. touching the tabbed box's content component.
  35080. */
  35081. void getActiveArea (int& x, int& y, int& w, int& h);
  35082. private:
  35083. TabBarButton (const TabBarButton&);
  35084. const TabBarButton& operator= (const TabBarButton&);
  35085. };
  35086. /**
  35087. A vertical or horizontal bar containing tabs that you can select.
  35088. You can use one of these to generate things like a dialog box that has
  35089. tabbed pages you can flip between. Attach a ChangeListener to the
  35090. button bar to be told when the user changes the page.
  35091. An easier method than doing this is to use a TabbedComponent, which
  35092. contains its own TabbedButtonBar and which takes care of the layout
  35093. and other housekeeping.
  35094. @see TabbedComponent
  35095. */
  35096. class JUCE_API TabbedButtonBar : public Component,
  35097. public ChangeBroadcaster,
  35098. public ButtonListener
  35099. {
  35100. public:
  35101. /** The placement of the tab-bar
  35102. @see setOrientation, getOrientation
  35103. */
  35104. enum Orientation
  35105. {
  35106. TabsAtTop,
  35107. TabsAtBottom,
  35108. TabsAtLeft,
  35109. TabsAtRight
  35110. };
  35111. /** Creates a TabbedButtonBar with a given placement.
  35112. You can change the orientation later if you need to.
  35113. */
  35114. TabbedButtonBar (const Orientation orientation);
  35115. /** Destructor. */
  35116. ~TabbedButtonBar();
  35117. /** Changes the bar's orientation.
  35118. This won't change the bar's actual size - you'll need to do that yourself,
  35119. but this determines which direction the tabs go in, and which side they're
  35120. stuck to.
  35121. */
  35122. void setOrientation (const Orientation orientation);
  35123. /** Returns the current orientation.
  35124. @see setOrientation
  35125. */
  35126. Orientation getOrientation() const throw() { return orientation; }
  35127. /** Deletes all the tabs from the bar.
  35128. @see addTab
  35129. */
  35130. void clearTabs();
  35131. /** Adds a tab to the bar.
  35132. Tabs are added in left-to-right reading order.
  35133. If this is the first tab added, it'll also be automatically selected.
  35134. */
  35135. void addTab (const String& tabName,
  35136. const Colour& tabBackgroundColour,
  35137. int insertIndex = -1);
  35138. /** Changes the name of one of the tabs. */
  35139. void setTabName (const int tabIndex,
  35140. const String& newName);
  35141. /** Gets rid of one of the tabs. */
  35142. void removeTab (const int tabIndex);
  35143. /** Moves a tab to a new index in the list.
  35144. Pass -1 as the index to move it to the end of the list.
  35145. */
  35146. void moveTab (const int currentIndex,
  35147. const int newIndex);
  35148. /** Returns the number of tabs in the bar. */
  35149. int getNumTabs() const;
  35150. /** Returns a list of all the tab names in the bar. */
  35151. const StringArray getTabNames() const;
  35152. /** Changes the currently selected tab.
  35153. This will send a change message and cause a synchronous callback to
  35154. the currentTabChanged() method. (But if the given tab is already selected,
  35155. nothing will be done).
  35156. To deselect all the tabs, use an index of -1.
  35157. */
  35158. void setCurrentTabIndex (int newTabIndex);
  35159. /** Returns the name of the currently selected tab.
  35160. This could be an empty string if none are selected.
  35161. */
  35162. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  35163. /** Returns the index of the currently selected tab.
  35164. This could return -1 if none are selected.
  35165. */
  35166. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  35167. /** Returns the button for a specific tab.
  35168. The button that is returned may be deleted later by this component, so don't hang
  35169. on to the pointer that is returned. A null pointer may be returned if the index is
  35170. out of range.
  35171. */
  35172. TabBarButton* getTabButton (const int index) const;
  35173. /** Callback method to indicate the selected tab has been changed.
  35174. @see setCurrentTabIndex
  35175. */
  35176. virtual void currentTabChanged (const int newCurrentTabIndex,
  35177. const String& newCurrentTabName);
  35178. /** Callback method to indicate that the user has right-clicked on a tab.
  35179. (Or ctrl-clicked on the Mac)
  35180. */
  35181. virtual void popupMenuClickOnTab (const int tabIndex,
  35182. const String& tabName);
  35183. /** Returns the colour of a tab.
  35184. This is the colour that was specified in addTab().
  35185. */
  35186. const Colour getTabBackgroundColour (const int tabIndex);
  35187. /** Changes the background colour of a tab.
  35188. @see addTab, getTabBackgroundColour
  35189. */
  35190. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35191. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35192. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35193. methods.
  35194. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35195. */
  35196. enum ColourIds
  35197. {
  35198. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  35199. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  35200. the look and feel will choose an appropriate colour. */
  35201. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  35202. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  35203. this isn't specified, the look and feel will choose an appropriate
  35204. colour. */
  35205. };
  35206. /** @internal */
  35207. void resized();
  35208. /** @internal */
  35209. void buttonClicked (Button* button);
  35210. /** @internal */
  35211. void lookAndFeelChanged();
  35212. juce_UseDebuggingNewOperator
  35213. protected:
  35214. /** This creates one of the tabs.
  35215. If you need to use custom tab components, you can override this method and
  35216. return your own class instead of the default.
  35217. */
  35218. virtual TabBarButton* createTabButton (const String& tabName,
  35219. const int tabIndex);
  35220. private:
  35221. Orientation orientation;
  35222. StringArray tabs;
  35223. Array <Colour> tabColours;
  35224. int currentTabIndex;
  35225. Component* behindFrontTab;
  35226. Button* extraTabsButton;
  35227. TabbedButtonBar (const TabbedButtonBar&);
  35228. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  35229. };
  35230. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35231. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  35232. /**
  35233. A component with a TabbedButtonBar along one of its sides.
  35234. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  35235. with addTab(), and this will take care of showing the pages for you when the
  35236. user clicks on a different tab.
  35237. @see TabbedButtonBar
  35238. */
  35239. class JUCE_API TabbedComponent : public Component
  35240. {
  35241. public:
  35242. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  35243. Once created, add some tabs with the addTab() method.
  35244. */
  35245. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  35246. /** Destructor. */
  35247. ~TabbedComponent();
  35248. /** Changes the placement of the tabs.
  35249. This will rearrange the layout to place the tabs along the appropriate
  35250. side of this component, and will shift the content component accordingly.
  35251. @see TabbedButtonBar::setOrientation
  35252. */
  35253. void setOrientation (const TabbedButtonBar::Orientation orientation);
  35254. /** Returns the current tab placement.
  35255. @see setOrientation, TabbedButtonBar::getOrientation
  35256. */
  35257. TabbedButtonBar::Orientation getOrientation() const throw();
  35258. /** Specifies how many pixels wide or high the tab-bar should be.
  35259. If the tabs are placed along the top or bottom, this specified the height
  35260. of the bar; if they're along the left or right edges, it'll be the width
  35261. of the bar.
  35262. */
  35263. void setTabBarDepth (const int newDepth);
  35264. /** Returns the current thickness of the tab bar.
  35265. @see setTabBarDepth
  35266. */
  35267. int getTabBarDepth() const throw() { return tabDepth; }
  35268. /** Specifies the thickness of an outline that should be drawn around the content component.
  35269. If this thickness is > 0, a line will be drawn around the three sides of the content
  35270. component which don't touch the tab-bar, and the content component will be inset by this amount.
  35271. To set the colour of the line, use setColour (outlineColourId, ...).
  35272. */
  35273. void setOutline (const int newThickness);
  35274. /** Specifies a gap to leave around the edge of the content component.
  35275. Each edge of the content component will be indented by the given number of pixels.
  35276. */
  35277. void setIndent (const int indentThickness);
  35278. /** Removes all the tabs from the bar.
  35279. @see TabbedButtonBar::clearTabs
  35280. */
  35281. void clearTabs();
  35282. /** Adds a tab to the tab-bar.
  35283. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  35284. is true, it will be deleted when the tab is removed or when this object is
  35285. deleted.
  35286. @see TabbedButtonBar::addTab
  35287. */
  35288. void addTab (const String& tabName,
  35289. const Colour& tabBackgroundColour,
  35290. Component* const contentComponent,
  35291. const bool deleteComponentWhenNotNeeded,
  35292. const int insertIndex = -1);
  35293. /** Changes the name of one of the tabs. */
  35294. void setTabName (const int tabIndex,
  35295. const String& newName);
  35296. /** Gets rid of one of the tabs. */
  35297. void removeTab (const int tabIndex);
  35298. /** Returns the number of tabs in the bar. */
  35299. int getNumTabs() const;
  35300. /** Returns a list of all the tab names in the bar. */
  35301. const StringArray getTabNames() const;
  35302. /** Returns the content component that was added for the given index.
  35303. Be sure not to use or delete the components that are returned, as this may interfere
  35304. with the TabbedComponent's use of them.
  35305. */
  35306. Component* getTabContentComponent (const int tabIndex) const throw();
  35307. /** Returns the colour of one of the tabs. */
  35308. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  35309. /** Changes the background colour of one of the tabs. */
  35310. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35311. /** Changes the currently-selected tab.
  35312. To deselect all the tabs, pass -1 as the index.
  35313. @see TabbedButtonBar::setCurrentTabIndex
  35314. */
  35315. void setCurrentTabIndex (const int newTabIndex);
  35316. /** Returns the index of the currently selected tab.
  35317. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  35318. */
  35319. int getCurrentTabIndex() const;
  35320. /** Returns the name of the currently selected tab.
  35321. @see addTab, TabbedButtonBar::getCurrentTabName()
  35322. */
  35323. const String& getCurrentTabName() const;
  35324. /** Returns the current component that's filling the panel.
  35325. This will return 0 if there isn't one.
  35326. */
  35327. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  35328. /** Callback method to indicate the selected tab has been changed.
  35329. @see setCurrentTabIndex
  35330. */
  35331. virtual void currentTabChanged (const int newCurrentTabIndex,
  35332. const String& newCurrentTabName);
  35333. /** Callback method to indicate that the user has right-clicked on a tab.
  35334. (Or ctrl-clicked on the Mac)
  35335. */
  35336. virtual void popupMenuClickOnTab (const int tabIndex,
  35337. const String& tabName);
  35338. /** Returns the tab button bar component that is being used.
  35339. */
  35340. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  35341. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35342. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35343. methods.
  35344. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35345. */
  35346. enum ColourIds
  35347. {
  35348. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  35349. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  35350. (See setOutline) */
  35351. };
  35352. /** @internal */
  35353. void paint (Graphics& g);
  35354. /** @internal */
  35355. void resized();
  35356. /** @internal */
  35357. void lookAndFeelChanged();
  35358. juce_UseDebuggingNewOperator
  35359. protected:
  35360. TabbedButtonBar* tabs;
  35361. /** This creates one of the tab buttons.
  35362. If you need to use custom tab components, you can override this method and
  35363. return your own class instead of the default.
  35364. */
  35365. virtual TabBarButton* createTabButton (const String& tabName,
  35366. const int tabIndex);
  35367. private:
  35368. Array <Component*> contentComponents;
  35369. Component* panelComponent;
  35370. int tabDepth;
  35371. int outlineThickness, edgeIndent;
  35372. friend class TabCompButtonBar;
  35373. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  35374. TabbedComponent (const TabbedComponent&);
  35375. const TabbedComponent& operator= (const TabbedComponent&);
  35376. };
  35377. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35378. /********* End of inlined file: juce_TabbedComponent.h *********/
  35379. /********* Start of inlined file: juce_DocumentWindow.h *********/
  35380. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35381. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  35382. /********* Start of inlined file: juce_ResizableWindow.h *********/
  35383. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35384. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35385. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  35386. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35387. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35388. /********* Start of inlined file: juce_DropShadower.h *********/
  35389. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  35390. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  35391. /**
  35392. Adds a drop-shadow to a component.
  35393. This object creates and manages a set of components which sit around a
  35394. component, creating a gaussian shadow around it. The components will track
  35395. the position of the component and if it's brought to the front they'll also
  35396. follow this.
  35397. For desktop windows you don't need to use this class directly - just
  35398. set the Component::windowHasDropShadow flag when calling
  35399. Component::addToDesktop(), and the system will create one of these if it's
  35400. needed (which it obviously isn't on the Mac, for example).
  35401. */
  35402. class JUCE_API DropShadower : public ComponentListener
  35403. {
  35404. public:
  35405. /** Creates a DropShadower.
  35406. @param alpha the opacity of the shadows, from 0 to 1.0
  35407. @param xOffset the horizontal displacement of the shadow, in pixels
  35408. @param yOffset the vertical displacement of the shadow, in pixels
  35409. @param blurRadius the radius of the blur to use for creating the shadow
  35410. */
  35411. DropShadower (const float alpha = 0.5f,
  35412. const int xOffset = 1,
  35413. const int yOffset = 5,
  35414. const float blurRadius = 10.0f);
  35415. /** Destructor. */
  35416. virtual ~DropShadower();
  35417. /** Attaches the DropShadower to the component you want to shadow. */
  35418. void setOwner (Component* componentToFollow);
  35419. /** @internal */
  35420. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35421. /** @internal */
  35422. void componentBroughtToFront (Component& component);
  35423. /** @internal */
  35424. void componentChildrenChanged (Component& component);
  35425. /** @internal */
  35426. void componentParentHierarchyChanged (Component& component);
  35427. /** @internal */
  35428. void componentVisibilityChanged (Component& component);
  35429. juce_UseDebuggingNewOperator
  35430. private:
  35431. Component* owner;
  35432. int numShadows;
  35433. Component* shadowWindows[4];
  35434. Image* shadowImageSections[12];
  35435. const int shadowEdge, xOffset, yOffset;
  35436. const float alpha, blurRadius;
  35437. bool inDestructor, reentrant;
  35438. void updateShadows();
  35439. void setShadowImage (Image* const src,
  35440. const int num,
  35441. const int w, const int h,
  35442. const int sx, const int sy) throw();
  35443. void bringShadowWindowsToFront();
  35444. void deleteShadowWindows();
  35445. DropShadower (const DropShadower&);
  35446. const DropShadower& operator= (const DropShadower&);
  35447. };
  35448. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  35449. /********* End of inlined file: juce_DropShadower.h *********/
  35450. /**
  35451. A base class for top-level windows.
  35452. This class is used for components that are considered a major part of your
  35453. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  35454. etc. Things like menus that pop up briefly aren't derived from it.
  35455. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  35456. could itself be the child of another component.
  35457. The class manages a list of all instances of top-level windows that are in use,
  35458. and each one is also given the concept of being "active". The active window is
  35459. one that is actively being used by the user. This isn't quite the same as the
  35460. component with the keyboard focus, because there may be a popup menu or other
  35461. temporary window which gets keyboard focus while the active top level window is
  35462. unchanged.
  35463. A top-level window also has an optional drop-shadow.
  35464. @see ResizableWindow, DocumentWindow, DialogWindow
  35465. */
  35466. class JUCE_API TopLevelWindow : public Component
  35467. {
  35468. public:
  35469. /** Creates a TopLevelWindow.
  35470. @param name the name to give the component
  35471. @param addToDesktop if true, the window will be automatically added to the
  35472. desktop; if false, you can use it as a child component
  35473. */
  35474. TopLevelWindow (const String& name,
  35475. const bool addToDesktop);
  35476. /** Destructor. */
  35477. ~TopLevelWindow();
  35478. /** True if this is currently the TopLevelWindow that is actively being used.
  35479. This isn't quite the same as having keyboard focus, because the focus may be
  35480. on a child component or a temporary pop-up menu, etc, while this window is
  35481. still considered to be active.
  35482. @see activeWindowStatusChanged
  35483. */
  35484. bool isActiveWindow() const throw() { return windowIsActive_; }
  35485. /** This will set the bounds of the window so that it's centred in front of another
  35486. window.
  35487. If your app has a few windows open and want to pop up a dialog box for one of
  35488. them, you can use this to show it in front of the relevent parent window, which
  35489. is a bit neater than just having it appear in the middle of the screen.
  35490. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  35491. be used instead. If no window is focused, it'll just default to the middle of the
  35492. screen.
  35493. */
  35494. void centreAroundComponent (Component* componentToCentreAround,
  35495. const int width, const int height);
  35496. /** Turns the drop-shadow on and off. */
  35497. void setDropShadowEnabled (const bool useShadow);
  35498. /** Sets whether an OS-native title bar will be used, or a Juce one.
  35499. @see isUsingNativeTitleBar
  35500. */
  35501. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  35502. /** Returns true if the window is currently using an OS-native title bar.
  35503. @see setUsingNativeTitleBar
  35504. */
  35505. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  35506. /** Returns the number of TopLevelWindow objects currently in use.
  35507. @see getTopLevelWindow
  35508. */
  35509. static int getNumTopLevelWindows() throw();
  35510. /** Returns one of the TopLevelWindow objects currently in use.
  35511. The index is 0 to (getNumTopLevelWindows() - 1).
  35512. */
  35513. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  35514. /** Returns the currently-active top level window.
  35515. There might not be one, of course, so this can return 0.
  35516. */
  35517. static TopLevelWindow* getActiveTopLevelWindow() throw();
  35518. juce_UseDebuggingNewOperator
  35519. /** @internal */
  35520. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  35521. protected:
  35522. /** This callback happens when this window becomes active or inactive.
  35523. @see isActiveWindow
  35524. */
  35525. virtual void activeWindowStatusChanged();
  35526. /** @internal */
  35527. void focusOfChildComponentChanged (FocusChangeType cause);
  35528. /** @internal */
  35529. void parentHierarchyChanged();
  35530. /** @internal */
  35531. void visibilityChanged();
  35532. /** @internal */
  35533. virtual int getDesktopWindowStyleFlags() const;
  35534. /** @internal */
  35535. void recreateDesktopWindow();
  35536. private:
  35537. friend class TopLevelWindowManager;
  35538. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  35539. DropShadower* shadower;
  35540. void setWindowActive (const bool isNowActive) throw();
  35541. TopLevelWindow (const TopLevelWindow&);
  35542. const TopLevelWindow& operator= (const TopLevelWindow&);
  35543. };
  35544. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  35545. /********* End of inlined file: juce_TopLevelWindow.h *********/
  35546. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  35547. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35548. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35549. /**
  35550. A component that resizes its parent window when dragged.
  35551. This component forms a frame around the edge of a component, allowing it to
  35552. be dragged by the edges or corners to resize it - like the way windows are
  35553. resized in MSWindows or Linux.
  35554. To use it, just add it to your component, making it fill the entire parent component
  35555. (there's a mouse hit-test that only traps mouse-events which land around the
  35556. edge of the component, so it's even ok to put it on top of any other components
  35557. you're using). Make sure you rescale the resizer component to fill the parent
  35558. each time the parent's size changes.
  35559. @see ResizableCornerComponent
  35560. */
  35561. class JUCE_API ResizableBorderComponent : public Component
  35562. {
  35563. public:
  35564. /** Creates a resizer.
  35565. Pass in the target component which you want to be resized when this one is
  35566. dragged.
  35567. The target component will usually be a parent of the resizer component, but this
  35568. isn't mandatory.
  35569. Remember that when the target component is resized, it'll need to move and
  35570. resize this component to keep it in place, as this won't happen automatically.
  35571. If the constrainer parameter is non-zero, then this object will be used to enforce
  35572. limits on the size and position that the component can be stretched to. Make sure
  35573. that the constrainer isn't deleted while still in use by this object.
  35574. @see ComponentBoundsConstrainer
  35575. */
  35576. ResizableBorderComponent (Component* const componentToResize,
  35577. ComponentBoundsConstrainer* const constrainer);
  35578. /** Destructor. */
  35579. ~ResizableBorderComponent();
  35580. /** Specifies how many pixels wide the draggable edges of this component are.
  35581. @see getBorderThickness
  35582. */
  35583. void setBorderThickness (const BorderSize& newBorderSize) throw();
  35584. /** Returns the number of pixels wide that the draggable edges of this component are.
  35585. @see setBorderThickness
  35586. */
  35587. const BorderSize getBorderThickness() const throw();
  35588. juce_UseDebuggingNewOperator
  35589. protected:
  35590. /** @internal */
  35591. void paint (Graphics& g);
  35592. /** @internal */
  35593. void mouseEnter (const MouseEvent& e);
  35594. /** @internal */
  35595. void mouseMove (const MouseEvent& e);
  35596. /** @internal */
  35597. void mouseDown (const MouseEvent& e);
  35598. /** @internal */
  35599. void mouseDrag (const MouseEvent& e);
  35600. /** @internal */
  35601. void mouseUp (const MouseEvent& e);
  35602. /** @internal */
  35603. bool hitTest (int x, int y);
  35604. private:
  35605. Component* const component;
  35606. ComponentBoundsConstrainer* constrainer;
  35607. BorderSize borderSize;
  35608. int originalX, originalY, originalW, originalH;
  35609. int mouseZone;
  35610. void updateMouseZone (const MouseEvent& e) throw();
  35611. ResizableBorderComponent (const ResizableBorderComponent&);
  35612. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  35613. };
  35614. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  35615. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  35616. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  35617. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35618. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35619. /** A component that resizes a parent window when dragged.
  35620. This is the small triangular stripey resizer component you get in the bottom-right
  35621. of windows (more commonly on the Mac than Windows). Put one in the corner of
  35622. a larger component and it will automatically resize its parent when it gets dragged
  35623. around.
  35624. @see ResizableFrameComponent
  35625. */
  35626. class JUCE_API ResizableCornerComponent : public Component
  35627. {
  35628. public:
  35629. /** Creates a resizer.
  35630. Pass in the target component which you want to be resized when this one is
  35631. dragged.
  35632. The target component will usually be a parent of the resizer component, but this
  35633. isn't mandatory.
  35634. Remember that when the target component is resized, it'll need to move and
  35635. resize this component to keep it in place, as this won't happen automatically.
  35636. If the constrainer parameter is non-zero, then this object will be used to enforce
  35637. limits on the size and position that the component can be stretched to. Make sure
  35638. that the constrainer isn't deleted while still in use by this object. If you
  35639. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  35640. @see ComponentBoundsConstrainer
  35641. */
  35642. ResizableCornerComponent (Component* const componentToResize,
  35643. ComponentBoundsConstrainer* const constrainer);
  35644. /** Destructor. */
  35645. ~ResizableCornerComponent();
  35646. juce_UseDebuggingNewOperator
  35647. protected:
  35648. /** @internal */
  35649. void paint (Graphics& g);
  35650. /** @internal */
  35651. void mouseDown (const MouseEvent& e);
  35652. /** @internal */
  35653. void mouseDrag (const MouseEvent& e);
  35654. /** @internal */
  35655. void mouseUp (const MouseEvent& e);
  35656. /** @internal */
  35657. bool hitTest (int x, int y);
  35658. private:
  35659. Component* const component;
  35660. ComponentBoundsConstrainer* constrainer;
  35661. int originalX, originalY, originalW, originalH;
  35662. ResizableCornerComponent (const ResizableCornerComponent&);
  35663. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  35664. };
  35665. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  35666. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  35667. /**
  35668. A base class for top-level windows that can be dragged around and resized.
  35669. To add content to the window, use its setContentComponent() method to
  35670. give it a component that will remain positioned inside it (leaving a gap around
  35671. the edges for a border).
  35672. It's not advisable to add child components directly to a ResizableWindow: put them
  35673. inside your content component instead. And overriding methods like resized(), moved(), etc
  35674. is also not recommended - instead override these methods for your content component.
  35675. (If for some obscure reason you do need to override these methods, always remember to
  35676. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35677. decorations correctly).
  35678. By default resizing isn't enabled - use the setResizable() method to enable it and
  35679. to choose the style of resizing to use.
  35680. @see TopLevelWindow
  35681. */
  35682. class JUCE_API ResizableWindow : public TopLevelWindow
  35683. {
  35684. public:
  35685. /** Creates a ResizableWindow.
  35686. This constructor doesn't specify a background colour, so the LookAndFeel's default
  35687. background colour will be used.
  35688. @param name the name to give the component
  35689. @param addToDesktop if true, the window will be automatically added to the
  35690. desktop; if false, you can use it as a child component
  35691. */
  35692. ResizableWindow (const String& name,
  35693. const bool addToDesktop);
  35694. /** Creates a ResizableWindow.
  35695. @param name the name to give the component
  35696. @param backgroundColour the colour to use for filling the window's background.
  35697. @param addToDesktop if true, the window will be automatically added to the
  35698. desktop; if false, you can use it as a child component
  35699. */
  35700. ResizableWindow (const String& name,
  35701. const Colour& backgroundColour,
  35702. const bool addToDesktop);
  35703. /** Destructor.
  35704. If a content component has been set with setContentComponent(), it
  35705. will be deleted.
  35706. */
  35707. ~ResizableWindow();
  35708. /** Returns the colour currently being used for the window's background.
  35709. As a convenience the window will fill itself with this colour, but you
  35710. can override the paint() method if you need more customised behaviour.
  35711. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  35712. @see setBackgroundColour
  35713. */
  35714. const Colour getBackgroundColour() const throw();
  35715. /** Changes the colour currently being used for the window's background.
  35716. As a convenience the window will fill itself with this colour, but you
  35717. can override the paint() method if you need more customised behaviour.
  35718. Note that the opaque state of this window is altered by this call to reflect
  35719. the opacity of the colour passed-in. On window systems which can't support
  35720. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35721. be using this class as a base for a semi-transparent component anyway).
  35722. You can also use the ResizableWindow::backgroundColourId colour id to set
  35723. this colour.
  35724. @see getBackgroundColour
  35725. */
  35726. void setBackgroundColour (const Colour& newColour);
  35727. /** Make the window resizable or fixed.
  35728. @param shouldBeResizable whether it's resizable at all
  35729. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35730. bottom-right; if false, it'll use a ResizableBorderComponent
  35731. around the edge
  35732. @see setResizeLimits, isResizable
  35733. */
  35734. void setResizable (const bool shouldBeResizable,
  35735. const bool useBottomRightCornerResizer);
  35736. /** True if resizing is enabled.
  35737. @see setResizable
  35738. */
  35739. bool isResizable() const throw();
  35740. /** This sets the maximum and minimum sizes for the window.
  35741. If the window's current size is outside these limits, it will be resized to
  35742. make sure it's within them.
  35743. Calling setBounds() on the component will bypass any size checking - it's only when
  35744. the window is being resized by the user that these values are enforced.
  35745. @see setResizable, setFixedAspectRatio
  35746. */
  35747. void setResizeLimits (const int newMinimumWidth,
  35748. const int newMinimumHeight,
  35749. const int newMaximumWidth,
  35750. const int newMaximumHeight) throw();
  35751. /** Returns the bounds constrainer object that this window is using.
  35752. You can access this to change its properties.
  35753. */
  35754. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35755. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35756. A pointer to the object you pass in will be kept, but it won't be deleted
  35757. by this object, so it's the caller's responsiblity to manage it.
  35758. If you pass 0, then no contraints will be placed on the positioning of the window.
  35759. */
  35760. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35761. /** Calls the window's setBounds method, after first checking these bounds
  35762. with the current constrainer.
  35763. @see setConstrainer
  35764. */
  35765. void setBoundsConstrained (int x, int y, int width, int height);
  35766. /** Returns true if the window is currently in full-screen mode.
  35767. @see setFullScreen
  35768. */
  35769. bool isFullScreen() const;
  35770. /** Puts the window into full-screen mode, or restores it to its normal size.
  35771. If true, the window will become full-screen; if false, it will return to the
  35772. last size it was before being made full-screen.
  35773. @see isFullScreen
  35774. */
  35775. void setFullScreen (const bool shouldBeFullScreen);
  35776. /** Returns true if the window is currently minimised.
  35777. @see setMinimised
  35778. */
  35779. bool isMinimised() const;
  35780. /** Minimises the window, or restores it to its previous position and size.
  35781. When being un-minimised, it'll return to the last position and size it
  35782. was in before being minimised.
  35783. @see isMinimised
  35784. */
  35785. void setMinimised (const bool shouldMinimise);
  35786. /** Returns a string which encodes the window's current size and position.
  35787. This string will encapsulate the window's size, position, and whether it's
  35788. in full-screen mode. It's intended for letting your application save and
  35789. restore a window's position.
  35790. Use the restoreWindowStateFromString() to restore from a saved state.
  35791. @see restoreWindowStateFromString
  35792. */
  35793. const String getWindowStateAsString();
  35794. /** Restores the window to a previously-saved size and position.
  35795. This restores the window's size, positon and full-screen status from an
  35796. string that was previously created with the getWindowStateAsString()
  35797. method.
  35798. @returns false if the string wasn't a valid window state
  35799. @see getWindowStateAsString
  35800. */
  35801. bool restoreWindowStateFromString (const String& previousState);
  35802. /** Returns the current content component.
  35803. This will be the component set by setContentComponent(), or 0 if none
  35804. has yet been specified.
  35805. @see setContentComponent
  35806. */
  35807. Component* getContentComponent() const throw() { return contentComponent; }
  35808. /** Changes the current content component.
  35809. This sets a component that will be placed in the centre of the ResizableWindow,
  35810. (leaving a space around the edge for the border).
  35811. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35812. with addChildComponent(). Instead, add them to the content component.
  35813. @param newContentComponent the new component to use (or null to not use one) - this
  35814. component will be deleted either when replaced by another call
  35815. to this method, or when the ResizableWindow is deleted.
  35816. To remove a content component without deleting it, use
  35817. setContentComponent (0, false).
  35818. @param deleteOldOne if true, the previous content component will be deleted; if
  35819. false, the previous component will just be removed without
  35820. deleting it.
  35821. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35822. it always fits around the size of the content component. If false, the
  35823. new content will be resized to fit the current space available.
  35824. */
  35825. void setContentComponent (Component* const newContentComponent,
  35826. const bool deleteOldOne = true,
  35827. const bool resizeToFit = false);
  35828. /** Changes the window so that the content component ends up with the specified size.
  35829. This is basically a setSize call on the window, but which adds on the borders,
  35830. so you can specify the content component's target size.
  35831. */
  35832. void setContentComponentSize (int width, int height);
  35833. /** A set of colour IDs to use to change the colour of various aspects of the window.
  35834. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35835. methods.
  35836. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35837. */
  35838. enum ColourIds
  35839. {
  35840. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  35841. };
  35842. juce_UseDebuggingNewOperator
  35843. protected:
  35844. /** @internal */
  35845. void paint (Graphics& g);
  35846. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35847. void moved();
  35848. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35849. void resized();
  35850. /** @internal */
  35851. void mouseDown (const MouseEvent& e);
  35852. /** @internal */
  35853. void mouseDrag (const MouseEvent& e);
  35854. /** @internal */
  35855. void lookAndFeelChanged();
  35856. /** @internal */
  35857. void childBoundsChanged (Component* child);
  35858. /** @internal */
  35859. void parentSizeChanged();
  35860. /** @internal */
  35861. void visibilityChanged();
  35862. /** @internal */
  35863. void activeWindowStatusChanged();
  35864. /** @internal */
  35865. int getDesktopWindowStyleFlags() const;
  35866. /** Returns the width of the border to use around the window.
  35867. @see getContentComponentBorder
  35868. */
  35869. virtual const BorderSize getBorderThickness();
  35870. /** Returns the insets to use when positioning the content component.
  35871. @see getBorderThickness
  35872. */
  35873. virtual const BorderSize getContentComponentBorder();
  35874. #ifdef JUCE_DEBUG
  35875. /** Overridden to warn people about adding components directly to this component
  35876. instead of using setContentComponent().
  35877. If you know what you're doing and are sure you really want to add a component, specify
  35878. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35879. */
  35880. void addChildComponent (Component* const child, int zOrder = -1);
  35881. /** Overridden to warn people about adding components directly to this component
  35882. instead of using setContentComponent().
  35883. If you know what you're doing and are sure you really want to add a component, specify
  35884. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35885. */
  35886. void addAndMakeVisible (Component* const child, int zOrder = -1);
  35887. #endif
  35888. ResizableCornerComponent* resizableCorner;
  35889. ResizableBorderComponent* resizableBorder;
  35890. private:
  35891. Component* contentComponent;
  35892. bool resizeToFitContent, fullscreen;
  35893. ComponentDragger dragger;
  35894. Rectangle lastNonFullScreenPos;
  35895. ComponentBoundsConstrainer defaultConstrainer;
  35896. ComponentBoundsConstrainer* constrainer;
  35897. #ifdef JUCE_DEBUG
  35898. bool hasBeenResized;
  35899. #endif
  35900. void updateLastPos();
  35901. ResizableWindow (const ResizableWindow&);
  35902. const ResizableWindow& operator= (const ResizableWindow&);
  35903. // (xxx remove these eventually)
  35904. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35905. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  35906. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35907. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  35908. };
  35909. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35910. /********* End of inlined file: juce_ResizableWindow.h *********/
  35911. /**
  35912. A resizable window with a title bar and maximise, minimise and close buttons.
  35913. This subclass of ResizableWindow creates a fairly standard type of window with
  35914. a title bar and various buttons. The name of the component is shown in the
  35915. title bar, and an icon can optionally be specified with setIcon().
  35916. All the methods available to a ResizableWindow are also available to this,
  35917. so it can easily be made resizable, minimised, maximised, etc.
  35918. It's not advisable to add child components directly to a DocumentWindow: put them
  35919. inside your content component instead. And overriding methods like resized(), moved(), etc
  35920. is also not recommended - instead override these methods for your content component.
  35921. (If for some obscure reason you do need to override these methods, always remember to
  35922. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35923. decorations correctly).
  35924. You can also automatically add a menu bar to the window, using the setMenuBar()
  35925. method.
  35926. @see ResizableWindow, DialogWindow
  35927. */
  35928. class JUCE_API DocumentWindow : public ResizableWindow
  35929. {
  35930. public:
  35931. /** The set of available button-types that can be put on the title bar.
  35932. @see setTitleBarButtonsRequired
  35933. */
  35934. enum TitleBarButtons
  35935. {
  35936. minimiseButton = 1,
  35937. maximiseButton = 2,
  35938. closeButton = 4,
  35939. /** A combination of all the buttons above. */
  35940. allButtons = 7
  35941. };
  35942. /** Creates a DocumentWindow.
  35943. @param name the name to give the component - this is also
  35944. the title shown at the top of the window. To change
  35945. this later, use setName()
  35946. @param backgroundColour the colour to use for filling the window's background.
  35947. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35948. should be shown on the title bar. This value is a bitwise
  35949. combination of values from the TitleBarButtons enum. Note
  35950. that it can be "allButtons" to get them all. You
  35951. can change this later with the setTitleBarButtonsRequired()
  35952. method, which can also specify where they are positioned.
  35953. @param addToDesktop if true, the window will be automatically added to the
  35954. desktop; if false, you can use it as a child component
  35955. @see TitleBarButtons
  35956. */
  35957. DocumentWindow (const String& name,
  35958. const Colour& backgroundColour,
  35959. const int requiredButtons,
  35960. const bool addToDesktop = true);
  35961. /** Destructor.
  35962. If a content component has been set with setContentComponent(), it
  35963. will be deleted.
  35964. */
  35965. ~DocumentWindow();
  35966. /** Changes the component's name.
  35967. (This is overridden from Component::setName() to cause a repaint, as
  35968. the name is what gets drawn across the window's title bar).
  35969. */
  35970. void setName (const String& newName);
  35971. /** Sets an icon to show in the title bar, next to the title.
  35972. A copy is made internally of the image, so the caller can delete the
  35973. image after calling this. If 0 is passed-in, any existing icon will be
  35974. removed.
  35975. */
  35976. void setIcon (const Image* imageToUse);
  35977. /** Changes the height of the title-bar. */
  35978. void setTitleBarHeight (const int newHeight);
  35979. /** Returns the current title bar height. */
  35980. int getTitleBarHeight() const;
  35981. /** Changes the set of title-bar buttons being shown.
  35982. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  35983. should be shown on the title bar. This value is a bitwise
  35984. combination of values from the TitleBarButtons enum. Note
  35985. that it can be "allButtons" to get them all.
  35986. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  35987. left side of the bar; if false, they'll be placed at the right
  35988. */
  35989. void setTitleBarButtonsRequired (const int requiredButtons,
  35990. const bool positionTitleBarButtonsOnLeft);
  35991. /** Sets whether the title should be centred within the window.
  35992. If true, the title text is shown in the middle of the title-bar; if false,
  35993. it'll be shown at the left of the bar.
  35994. */
  35995. void setTitleBarTextCentred (const bool textShouldBeCentred);
  35996. /** Creates a menu inside this window.
  35997. @param menuBarModel this specifies a MenuBarModel that should be used to
  35998. generate the contents of a menu bar that will be placed
  35999. just below the title bar, and just above any content
  36000. component. If this value is zero, any existing menu bar
  36001. will be removed from the component; if non-zero, one will
  36002. be added if it's required.
  36003. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  36004. or less to use the look-and-feel's default size.
  36005. */
  36006. void setMenuBar (MenuBarModel* menuBarModel,
  36007. const int menuBarHeight = 0);
  36008. /** This method is called when the user tries to close the window.
  36009. This is triggered by the user clicking the close button, or using some other
  36010. OS-specific key shortcut or OS menu for getting rid of a window.
  36011. If the window is just a pop-up, you should override this closeButtonPressed()
  36012. method and make it delete the window in whatever way is appropriate for your
  36013. app. E.g. you might just want to call "delete this".
  36014. If your app is centred around this window such that the whole app should quit when
  36015. the window is closed, then you will probably want to use this method as an opportunity
  36016. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  36017. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  36018. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  36019. or closing it via the taskbar icon on Windows).
  36020. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  36021. redirects it to call this method, so any methods of closing the window that are
  36022. caught by userTriedToCloseWindow() will also end up here).
  36023. */
  36024. virtual void closeButtonPressed();
  36025. /** Callback that is triggered when the minimise button is pressed.
  36026. The default implementation of this calls ResizableWindow::setMinimised(), but
  36027. you can override it to do more customised behaviour.
  36028. */
  36029. virtual void minimiseButtonPressed();
  36030. /** Callback that is triggered when the maximise button is pressed, or when the
  36031. title-bar is double-clicked.
  36032. The default implementation of this calls ResizableWindow::setFullScreen(), but
  36033. you can override it to do more customised behaviour.
  36034. */
  36035. virtual void maximiseButtonPressed();
  36036. /** Returns the close button, (or 0 if there isn't one). */
  36037. Button* getCloseButton() const throw();
  36038. /** Returns the minimise button, (or 0 if there isn't one). */
  36039. Button* getMinimiseButton() const throw();
  36040. /** Returns the maximise button, (or 0 if there isn't one). */
  36041. Button* getMaximiseButton() const throw();
  36042. /** A set of colour IDs to use to change the colour of various aspects of the window.
  36043. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36044. methods.
  36045. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36046. */
  36047. enum ColourIds
  36048. {
  36049. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  36050. and feel class how this is used. */
  36051. };
  36052. /** @internal */
  36053. void paint (Graphics& g);
  36054. /** @internal */
  36055. void resized();
  36056. /** @internal */
  36057. void lookAndFeelChanged();
  36058. /** @internal */
  36059. const BorderSize getBorderThickness();
  36060. /** @internal */
  36061. const BorderSize getContentComponentBorder();
  36062. /** @internal */
  36063. void mouseDoubleClick (const MouseEvent& e);
  36064. /** @internal */
  36065. void userTriedToCloseWindow();
  36066. /** @internal */
  36067. void activeWindowStatusChanged();
  36068. /** @internal */
  36069. int getDesktopWindowStyleFlags() const;
  36070. /** @internal */
  36071. void parentHierarchyChanged();
  36072. juce_UseDebuggingNewOperator
  36073. private:
  36074. int titleBarHeight, menuBarHeight, requiredButtons;
  36075. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  36076. Button* titleBarButtons [3];
  36077. Image* titleBarIcon;
  36078. MenuBarComponent* menuBar;
  36079. MenuBarModel* menuBarModel;
  36080. class ButtonListenerProxy : public ButtonListener
  36081. {
  36082. public:
  36083. ButtonListenerProxy();
  36084. void buttonClicked (Button* button);
  36085. DocumentWindow* owner;
  36086. } buttonListener;
  36087. int getBorderSize() const;
  36088. void repaintTitleBar();
  36089. DocumentWindow (const DocumentWindow&);
  36090. const DocumentWindow& operator= (const DocumentWindow&);
  36091. };
  36092. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36093. /********* End of inlined file: juce_DocumentWindow.h *********/
  36094. class MultiDocumentPanel;
  36095. class MDITabbedComponentInternal;
  36096. /**
  36097. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  36098. component.
  36099. It's like a normal DocumentWindow but has some extra functionality to make sure
  36100. everything works nicely inside a MultiDocumentPanel.
  36101. @see MultiDocumentPanel
  36102. */
  36103. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  36104. {
  36105. public:
  36106. /**
  36107. */
  36108. MultiDocumentPanelWindow (const Colour& backgroundColour);
  36109. /** Destructor. */
  36110. ~MultiDocumentPanelWindow();
  36111. /** @internal */
  36112. void maximiseButtonPressed();
  36113. /** @internal */
  36114. void closeButtonPressed();
  36115. /** @internal */
  36116. void activeWindowStatusChanged();
  36117. /** @internal */
  36118. void broughtToFront();
  36119. juce_UseDebuggingNewOperator
  36120. private:
  36121. void updateOrder();
  36122. MultiDocumentPanel* getOwner() const throw();
  36123. };
  36124. /**
  36125. A component that contains a set of other components either in floating windows
  36126. or tabs.
  36127. This acts as a panel that can be used to hold a set of open document windows, with
  36128. different layout modes.
  36129. Use addDocument() and closeDocument() to add or remove components from the
  36130. panel - never use any of the Component methods to access the panel's child
  36131. components directly, as these are managed internally.
  36132. */
  36133. class JUCE_API MultiDocumentPanel : public Component,
  36134. private ComponentListener
  36135. {
  36136. public:
  36137. /** Creates an empty panel.
  36138. Use addDocument() and closeDocument() to add or remove components from the
  36139. panel - never use any of the Component methods to access the panel's child
  36140. components directly, as these are managed internally.
  36141. */
  36142. MultiDocumentPanel();
  36143. /** Destructor.
  36144. When deleted, this will call closeAllDocuments (false) to make sure all its
  36145. components are deleted. If you need to make sure all documents are saved
  36146. before closing, then you should call closeAllDocuments (true) and check that
  36147. it returns true before deleting the panel.
  36148. */
  36149. ~MultiDocumentPanel();
  36150. /** Tries to close all the documents.
  36151. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36152. be called for each open document, and any of these calls fails, this method
  36153. will stop and return false, leaving some documents still open.
  36154. If checkItsOkToCloseFirst is false, then all documents will be closed
  36155. unconditionally.
  36156. @see closeDocument
  36157. */
  36158. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  36159. /** Adds a document component to the panel.
  36160. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  36161. this will fail and return false. (If it does fail, the component passed-in will not be
  36162. deleted, even if deleteWhenRemoved was set to true).
  36163. The MultiDocumentPanel will deal with creating a window border to go around your component,
  36164. so just pass in the bare content component here, no need to give it a ResizableWindow
  36165. or DocumentWindow.
  36166. @param component the component to add
  36167. @param backgroundColour the background colour to use to fill the component's
  36168. window or tab
  36169. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  36170. or closeAllDocuments(), then it will be deleted. If false, then
  36171. the caller must handle the component's deletion
  36172. */
  36173. bool addDocument (Component* const component,
  36174. const Colour& backgroundColour,
  36175. const bool deleteWhenRemoved);
  36176. /** Closes one of the documents.
  36177. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36178. be called, and if it fails, this method will return false without closing the
  36179. document.
  36180. If checkItsOkToCloseFirst is false, then the documents will be closed
  36181. unconditionally.
  36182. The component will be deleted if the deleteWhenRemoved parameter was set to
  36183. true when it was added with addDocument.
  36184. @see addDocument, closeAllDocuments
  36185. */
  36186. bool closeDocument (Component* component,
  36187. const bool checkItsOkToCloseFirst);
  36188. /** Returns the number of open document windows.
  36189. @see getDocument
  36190. */
  36191. int getNumDocuments() const throw();
  36192. /** Returns one of the open documents.
  36193. The order of the documents in this array may change when they are added, removed
  36194. or moved around.
  36195. @see getNumDocuments
  36196. */
  36197. Component* getDocument (const int index) const throw();
  36198. /** Returns the document component that is currently focused or on top.
  36199. If currently using floating windows, then this will be the component in the currently
  36200. active window, or the top component if none are active.
  36201. If it's currently in tabbed mode, then it'll return the component in the active tab.
  36202. @see setActiveDocument
  36203. */
  36204. Component* getActiveDocument() const throw();
  36205. /** Makes one of the components active and brings it to the top.
  36206. @see getActiveDocument
  36207. */
  36208. void setActiveDocument (Component* component);
  36209. /** Callback which gets invoked when the currently-active document changes. */
  36210. virtual void activeDocumentChanged();
  36211. /** Sets a limit on how many windows can be open at once.
  36212. If this is zero or less there's no limit (the default). addDocument() will fail
  36213. if this number is exceeded.
  36214. */
  36215. void setMaximumNumDocuments (const int maximumNumDocuments);
  36216. /** Sets an option to make the document fullscreen if there's only one document open.
  36217. If set to true, then if there's only one document, it'll fill the whole of this
  36218. component without tabs or a window border. If false, then tabs or a window
  36219. will always be shown, even if there's only one document. If there's more than
  36220. one document open, then this option makes no difference.
  36221. */
  36222. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  36223. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  36224. */
  36225. bool isFullscreenWhenOneDocument() const throw();
  36226. /** The different layout modes available. */
  36227. enum LayoutMode
  36228. {
  36229. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  36230. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  36231. };
  36232. /** Changes the panel's mode.
  36233. @see LayoutMode, getLayoutMode
  36234. */
  36235. void setLayoutMode (const LayoutMode newLayoutMode);
  36236. /** Returns the current layout mode. */
  36237. LayoutMode getLayoutMode() const throw() { return mode; }
  36238. /** Sets the background colour for the whole panel.
  36239. Each document has its own background colour, but this is the one used to fill the areas
  36240. behind them.
  36241. */
  36242. void setBackgroundColour (const Colour& newBackgroundColour);
  36243. /** Returns the current background colour.
  36244. @see setBackgroundColour
  36245. */
  36246. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  36247. /** A subclass must override this to say whether its currently ok for a document
  36248. to be closed.
  36249. This method is called by closeDocument() and closeAllDocuments() to indicate that
  36250. a document should be saved if possible, ready for it to be closed.
  36251. If this method returns true, then it means the document is ok and can be closed.
  36252. If it returns false, then it means that the closeDocument() method should stop
  36253. and not close.
  36254. Normally, you'd use this method to ask the user if they want to save any changes,
  36255. then return true if the save operation went ok. If the user cancelled the save
  36256. operation you could return false here to abort the close operation.
  36257. If your component is based on the FileBasedDocument class, then you'd probably want
  36258. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  36259. FileBasedDocument::savedOk
  36260. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  36261. */
  36262. virtual bool tryToCloseDocument (Component* component) = 0;
  36263. /** Creates a new window to be used for a document.
  36264. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  36265. but you might want to override it to return a custom component.
  36266. */
  36267. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  36268. /** @internal */
  36269. void paint (Graphics& g);
  36270. /** @internal */
  36271. void resized();
  36272. /** @internal */
  36273. void componentNameChanged (Component&);
  36274. juce_UseDebuggingNewOperator
  36275. private:
  36276. LayoutMode mode;
  36277. Array <Component*> components;
  36278. TabbedComponent* tabComponent;
  36279. Colour backgroundColour;
  36280. int maximumNumDocuments, numDocsBeforeTabsUsed;
  36281. friend class MultiDocumentPanelWindow;
  36282. friend class MDITabbedComponentInternal;
  36283. Component* getContainerComp (Component* c) const;
  36284. void updateOrder();
  36285. void addWindow (Component* component);
  36286. };
  36287. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36288. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  36289. #endif
  36290. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36291. #endif
  36292. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36293. #endif
  36294. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  36295. #endif
  36296. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36297. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  36298. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36299. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36300. /**
  36301. For laying out a set of components, where the components have preferred sizes
  36302. and size limits, but where they are allowed to stretch to fill the available
  36303. space.
  36304. For example, if you have a component containing several other components, and
  36305. each one should be given a share of the total size, you could use one of these
  36306. to resize the child components when the parent component is resized. Then
  36307. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  36308. A StretchableLayoutManager operates only in one dimension, so if you have a set
  36309. of components stacked vertically on top of each other, you'd use one to manage their
  36310. heights. To build up complex arrangements of components, e.g. for applications
  36311. with multiple nested panels, you would use more than one StretchableLayoutManager.
  36312. E.g. by using two (one vertical, one horizontal), you could create a resizable
  36313. spreadsheet-style table.
  36314. E.g.
  36315. @code
  36316. class MyComp : public Component
  36317. {
  36318. StretchableLayoutManager myLayout;
  36319. MyComp()
  36320. {
  36321. myLayout.setItemLayout (0, // for item 0
  36322. 50, 100, // must be between 50 and 100 pixels in size
  36323. -0.6); // and its preferred size is 60% of the total available space
  36324. myLayout.setItemLayout (1, // for item 1
  36325. -0.2, -0.6, // size must be between 20% and 60% of the available space
  36326. 50); // and its preferred size is 50 pixels
  36327. }
  36328. void resized()
  36329. {
  36330. // make a list of two of our child components that we want to reposition
  36331. Component* comps[] = { myComp1, myComp2 };
  36332. // this will position the 2 components, one above the other, to fit
  36333. // vertically into the rectangle provided.
  36334. myLayout.layOutComponents (comps, 2,
  36335. 0, 0, getWidth(), getHeight(),
  36336. true);
  36337. }
  36338. };
  36339. @endcode
  36340. @see StretchableLayoutResizerBar
  36341. */
  36342. class JUCE_API StretchableLayoutManager
  36343. {
  36344. public:
  36345. /** Creates an empty layout.
  36346. You'll need to add some item properties to the layout before it can be used
  36347. to resize things - see setItemLayout().
  36348. */
  36349. StretchableLayoutManager();
  36350. /** Destructor. */
  36351. ~StretchableLayoutManager();
  36352. /** For a numbered item, this sets its size limits and preferred size.
  36353. @param itemIndex the index of the item to change.
  36354. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36355. indicates an absolute size in pixels. A negative number indicates a
  36356. proportion of the available space (e.g -0.5 is 50%)
  36357. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36358. indicates an absolute size in pixels. A negative number indicates a
  36359. proportion of the available space
  36360. @param preferredSize the size that this item would like to be, if there's enough room. A
  36361. positive number indicates an absolute size in pixels. A negative number
  36362. indicates a proportion of the available space
  36363. @see getItemLayout
  36364. */
  36365. void setItemLayout (const int itemIndex,
  36366. const double minimumSize,
  36367. const double maximumSize,
  36368. const double preferredSize);
  36369. /** For a numbered item, this returns its size limits and preferred size.
  36370. @param itemIndex the index of the item.
  36371. @param minimumSize the minimum size that this item is allowed to be - a positive number
  36372. indicates an absolute size in pixels. A negative number indicates a
  36373. proportion of the available space (e.g -0.5 is 50%)
  36374. @param maximumSize the maximum size that this item is allowed to be - a positive number
  36375. indicates an absolute size in pixels. A negative number indicates a
  36376. proportion of the available space
  36377. @param preferredSize the size that this item would like to be, if there's enough room. A
  36378. positive number indicates an absolute size in pixels. A negative number
  36379. indicates a proportion of the available space
  36380. @returns false if the item's properties hadn't been set
  36381. @see setItemLayout
  36382. */
  36383. bool getItemLayout (const int itemIndex,
  36384. double& minimumSize,
  36385. double& maximumSize,
  36386. double& preferredSize) const;
  36387. /** Clears all the properties that have been set with setItemLayout() and resets
  36388. this object to its initial state.
  36389. */
  36390. void clearAllItems();
  36391. /** Takes a set of components that correspond to the layout's items, and positions
  36392. them to fill a space.
  36393. This will try to give each item its preferred size, whether that's a relative size
  36394. or an absolute one.
  36395. @param components an array of components that correspond to each of the
  36396. numbered items that the StretchableLayoutManager object
  36397. has been told about with setItemLayout()
  36398. @param numComponents the number of components in the array that is passed-in. This
  36399. should be the same as the number of items this object has been
  36400. told about.
  36401. @param x the left of the rectangle in which the components should
  36402. be laid out
  36403. @param y the top of the rectangle in which the components should
  36404. be laid out
  36405. @param width the width of the rectangle in which the components should
  36406. be laid out
  36407. @param height the height of the rectangle in which the components should
  36408. be laid out
  36409. @param vertically if true, the components will be positioned in a vertical stack,
  36410. so that they fill the height of the rectangle. If false, they
  36411. will be placed side-by-side in a horizontal line, filling the
  36412. available width
  36413. @param resizeOtherDimension if true, this means that the components will have their
  36414. other dimension resized to fit the space - i.e. if the 'vertically'
  36415. parameter is true, their x-positions and widths are adjusted to fit
  36416. the x and width parameters; if 'vertically' is false, their y-positions
  36417. and heights are adjusted to fit the y and height parameters.
  36418. */
  36419. void layOutComponents (Component** const components,
  36420. int numComponents,
  36421. int x, int y, int width, int height,
  36422. const bool vertically,
  36423. const bool resizeOtherDimension);
  36424. /** Returns the current position of one of the items.
  36425. This is only a valid call after layOutComponents() has been called, as it
  36426. returns the last position that this item was placed at. If the layout was
  36427. vertical, the value returned will be the y position of the top of the item,
  36428. relative to the top of the rectangle in which the items were placed (so for
  36429. example, item 0 will always have position of 0, even in the rectangle passed
  36430. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  36431. the position returned is the item's left-hand position, again relative to the
  36432. x position of the rectangle used.
  36433. @see getItemCurrentSize, setItemPosition
  36434. */
  36435. int getItemCurrentPosition (const int itemIndex) const;
  36436. /** Returns the current size of one of the items.
  36437. This is only meaningful after layOutComponents() has been called, as it
  36438. returns the last size that this item was given. If the layout was done
  36439. vertically, it'll return the item's height in pixels; if it was horizontal,
  36440. it'll return its width.
  36441. @see getItemCurrentRelativeSize
  36442. */
  36443. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  36444. /** Returns the current size of one of the items.
  36445. This is only meaningful after layOutComponents() has been called, as it
  36446. returns the last size that this item was given. If the layout was done
  36447. vertically, it'll return a negative value representing the item's height relative
  36448. to the last size used for laying the components out; if the layout was done
  36449. horizontally it'll be the proportion of its width.
  36450. @see getItemCurrentAbsoluteSize
  36451. */
  36452. double getItemCurrentRelativeSize (const int itemIndex) const;
  36453. /** Moves one of the items, shifting along any other items as necessary in
  36454. order to get it to the desired position.
  36455. Calling this method will also update the preferred sizes of the items it
  36456. shuffles along, so that they reflect their new positions.
  36457. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  36458. about when it's dragged).
  36459. @param itemIndex the item to move
  36460. @param newPosition the absolute position that you'd like this item to move
  36461. to. The item might not be able to always reach exactly this position,
  36462. because other items may have minimum sizes that constrain how
  36463. far it can go
  36464. */
  36465. void setItemPosition (const int itemIndex,
  36466. int newPosition);
  36467. juce_UseDebuggingNewOperator
  36468. private:
  36469. struct ItemLayoutProperties
  36470. {
  36471. int itemIndex;
  36472. int currentSize;
  36473. double minSize, maxSize, preferredSize;
  36474. };
  36475. OwnedArray <ItemLayoutProperties> items;
  36476. int totalSize;
  36477. static int sizeToRealSize (double size, int totalSpace);
  36478. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  36479. void setTotalSize (const int newTotalSize);
  36480. int fitComponentsIntoSpace (const int startIndex,
  36481. const int endIndex,
  36482. const int availableSpace,
  36483. int startPos);
  36484. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  36485. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  36486. void updatePrefSizesToMatchCurrentPositions();
  36487. StretchableLayoutManager (const StretchableLayoutManager&);
  36488. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  36489. };
  36490. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36491. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  36492. #endif
  36493. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36494. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36495. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36496. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36497. /**
  36498. A component that acts as one of the vertical or horizontal bars you see being
  36499. used to resize panels in a window.
  36500. One of these acts with a StretchableLayoutManager to resize the other components.
  36501. @see StretchableLayoutManager
  36502. */
  36503. class JUCE_API StretchableLayoutResizerBar : public Component
  36504. {
  36505. public:
  36506. /** Creates a resizer bar for use on a specified layout.
  36507. @param layoutToUse the layout that will be affected when this bar
  36508. is dragged
  36509. @param itemIndexInLayout the item index in the layout that corresponds to
  36510. this bar component. You'll need to set up the item
  36511. properties in a suitable way for a divider bar, e.g.
  36512. for an 8-pixel wide bar which, you could call
  36513. myLayout->setItemLayout (barIndex, 8, 8, 8)
  36514. @param isBarVertical true if it's an upright bar that you drag left and
  36515. right; false for a horizontal one that you drag up and
  36516. down
  36517. */
  36518. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  36519. const int itemIndexInLayout,
  36520. const bool isBarVertical);
  36521. /** Destructor. */
  36522. ~StretchableLayoutResizerBar();
  36523. /** This is called when the bar is dragged.
  36524. This method must update the positions of any components whose position is
  36525. determined by the StretchableLayoutManager, because they might have just
  36526. moved.
  36527. The default implementation calls the resized() method of this component's
  36528. parent component, because that's often where you're likely to apply the
  36529. layout, but it can be overridden for more specific needs.
  36530. */
  36531. virtual void hasBeenMoved();
  36532. /** @internal */
  36533. void paint (Graphics& g);
  36534. /** @internal */
  36535. void mouseDown (const MouseEvent& e);
  36536. /** @internal */
  36537. void mouseDrag (const MouseEvent& e);
  36538. juce_UseDebuggingNewOperator
  36539. private:
  36540. StretchableLayoutManager* layout;
  36541. int itemIndex, mouseDownPos;
  36542. bool isVertical;
  36543. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  36544. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  36545. };
  36546. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  36547. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  36548. #endif
  36549. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36550. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  36551. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36552. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36553. /**
  36554. A utility class for fitting a set of objects whose sizes can vary between
  36555. a minimum and maximum size, into a space.
  36556. This is a trickier algorithm than it would first seem, so I've put it in this
  36557. class to allow it to be shared by various bits of code.
  36558. To use it, create one of these objects, call addItem() to add the list of items
  36559. you need, then call resizeToFit(), which will change all their sizes. You can
  36560. then retrieve the new sizes with getItemSize() and getNumItems().
  36561. It's currently used by the TableHeaderComponent for stretching out the table
  36562. headings to fill the table's width.
  36563. */
  36564. class StretchableObjectResizer
  36565. {
  36566. public:
  36567. /** Creates an empty object resizer. */
  36568. StretchableObjectResizer();
  36569. /** Destructor. */
  36570. ~StretchableObjectResizer();
  36571. /** Adds an item to the list.
  36572. The order parameter lets you specify groups of items that are resized first when some
  36573. space needs to be found. Those items with an order of 0 will be the first ones to be
  36574. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  36575. will then try resizing the items with an order of 1, then 2, and so on.
  36576. */
  36577. void addItem (const double currentSize,
  36578. const double minSize,
  36579. const double maxSize,
  36580. const int order = 0);
  36581. /** Resizes all the items to fit this amount of space.
  36582. This will attempt to fit them in without exceeding each item's miniumum and
  36583. maximum sizes. In cases where none of the items can be expanded or enlarged any
  36584. further, the final size may be greater or less than the size passed in.
  36585. After calling this method, you can retrieve the new sizes with the getItemSize()
  36586. method.
  36587. */
  36588. void resizeToFit (const double targetSize);
  36589. /** Returns the number of items that have been added. */
  36590. int getNumItems() const throw() { return items.size(); }
  36591. /** Returns the size of one of the items. */
  36592. double getItemSize (const int index) const throw();
  36593. juce_UseDebuggingNewOperator
  36594. private:
  36595. struct Item
  36596. {
  36597. double size;
  36598. double minSize;
  36599. double maxSize;
  36600. int order;
  36601. };
  36602. OwnedArray <Item> items;
  36603. StretchableObjectResizer (const StretchableObjectResizer&);
  36604. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  36605. };
  36606. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  36607. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  36608. #endif
  36609. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36610. #endif
  36611. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36612. #endif
  36613. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  36614. #endif
  36615. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36616. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36617. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36618. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36619. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  36620. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36621. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36622. /********* Start of inlined file: juce_FileFilter.h *********/
  36623. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36624. #define __JUCE_FILEFILTER_JUCEHEADER__
  36625. /**
  36626. Interface for deciding which files are suitable for something.
  36627. For example, this is used by DirectoryContentsList to select which files
  36628. go into the list.
  36629. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36630. */
  36631. class JUCE_API FileFilter
  36632. {
  36633. public:
  36634. /** Creates a filter with the given description.
  36635. The description can be returned later with the getDescription() method.
  36636. */
  36637. FileFilter (const String& filterDescription);
  36638. /** Destructor. */
  36639. virtual ~FileFilter();
  36640. /** Returns the description that the filter was created with. */
  36641. const String& getDescription() const throw();
  36642. /** Should return true if this file is suitable for inclusion in whatever context
  36643. the object is being used.
  36644. */
  36645. virtual bool isFileSuitable (const File& file) const = 0;
  36646. /** Should return true if this directory is suitable for inclusion in whatever context
  36647. the object is being used.
  36648. */
  36649. virtual bool isDirectorySuitable (const File& file) const = 0;
  36650. protected:
  36651. String description;
  36652. };
  36653. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36654. /********* End of inlined file: juce_FileFilter.h *********/
  36655. /**
  36656. A class to asynchronously scan for details about the files in a directory.
  36657. This keeps a list of files and some information about them, using a background
  36658. thread to scan for more files. As files are found, it broadcasts change messages
  36659. to tell any listeners.
  36660. @see FileListComponent, FileBrowserComponent
  36661. */
  36662. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36663. public TimeSliceClient
  36664. {
  36665. public:
  36666. /** Creates a directory list.
  36667. To set the directory it should point to, use setDirectory(), which will
  36668. also start it scanning for files on the background thread.
  36669. When the background thread finds and adds new files to this list, the
  36670. ChangeBroadcaster class will send a change message, so you can register
  36671. listeners and update them when the list changes.
  36672. @param fileFilter an optional filter to select which files are
  36673. included in the list. If this is 0, then all files
  36674. and directories are included. Make sure that the
  36675. filter doesn't get deleted during the lifetime of this
  36676. object
  36677. @param threadToUse a thread object that this list can use
  36678. to scan for files as a background task. Make sure
  36679. that the thread you give it has been started, or you
  36680. won't get any files!
  36681. */
  36682. DirectoryContentsList (const FileFilter* const fileFilter,
  36683. TimeSliceThread& threadToUse);
  36684. /** Destructor. */
  36685. ~DirectoryContentsList();
  36686. /** Sets the directory to look in for files.
  36687. If the directory that's passed in is different to the current one, this will
  36688. also start the background thread scanning it for files.
  36689. */
  36690. void setDirectory (const File& directory,
  36691. const bool includeDirectories,
  36692. const bool includeFiles);
  36693. /** Returns the directory that's currently being used. */
  36694. const File& getDirectory() const throw();
  36695. /** Clears the list, and stops the thread scanning for files. */
  36696. void clear();
  36697. /** Clears the list and restarts scanning the directory for files. */
  36698. void refresh();
  36699. /** True if the background thread hasn't yet finished scanning for files. */
  36700. bool isStillLoading() const;
  36701. /** Tells the list whether or not to ignore hidden files.
  36702. By default these are ignored.
  36703. */
  36704. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  36705. /** Contains cached information about one of the files in a DirectoryContentsList.
  36706. */
  36707. struct FileInfo
  36708. {
  36709. /** The filename.
  36710. This isn't a full pathname, it's just the last part of the path, same as you'd
  36711. get from File::getFileName().
  36712. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36713. */
  36714. String filename;
  36715. /** File size in bytes. */
  36716. int64 fileSize;
  36717. /** File modification time.
  36718. As supplied by File::getLastModificationTime().
  36719. */
  36720. Time modificationTime;
  36721. /** File creation time.
  36722. As supplied by File::getCreationTime().
  36723. */
  36724. Time creationTime;
  36725. /** True if the file is a directory. */
  36726. bool isDirectory;
  36727. /** True if the file is read-only. */
  36728. bool isReadOnly;
  36729. };
  36730. /** Returns the number of files currently available in the list.
  36731. The info about one of these files can be retrieved with getFileInfo() or
  36732. getFile().
  36733. Obviously as the background thread runs and scans the directory for files, this
  36734. number will change.
  36735. @see getFileInfo, getFile
  36736. */
  36737. int getNumFiles() const;
  36738. /** Returns the cached information about one of the files in the list.
  36739. If the index is in-range, this will return true and will copy the file's details
  36740. to the structure that is passed-in.
  36741. If it returns false, then the index wasn't in range, and the structure won't
  36742. be affected.
  36743. @see getNumFiles, getFile
  36744. */
  36745. bool getFileInfo (const int index,
  36746. FileInfo& resultInfo) const;
  36747. /** Returns one of the files in the list.
  36748. @param index should be less than getNumFiles(). If this is out-of-range, the
  36749. return value will be File::nonexistent
  36750. @see getNumFiles, getFileInfo
  36751. */
  36752. const File getFile (const int index) const;
  36753. /** Returns the file filter being used.
  36754. The filter is specified in the constructor.
  36755. */
  36756. const FileFilter* getFilter() const throw() { return fileFilter; }
  36757. /** @internal */
  36758. bool useTimeSlice();
  36759. /** @internal */
  36760. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  36761. /** @internal */
  36762. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  36763. const DirectoryContentsList::FileInfo* const second) throw();
  36764. juce_UseDebuggingNewOperator
  36765. private:
  36766. File root;
  36767. const FileFilter* fileFilter;
  36768. TimeSliceThread& thread;
  36769. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  36770. CriticalSection fileListLock;
  36771. OwnedArray <FileInfo> files;
  36772. void* volatile fileFindHandle;
  36773. bool volatile shouldStop;
  36774. void changed();
  36775. bool checkNextFile (bool& hasChanged);
  36776. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  36777. const int64 fileSize, const Time& modTime,
  36778. const Time& creationTime, const bool isReadOnly);
  36779. DirectoryContentsList (const DirectoryContentsList&);
  36780. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  36781. };
  36782. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36783. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  36784. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  36785. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36786. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36787. /**
  36788. A listener for user selection events in a file browser.
  36789. This is used by a FileBrowserComponent or FileListComponent.
  36790. */
  36791. class JUCE_API FileBrowserListener
  36792. {
  36793. public:
  36794. /** Destructor. */
  36795. virtual ~FileBrowserListener();
  36796. /** Callback when the user selects a different file in the browser. */
  36797. virtual void selectionChanged() = 0;
  36798. /** Callback when the user clicks on a file in the browser. */
  36799. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36800. /** Callback when the user double-clicks on a file in the browser. */
  36801. virtual void fileDoubleClicked (const File& file) = 0;
  36802. };
  36803. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36804. /********* End of inlined file: juce_FileBrowserListener.h *********/
  36805. /**
  36806. A base class for components that display a list of the files in a directory.
  36807. @see DirectoryContentsList
  36808. */
  36809. class JUCE_API DirectoryContentsDisplayComponent
  36810. {
  36811. public:
  36812. /**
  36813. */
  36814. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36815. /** Destructor. */
  36816. virtual ~DirectoryContentsDisplayComponent();
  36817. /** Returns the file that the user has currently selected.
  36818. Returns File::nonexistent if none is selected.
  36819. */
  36820. virtual const File getSelectedFile() const = 0;
  36821. /** Scrolls this view to the top. */
  36822. virtual void scrollToTop() = 0;
  36823. /** Adds a listener to be told when files are selected or clicked.
  36824. @see removeListener
  36825. */
  36826. void addListener (FileBrowserListener* const listener) throw();
  36827. /** Removes a listener.
  36828. @see addListener
  36829. */
  36830. void removeListener (FileBrowserListener* const listener) throw();
  36831. /** A set of colour IDs to use to change the colour of various aspects of the label.
  36832. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36833. methods.
  36834. Note that you can also use the constants from TextEditor::ColourIds to change the
  36835. colour of the text editor that is opened when a label is editable.
  36836. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36837. */
  36838. enum ColourIds
  36839. {
  36840. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36841. textColourId = 0x1000541, /**< The colour for the text. */
  36842. };
  36843. /** @internal */
  36844. void sendSelectionChangeMessage();
  36845. /** @internal */
  36846. void sendDoubleClickMessage (const File& file);
  36847. /** @internal */
  36848. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36849. juce_UseDebuggingNewOperator
  36850. protected:
  36851. DirectoryContentsList& fileList;
  36852. SortedSet <void*> listeners;
  36853. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36854. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36855. };
  36856. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36857. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  36858. #endif
  36859. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36860. #endif
  36861. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36862. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  36863. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36864. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36865. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  36866. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36867. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36868. /**
  36869. Base class for components that live inside a file chooser dialog box and
  36870. show previews of the files that get selected.
  36871. One of these allows special extra information to be displayed for files
  36872. in a dialog box as the user selects them. Each time the current file or
  36873. directory is changed, the selectedFileChanged() method will be called
  36874. to allow it to update itself appropriately.
  36875. @see FileChooser, ImagePreviewComponent
  36876. */
  36877. class JUCE_API FilePreviewComponent : public Component
  36878. {
  36879. public:
  36880. /** Creates a FilePreviewComponent. */
  36881. FilePreviewComponent();
  36882. /** Destructor. */
  36883. ~FilePreviewComponent();
  36884. /** Called to indicate that the user's currently selected file has changed.
  36885. @param newSelectedFile the newly selected file or directory, which may be
  36886. File::nonexistent if none is selected.
  36887. */
  36888. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36889. juce_UseDebuggingNewOperator
  36890. private:
  36891. FilePreviewComponent (const FilePreviewComponent&);
  36892. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  36893. };
  36894. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36895. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  36896. /**
  36897. A component for browsing and selecting a file or directory to open or save.
  36898. This contains a FileListComponent and adds various boxes and controls for
  36899. navigating and selecting a file. It can work in different modes so that it can
  36900. be used for loading or saving a file, or for choosing a directory.
  36901. @see FileChooserDialogBox, FileChooser, FileListComponent
  36902. */
  36903. class JUCE_API FileBrowserComponent : public Component,
  36904. public ChangeBroadcaster,
  36905. private FileBrowserListener,
  36906. private TextEditorListener,
  36907. private ButtonListener,
  36908. private ComboBoxListener
  36909. {
  36910. public:
  36911. /** Various modes that the browser can be used in.
  36912. One of these is passed into the constructor.
  36913. */
  36914. enum FileChooserMode
  36915. {
  36916. loadFileMode, /**< the component should allow the user to choose an existing
  36917. file with the intention of opening it. */
  36918. saveFileMode, /**< the component should allow the user to specify the name of
  36919. a file that will be used to save something. */
  36920. chooseDirectoryMode /**< the component should allow the user to select an existing
  36921. directory. */
  36922. };
  36923. /** Creates a FileBrowserComponent.
  36924. @param browserMode The intended purpose for the browser - see the
  36925. FileChooserMode enum for the various options
  36926. @param initialFileOrDirectory The file or directory that should be selected when
  36927. the component begins. If this is File::nonexistent,
  36928. a default directory will be chosen.
  36929. @param fileFilter an optional filter to use to determine which files
  36930. are shown. If this is 0 then all files are displayed. Note
  36931. that a pointer is kept internally to this object, so
  36932. make sure that it is not deleted before the browser object
  36933. is deleted.
  36934. @param previewComp an optional preview component that will be used to
  36935. show previews of files that the user selects
  36936. @param useTreeView if this is false, the files are shown in a list; if true,
  36937. they are shown in a treeview
  36938. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  36939. text into the filename box.
  36940. */
  36941. FileBrowserComponent (FileChooserMode browserMode,
  36942. const File& initialFileOrDirectory,
  36943. const FileFilter* fileFilter,
  36944. FilePreviewComponent* previewComp,
  36945. const bool useTreeView = false,
  36946. const bool filenameTextBoxIsReadOnly = false);
  36947. /** Destructor. */
  36948. ~FileBrowserComponent();
  36949. /**
  36950. */
  36951. const File getCurrentFile() const throw();
  36952. /** Returns true if the current file is usable.
  36953. This can be used to decide whether the user can press "ok" for the
  36954. current file. What it does depends on the mode, so for example in an "open"
  36955. mode, the current file is only valid if one has been selected and if the file
  36956. exists. In a "save" mode, a non-existent file would also be valid.
  36957. */
  36958. bool currentFileIsValid() const;
  36959. /** Returns the directory whose contents are currently being shown in the listbox. */
  36960. const File getRoot() const;
  36961. /** Changes the directory that's being shown in the listbox. */
  36962. void setRoot (const File& newRootDirectory);
  36963. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36964. void goUp();
  36965. /** Refreshes the directory that's currently being listed. */
  36966. void refresh();
  36967. /** Returns the browser's current mode. */
  36968. FileChooserMode getMode() const throw() { return mode; }
  36969. /** Returns a verb to describe what should happen when the file is accepted.
  36970. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36971. mode, it'll be "Save", etc.
  36972. */
  36973. virtual const String getActionVerb() const;
  36974. /** Adds a listener to be told when the user selects and clicks on files.
  36975. @see removeListener
  36976. */
  36977. void addListener (FileBrowserListener* const listener) throw();
  36978. /** Removes a listener.
  36979. @see addListener
  36980. */
  36981. void removeListener (FileBrowserListener* const listener) throw();
  36982. /** @internal */
  36983. void resized();
  36984. /** @internal */
  36985. void buttonClicked (Button* b);
  36986. /** @internal */
  36987. void comboBoxChanged (ComboBox*);
  36988. /** @internal */
  36989. void textEditorTextChanged (TextEditor& editor);
  36990. /** @internal */
  36991. void textEditorReturnKeyPressed (TextEditor& editor);
  36992. /** @internal */
  36993. void textEditorEscapeKeyPressed (TextEditor& editor);
  36994. /** @internal */
  36995. void textEditorFocusLost (TextEditor& editor);
  36996. /** @internal */
  36997. void selectionChanged();
  36998. /** @internal */
  36999. void fileClicked (const File& f, const MouseEvent& e);
  37000. /** @internal */
  37001. void fileDoubleClicked (const File& f);
  37002. /** @internal */
  37003. FilePreviewComponent* getPreviewComponent() const throw();
  37004. juce_UseDebuggingNewOperator
  37005. protected:
  37006. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  37007. private:
  37008. DirectoryContentsList* fileList;
  37009. FileFilter* directoriesOnlyFilter;
  37010. FileChooserMode mode;
  37011. File currentRoot;
  37012. SortedSet <void*> listeners;
  37013. DirectoryContentsDisplayComponent* fileListComponent;
  37014. FilePreviewComponent* previewComp;
  37015. ComboBox* currentPathBox;
  37016. TextEditor* filenameBox;
  37017. Button* goUpButton;
  37018. TimeSliceThread thread;
  37019. void sendListenerChangeMessage();
  37020. FileBrowserComponent (const FileBrowserComponent&);
  37021. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  37022. };
  37023. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37024. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  37025. #endif
  37026. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37027. #endif
  37028. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37029. /********* Start of inlined file: juce_FileChooser.h *********/
  37030. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37031. #define __JUCE_FILECHOOSER_JUCEHEADER__
  37032. /**
  37033. Creates a dialog box to choose a file or directory to load or save.
  37034. To use a FileChooser:
  37035. - create one (as a local stack variable is the neatest way)
  37036. - call one of its browseFor.. methods
  37037. - if this returns true, the user has selected a file, so you can retrieve it
  37038. with the getResult() method.
  37039. e.g. @code
  37040. void loadMooseFile()
  37041. {
  37042. FileChooser myChooser ("Please select the moose you want to load...",
  37043. File::getSpecialLocation (File::userHomeDirectory),
  37044. "*.moose");
  37045. if (myChooser.browseForFileToOpen())
  37046. {
  37047. File mooseFile (myChooser.getResult());
  37048. loadMoose (mooseFile);
  37049. }
  37050. }
  37051. @endcode
  37052. */
  37053. class JUCE_API FileChooser
  37054. {
  37055. public:
  37056. /** Creates a FileChooser.
  37057. After creating one of these, use one of the browseFor... methods to display it.
  37058. @param dialogBoxTitle a text string to display in the dialog box to
  37059. tell the user what's going on
  37060. @param initialFileOrDirectory the file or directory that should be selected when
  37061. the dialog box opens. If this parameter is set to
  37062. File::nonexistent, a sensible default directory
  37063. will be used instead.
  37064. @param filePatternsAllowed a set of file patterns to specify which files can be
  37065. selected - each pattern should be separated by a
  37066. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  37067. empty string means that all files are allowed
  37068. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  37069. possible; if false, then a Juce-based browser dialog
  37070. box will always be used
  37071. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  37072. */
  37073. FileChooser (const String& dialogBoxTitle,
  37074. const File& initialFileOrDirectory = File::nonexistent,
  37075. const String& filePatternsAllowed = String::empty,
  37076. const bool useOSNativeDialogBox = true);
  37077. /** Destructor. */
  37078. ~FileChooser();
  37079. /** Shows a dialog box to choose a file to open.
  37080. This will display the dialog box modally, using an "open file" mode, so that
  37081. it won't allow non-existent files or directories to be chosen.
  37082. @param previewComponent an optional component to display inside the dialog
  37083. box to show special info about the files that the user
  37084. is browsing. The component will not be deleted by this
  37085. object, so the caller must take care of it.
  37086. @returns true if the user selected a file, in which case, use the getResult()
  37087. method to find out what it was. Returns false if they cancelled instead.
  37088. @see browseForFileToSave, browseForDirectory
  37089. */
  37090. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  37091. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  37092. The files that are returned can be obtained by calling getResults(). See
  37093. browseForFileToOpen() for more info about the behaviour of this method.
  37094. */
  37095. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  37096. /** Shows a dialog box to choose a file to save.
  37097. This will display the dialog box modally, using an "save file" mode, so it
  37098. will allow non-existent files to be chosen, but not directories.
  37099. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  37100. the user if they're sure they want to overwrite a file that already
  37101. exists
  37102. @returns true if the user chose a file and pressed 'ok', in which case, use
  37103. the getResult() method to find out what the file was. Returns false
  37104. if they cancelled instead.
  37105. @see browseForFileToOpen, browseForDirectory
  37106. */
  37107. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  37108. /** Shows a dialog box to choose a directory.
  37109. This will display the dialog box modally, using an "open directory" mode, so it
  37110. will only allow directories to be returned, not files.
  37111. @returns true if the user chose a directory and pressed 'ok', in which case, use
  37112. the getResult() method to find out what they chose. Returns false
  37113. if they cancelled instead.
  37114. @see browseForFileToOpen, browseForFileToSave
  37115. */
  37116. bool browseForDirectory();
  37117. /** Returns the last file that was chosen by one of the browseFor methods.
  37118. After calling the appropriate browseFor... method, this method lets you
  37119. find out what file or directory they chose.
  37120. Note that the file returned is only valid if the browse method returned true (i.e.
  37121. if the user pressed 'ok' rather than cancelling).
  37122. If you're using a multiple-file select, then use the getResults() method instead,
  37123. to obtain the list of all files chosen.
  37124. @see getResults
  37125. */
  37126. const File getResult() const;
  37127. /** Returns a list of all the files that were chosen during the last call to a
  37128. browse method.
  37129. This array may be empty if no files were chosen, or can contain multiple entries
  37130. if multiple files were chosen.
  37131. @see getResult
  37132. */
  37133. const OwnedArray <File>& getResults() const;
  37134. juce_UseDebuggingNewOperator
  37135. private:
  37136. String title, filters;
  37137. File startingFile;
  37138. OwnedArray <File> results;
  37139. bool useNativeDialogBox;
  37140. bool showDialog (const bool isDirectory,
  37141. const bool isSave,
  37142. const bool warnAboutOverwritingExistingFiles,
  37143. const bool selectMultipleFiles,
  37144. FilePreviewComponent* const previewComponent);
  37145. static void showPlatformDialog (OwnedArray<File>& results,
  37146. const String& title,
  37147. const File& file,
  37148. const String& filters,
  37149. bool isDirectory,
  37150. bool isSave,
  37151. bool warnAboutOverwritingExistingFiles,
  37152. bool selectMultipleFiles,
  37153. FilePreviewComponent* previewComponent);
  37154. };
  37155. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  37156. /********* End of inlined file: juce_FileChooser.h *********/
  37157. #endif
  37158. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37159. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  37160. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37161. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37162. /**
  37163. A file open/save dialog box.
  37164. This is a Juce-based file dialog box; to use a native file chooser, see the
  37165. FileChooser class.
  37166. To use one of these, create it and call its show() method. e.g.
  37167. @code
  37168. {
  37169. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  37170. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37171. File::nonexistent,
  37172. &wildcardFilter,
  37173. 0);
  37174. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  37175. T("Please choose some kind of file that you want to open..."),
  37176. browser,
  37177. getLookAndFeel().alertWindowBackground);
  37178. if (dialogBox.show())
  37179. {
  37180. File selectedFile = browser.getCurrentFile();
  37181. ...
  37182. }
  37183. }
  37184. @endcode
  37185. @see FileChooser
  37186. */
  37187. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37188. public ButtonListener,
  37189. public FileBrowserListener
  37190. {
  37191. public:
  37192. /** Creates a file chooser box.
  37193. @param title the main title to show at the top of the box
  37194. @param instructions an optional longer piece of text to show below the title in
  37195. a smaller font, describing in more detail what's required.
  37196. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37197. box. Make sure you delete this after (but not before!) the
  37198. dialog box has been deleted.
  37199. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37200. if they try to select a file that already exists. (This
  37201. flag is only used when saving files)
  37202. @param backgroundColour the background colour for the top level window
  37203. @see FileBrowserComponent, FilePreviewComponent
  37204. */
  37205. FileChooserDialogBox (const String& title,
  37206. const String& instructions,
  37207. FileBrowserComponent& browserComponent,
  37208. const bool warnAboutOverwritingExistingFiles,
  37209. const Colour& backgroundColour);
  37210. /** Destructor. */
  37211. ~FileChooserDialogBox();
  37212. /** Displays and runs the dialog box modally.
  37213. This will show the box with the specified size, returning true if the user
  37214. pressed 'ok', or false if they cancelled.
  37215. Leave the width or height as 0 to use the default size
  37216. */
  37217. bool show (int width = 0,int height = 0);
  37218. /** @internal */
  37219. void buttonClicked (Button* button);
  37220. /** @internal */
  37221. void closeButtonPressed();
  37222. /** @internal */
  37223. void selectionChanged();
  37224. /** @internal */
  37225. void fileClicked (const File& file, const MouseEvent& e);
  37226. /** @internal */
  37227. void fileDoubleClicked (const File& file);
  37228. juce_UseDebuggingNewOperator
  37229. private:
  37230. class ContentComponent : public Component
  37231. {
  37232. public:
  37233. ContentComponent();
  37234. ~ContentComponent();
  37235. void paint (Graphics& g);
  37236. void resized();
  37237. String instructions;
  37238. GlyphArrangement text;
  37239. FileBrowserComponent* chooserComponent;
  37240. FilePreviewComponent* previewComponent;
  37241. TextButton* okButton;
  37242. TextButton* cancelButton;
  37243. };
  37244. ContentComponent* content;
  37245. const bool warnAboutOverwritingExistingFiles;
  37246. FileChooserDialogBox (const FileChooserDialogBox&);
  37247. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37248. };
  37249. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37250. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  37251. #endif
  37252. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37253. #endif
  37254. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37255. /********* Start of inlined file: juce_FileListComponent.h *********/
  37256. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37257. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37258. /**
  37259. A component that displays the files in a directory as a listbox.
  37260. This implements the DirectoryContentsDisplayComponent base class so that
  37261. it can be used in a FileBrowserComponent.
  37262. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37263. class and the FileBrowserListener class.
  37264. @see DirectoryContentsList, FileTreeComponent
  37265. */
  37266. class JUCE_API FileListComponent : public ListBox,
  37267. public DirectoryContentsDisplayComponent,
  37268. private ListBoxModel,
  37269. private ChangeListener
  37270. {
  37271. public:
  37272. /** Creates a listbox to show the contents of a specified directory.
  37273. */
  37274. FileListComponent (DirectoryContentsList& listToShow);
  37275. /** Destructor. */
  37276. ~FileListComponent();
  37277. /** Returns the file that the user has currently selected.
  37278. Returns File::nonexistent if none is selected.
  37279. */
  37280. const File getSelectedFile() const;
  37281. /** Scrolls to the top of the list. */
  37282. void scrollToTop();
  37283. /** @internal */
  37284. void changeListenerCallback (void*);
  37285. /** @internal */
  37286. int getNumRows();
  37287. /** @internal */
  37288. void paintListBoxItem (int, Graphics&, int, int, bool);
  37289. /** @internal */
  37290. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37291. /** @internal */
  37292. void selectedRowsChanged (int lastRowSelected);
  37293. /** @internal */
  37294. void deleteKeyPressed (int currentSelectedRow);
  37295. /** @internal */
  37296. void returnKeyPressed (int currentSelectedRow);
  37297. juce_UseDebuggingNewOperator
  37298. private:
  37299. FileListComponent (const FileListComponent&);
  37300. const FileListComponent& operator= (const FileListComponent&);
  37301. File lastDirectory;
  37302. };
  37303. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37304. /********* End of inlined file: juce_FileListComponent.h *********/
  37305. #endif
  37306. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37307. /********* Start of inlined file: juce_FilenameComponent.h *********/
  37308. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37309. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37310. class FilenameComponent;
  37311. /**
  37312. Listens for events happening to a FilenameComponent.
  37313. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  37314. register one of these objects for event callbacks when the filename is changed.
  37315. @See FilenameComponent
  37316. */
  37317. class JUCE_API FilenameComponentListener
  37318. {
  37319. public:
  37320. /** Destructor. */
  37321. virtual ~FilenameComponentListener() {}
  37322. /** This method is called after the FilenameComponent's file has been changed. */
  37323. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  37324. };
  37325. /**
  37326. Shows a filename as an editable text box, with a 'browse' button and a
  37327. drop-down list for recently selected files.
  37328. A handy component for dialogue boxes where you want the user to be able to
  37329. select a file or directory.
  37330. Attach an FilenameComponentListener using the addListener() method, and it will
  37331. get called each time the user changes the filename, either by browsing for a file
  37332. and clicking 'ok', or by typing a new filename into the box and pressing return.
  37333. @see FileChooser, ComboBox
  37334. */
  37335. class JUCE_API FilenameComponent : public Component,
  37336. public SettableTooltipClient,
  37337. public FileDragAndDropTarget,
  37338. private AsyncUpdater,
  37339. private ButtonListener,
  37340. private ComboBoxListener
  37341. {
  37342. public:
  37343. /** Creates a FilenameComponent.
  37344. @param name the name for this component.
  37345. @param currentFile the file to initially show in the box
  37346. @param canEditFilename if true, the user can manually edit the filename; if false,
  37347. they can only change it by browsing for a new file
  37348. @param isDirectory if true, the file will be treated as a directory, and
  37349. an appropriate directory browser used
  37350. @param isForSaving if true, the file browser will allow non-existent files to
  37351. be picked, as the file is assumed to be used for saving rather
  37352. than loading
  37353. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  37354. If an empty string is passed in, then the pattern is assumed to be "*"
  37355. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  37356. to any filenames that are entered or chosen
  37357. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  37358. will only appear if the initial file isn't valid)
  37359. */
  37360. FilenameComponent (const String& name,
  37361. const File& currentFile,
  37362. const bool canEditFilename,
  37363. const bool isDirectory,
  37364. const bool isForSaving,
  37365. const String& fileBrowserWildcard,
  37366. const String& enforcedSuffix,
  37367. const String& textWhenNothingSelected);
  37368. /** Destructor. */
  37369. ~FilenameComponent();
  37370. /** Returns the currently displayed filename. */
  37371. const File getCurrentFile() const;
  37372. /** Changes the current filename.
  37373. If addToRecentlyUsedList is true, the filename will also be added to the
  37374. drop-down list of recent files.
  37375. If sendChangeNotification is false, then the listeners won't be told of the
  37376. change.
  37377. */
  37378. void setCurrentFile (File newFile,
  37379. const bool addToRecentlyUsedList,
  37380. const bool sendChangeNotification = true);
  37381. /** Changes whether the use can type into the filename box.
  37382. */
  37383. void setFilenameIsEditable (const bool shouldBeEditable);
  37384. /** Sets a file or directory to be the default starting point for the browser to show.
  37385. This is only used if the current file hasn't been set.
  37386. */
  37387. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37388. /** Returns all the entries on the recent files list.
  37389. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  37390. state of this list.
  37391. @see setRecentlyUsedFilenames
  37392. */
  37393. const StringArray getRecentlyUsedFilenames() const;
  37394. /** Sets all the entries on the recent files list.
  37395. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  37396. state of this list.
  37397. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  37398. */
  37399. void setRecentlyUsedFilenames (const StringArray& filenames);
  37400. /** Adds an entry to the recently-used files dropdown list.
  37401. If the file is already in the list, it will be moved to the top. A limit
  37402. is also placed on the number of items that are kept in the list.
  37403. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  37404. */
  37405. void addRecentlyUsedFile (const File& file);
  37406. /** Changes the limit for the number of files that will be stored in the recent-file list.
  37407. */
  37408. void setMaxNumberOfRecentFiles (const int newMaximum);
  37409. /** Changes the text shown on the 'browse' button.
  37410. By default this button just says "..." but you can change it. The button itself
  37411. can be changed using the look-and-feel classes, so it might not actually have any
  37412. text on it.
  37413. */
  37414. void setBrowseButtonText (const String& browseButtonText);
  37415. /** Adds a listener that will be called when the selected file is changed. */
  37416. void addListener (FilenameComponentListener* const listener) throw();
  37417. /** Removes a previously-registered listener. */
  37418. void removeListener (FilenameComponentListener* const listener) throw();
  37419. /** Gives the component a tooltip. */
  37420. void setTooltip (const String& newTooltip);
  37421. /** @internal */
  37422. void paintOverChildren (Graphics& g);
  37423. /** @internal */
  37424. void resized();
  37425. /** @internal */
  37426. void lookAndFeelChanged();
  37427. /** @internal */
  37428. bool isInterestedInFileDrag (const StringArray& files);
  37429. /** @internal */
  37430. void filesDropped (const StringArray& files, int, int);
  37431. /** @internal */
  37432. void fileDragEnter (const StringArray& files, int, int);
  37433. /** @internal */
  37434. void fileDragExit (const StringArray& files);
  37435. juce_UseDebuggingNewOperator
  37436. private:
  37437. ComboBox* filenameBox;
  37438. String lastFilename;
  37439. Button* browseButton;
  37440. int maxRecentFiles;
  37441. bool isDir, isSaving, isFileDragOver;
  37442. String wildcard, enforcedSuffix, browseButtonText;
  37443. SortedSet <void*> listeners;
  37444. File defaultBrowseFile;
  37445. void comboBoxChanged (ComboBox*);
  37446. void buttonClicked (Button* button);
  37447. void handleAsyncUpdate();
  37448. FilenameComponent (const FilenameComponent&);
  37449. const FilenameComponent& operator= (const FilenameComponent&);
  37450. };
  37451. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37452. /********* End of inlined file: juce_FilenameComponent.h *********/
  37453. #endif
  37454. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37455. #endif
  37456. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37457. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  37458. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37459. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37460. /**
  37461. Shows a set of file paths in a list, allowing them to be added, removed or
  37462. re-ordered.
  37463. @see FileSearchPath
  37464. */
  37465. class JUCE_API FileSearchPathListComponent : public Component,
  37466. public SettableTooltipClient,
  37467. public FileDragAndDropTarget,
  37468. private ButtonListener,
  37469. private ListBoxModel
  37470. {
  37471. public:
  37472. /** Creates an empty FileSearchPathListComponent.
  37473. */
  37474. FileSearchPathListComponent();
  37475. /** Destructor. */
  37476. ~FileSearchPathListComponent();
  37477. /** Returns the path as it is currently shown. */
  37478. const FileSearchPath& getPath() const throw() { return path; }
  37479. /** Changes the current path. */
  37480. void setPath (const FileSearchPath& newPath);
  37481. /** Sets a file or directory to be the default starting point for the browser to show.
  37482. This is only used if the current file hasn't been set.
  37483. */
  37484. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  37485. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37486. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37487. methods.
  37488. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37489. */
  37490. enum ColourIds
  37491. {
  37492. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37493. Make this transparent if you don't want the background to be filled. */
  37494. };
  37495. /** @internal */
  37496. int getNumRows();
  37497. /** @internal */
  37498. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37499. /** @internal */
  37500. void deleteKeyPressed (int lastRowSelected);
  37501. /** @internal */
  37502. void returnKeyPressed (int lastRowSelected);
  37503. /** @internal */
  37504. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37505. /** @internal */
  37506. void selectedRowsChanged (int lastRowSelected);
  37507. /** @internal */
  37508. void resized();
  37509. /** @internal */
  37510. void paint (Graphics& g);
  37511. /** @internal */
  37512. bool isInterestedInFileDrag (const StringArray& files);
  37513. /** @internal */
  37514. void filesDropped (const StringArray& files, int, int);
  37515. /** @internal */
  37516. void buttonClicked (Button* button);
  37517. juce_UseDebuggingNewOperator
  37518. private:
  37519. FileSearchPath path;
  37520. File defaultBrowseTarget;
  37521. ListBox* listBox;
  37522. Button* addButton;
  37523. Button* removeButton;
  37524. Button* changeButton;
  37525. Button* upButton;
  37526. Button* downButton;
  37527. void changed() throw();
  37528. void updateButtons() throw();
  37529. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37530. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37531. };
  37532. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37533. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  37534. #endif
  37535. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37536. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  37537. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37538. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37539. /**
  37540. A component that displays the files in a directory as a treeview.
  37541. This implements the DirectoryContentsDisplayComponent base class so that
  37542. it can be used in a FileBrowserComponent.
  37543. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37544. class and the FileBrowserListener class.
  37545. @see DirectoryContentsList, FileListComponent
  37546. */
  37547. class JUCE_API FileTreeComponent : public TreeView,
  37548. public DirectoryContentsDisplayComponent
  37549. {
  37550. public:
  37551. /** Creates a listbox to show the contents of a specified directory.
  37552. */
  37553. FileTreeComponent (DirectoryContentsList& listToShow);
  37554. /** Destructor. */
  37555. ~FileTreeComponent();
  37556. /** Returns the number of selected files in the tree.
  37557. */
  37558. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  37559. /** Returns one of the files that the user has currently selected.
  37560. Returns File::nonexistent if none is selected.
  37561. */
  37562. const File getSelectedFile (int index) const throw();
  37563. /** Returns the first of the files that the user has currently selected.
  37564. Returns File::nonexistent if none is selected.
  37565. */
  37566. const File getSelectedFile() const;
  37567. /** Scrolls the list to the top. */
  37568. void scrollToTop();
  37569. /** Setting a name for this allows tree items to be dragged.
  37570. The string that you pass in here will be returned by the getDragSourceDescription()
  37571. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37572. */
  37573. void setDragAndDropDescription (const String& description) throw();
  37574. /** Returns the last value that was set by setDragAndDropDescription().
  37575. */
  37576. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37577. juce_UseDebuggingNewOperator
  37578. private:
  37579. String dragAndDropDescription;
  37580. FileTreeComponent (const FileTreeComponent&);
  37581. const FileTreeComponent& operator= (const FileTreeComponent&);
  37582. };
  37583. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37584. /********* End of inlined file: juce_FileTreeComponent.h *********/
  37585. #endif
  37586. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37587. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  37588. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37589. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37590. /**
  37591. A simple preview component that shows thumbnails of image files.
  37592. @see FileChooserDialogBox, FilePreviewComponent
  37593. */
  37594. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37595. private Timer
  37596. {
  37597. public:
  37598. /** Creates an ImagePreviewComponent. */
  37599. ImagePreviewComponent();
  37600. /** Destructor. */
  37601. ~ImagePreviewComponent();
  37602. /** @internal */
  37603. void selectedFileChanged (const File& newSelectedFile);
  37604. /** @internal */
  37605. void paint (Graphics& g);
  37606. /** @internal */
  37607. void timerCallback();
  37608. juce_UseDebuggingNewOperator
  37609. private:
  37610. File fileToLoad;
  37611. Image* currentThumbnail;
  37612. String currentDetails;
  37613. void getThumbSize (int& w, int& h) const;
  37614. ImagePreviewComponent (const ImagePreviewComponent&);
  37615. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37616. };
  37617. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37618. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  37619. #endif
  37620. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37621. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  37622. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37623. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37624. /**
  37625. A type of FileFilter that works by wildcard pattern matching.
  37626. This filter only allows files that match one of the specified patterns, but
  37627. allows all directories through.
  37628. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37629. */
  37630. class JUCE_API WildcardFileFilter : public FileFilter
  37631. {
  37632. public:
  37633. /**
  37634. Creates a wildcard filter for one or more patterns.
  37635. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37636. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37637. or .aiff.
  37638. The description is a name to show the user in a list of possible patterns, so
  37639. for the wav/aiff example, your description might be "audio files".
  37640. */
  37641. WildcardFileFilter (const String& wildcardPatterns,
  37642. const String& description);
  37643. /** Destructor. */
  37644. ~WildcardFileFilter();
  37645. /** Returns true if the filename matches one of the patterns specified. */
  37646. bool isFileSuitable (const File& file) const;
  37647. /** This always returns true. */
  37648. bool isDirectorySuitable (const File& file) const;
  37649. juce_UseDebuggingNewOperator
  37650. private:
  37651. StringArray wildcards;
  37652. };
  37653. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37654. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  37655. #endif
  37656. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37657. /********* Start of inlined file: juce_AlertWindow.h *********/
  37658. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37659. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37660. /** A window that displays a message and has buttons for the user to react to it.
  37661. For simple dialog boxes with just a couple of buttons on them, there are
  37662. some static methods for running these.
  37663. For more complex dialogs, an AlertWindow can be created, then it can have some
  37664. buttons and components added to it, and its runModalLoop() method is then used to
  37665. show it. The value returned by runModalLoop() shows which button the
  37666. user pressed to dismiss the box.
  37667. @see ThreadWithProgressWindow
  37668. */
  37669. class JUCE_API AlertWindow : public TopLevelWindow,
  37670. private ButtonListener
  37671. {
  37672. public:
  37673. /** The type of icon to show in the dialog box. */
  37674. enum AlertIconType
  37675. {
  37676. NoIcon, /**< No icon will be shown on the dialog box. */
  37677. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37678. user to answer a question. */
  37679. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37680. warning about something and shouldn't be ignored. */
  37681. InfoIcon /**< An icon that indicates that the dialog box is just
  37682. giving the user some information, which doesn't require
  37683. a response from them. */
  37684. };
  37685. /** Creates an AlertWindow.
  37686. @param title the headline to show at the top of the dialog box
  37687. @param message a longer, more descriptive message to show underneath the
  37688. headline
  37689. @param iconType the type of icon to display
  37690. */
  37691. AlertWindow (const String& title,
  37692. const String& message,
  37693. AlertIconType iconType);
  37694. /** Destroys the AlertWindow */
  37695. ~AlertWindow();
  37696. /** Returns the type of alert icon that was specified when the window
  37697. was created. */
  37698. AlertIconType getAlertType() const throw() { return alertIconType; }
  37699. /** Changes the dialog box's message.
  37700. This will also resize the window to fit the new message if required.
  37701. */
  37702. void setMessage (const String& message);
  37703. /** Adds a button to the window.
  37704. @param name the text to show on the button
  37705. @param returnValue the value that should be returned from runModalLoop()
  37706. if this is the button that the user presses.
  37707. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37708. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37709. */
  37710. void addButton (const String& name,
  37711. const int returnValue,
  37712. const KeyPress& shortcutKey1 = KeyPress(),
  37713. const KeyPress& shortcutKey2 = KeyPress());
  37714. /** Returns the number of buttons that the window currently has. */
  37715. int getNumButtons() const;
  37716. /** Adds a textbox to the window for entering strings.
  37717. @param name an internal name for the text-box. This is the name to pass to
  37718. the getTextEditorContents() method to find out what the
  37719. user typed-in.
  37720. @param initialContents a string to show in the text box when it's first shown
  37721. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37722. text-box to label it.
  37723. @param isPasswordBox if true, the text editor will display asterisks instead of
  37724. the actual text
  37725. @see getTextEditorContents
  37726. */
  37727. void addTextEditor (const String& name,
  37728. const String& initialContents,
  37729. const String& onScreenLabel = String::empty,
  37730. const bool isPasswordBox = false);
  37731. /** Returns the contents of a named textbox.
  37732. After showing an AlertWindow that contains a text editor, this can be
  37733. used to find out what the user has typed into it.
  37734. @param nameOfTextEditor the name of the text box that you're interested in
  37735. @see addTextEditor
  37736. */
  37737. const String getTextEditorContents (const String& nameOfTextEditor) const;
  37738. /** Adds a drop-down list of choices to the box.
  37739. After the box has been shown, the getComboBoxComponent() method can
  37740. be used to find out which item the user picked.
  37741. @param name the label to use for the drop-down list
  37742. @param items the list of items to show in it
  37743. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37744. combo-box to label it.
  37745. @see getComboBoxComponent
  37746. */
  37747. void addComboBox (const String& name,
  37748. const StringArray& items,
  37749. const String& onScreenLabel = String::empty);
  37750. /** Returns a drop-down list that was added to the AlertWindow.
  37751. @param nameOfList the name that was passed into the addComboBox() method
  37752. when creating the drop-down
  37753. @returns the ComboBox component, or 0 if none was found for the given name.
  37754. */
  37755. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  37756. /** Adds a block of text.
  37757. This is handy for adding a multi-line note next to a textbox or combo-box,
  37758. to provide more details about what's going on.
  37759. */
  37760. void addTextBlock (const String& text);
  37761. /** Adds a progress-bar to the window.
  37762. @param progressValue a variable that will be repeatedly checked while the
  37763. dialog box is visible, to see how far the process has
  37764. got. The value should be in the range 0 to 1.0
  37765. */
  37766. void addProgressBarComponent (double& progressValue);
  37767. /** Adds a user-defined component to the dialog box.
  37768. @param component the component to add - its size should be set up correctly
  37769. before it is passed in. The caller is responsible for deleting
  37770. the component later on - the AlertWindow won't delete it.
  37771. */
  37772. void addCustomComponent (Component* const component);
  37773. /** Returns the number of custom components in the dialog box.
  37774. @see getCustomComponent, addCustomComponent
  37775. */
  37776. int getNumCustomComponents() const;
  37777. /** Returns one of the custom components in the dialog box.
  37778. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37779. will return 0
  37780. @see getNumCustomComponents, addCustomComponent
  37781. */
  37782. Component* getCustomComponent (const int index) const;
  37783. /** Removes one of the custom components in the dialog box.
  37784. Note that this won't delete it, it just removes the component from the window
  37785. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37786. will return 0
  37787. @returns the component that was removed (or zero)
  37788. @see getNumCustomComponents, addCustomComponent
  37789. */
  37790. Component* removeCustomComponent (const int index);
  37791. /** Returns true if the window contains any components other than just buttons.*/
  37792. bool containsAnyExtraComponents() const;
  37793. // easy-to-use message box functions:
  37794. /** Shows a dialog box that just has a message and a single button to get rid of it.
  37795. The box is shown modally, and the method returns after the user
  37796. has clicked the button (or pressed the escape or return keys).
  37797. @param iconType the type of icon to show
  37798. @param title the headline to show at the top of the box
  37799. @param message a longer, more descriptive message to show underneath the
  37800. headline
  37801. @param buttonText the text to show in the button - if this string is empty, the
  37802. default string "ok" (or a localised version) will be used.
  37803. */
  37804. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  37805. const String& title,
  37806. const String& message,
  37807. const String& buttonText = String::empty);
  37808. /** Shows a dialog box with two buttons.
  37809. Ideal for ok/cancel or yes/no choices. The return key can also be used
  37810. to trigger the first button, and the escape key for the second button.
  37811. @param iconType the type of icon to show
  37812. @param title the headline to show at the top of the box
  37813. @param message a longer, more descriptive message to show underneath the
  37814. headline
  37815. @param button1Text the text to show in the first button - if this string is
  37816. empty, the default string "ok" (or a localised version of it)
  37817. will be used.
  37818. @param button2Text the text to show in the second button - if this string is
  37819. empty, the default string "cancel" (or a localised version of it)
  37820. will be used.
  37821. @returns true if button 1 was clicked, false if it was button 2
  37822. */
  37823. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  37824. const String& title,
  37825. const String& message,
  37826. const String& button1Text = String::empty,
  37827. const String& button2Text = String::empty);
  37828. /** Shows a dialog box with three buttons.
  37829. Ideal for yes/no/cancel boxes.
  37830. The escape key can be used to trigger the third button.
  37831. @param iconType the type of icon to show
  37832. @param title the headline to show at the top of the box
  37833. @param message a longer, more descriptive message to show underneath the
  37834. headline
  37835. @param button1Text the text to show in the first button - if an empty string, then
  37836. "yes" will be used (or a localised version of it)
  37837. @param button2Text the text to show in the first button - if an empty string, then
  37838. "no" will be used (or a localised version of it)
  37839. @param button3Text the text to show in the first button - if an empty string, then
  37840. "cancel" will be used (or a localised version of it)
  37841. @returns one of the following values:
  37842. - 0 if the third button was pressed (normally used for 'cancel')
  37843. - 1 if the first button was pressed (normally used for 'yes')
  37844. - 2 if the middle button was pressed (normally used for 'no')
  37845. */
  37846. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  37847. const String& title,
  37848. const String& message,
  37849. const String& button1Text = String::empty,
  37850. const String& button2Text = String::empty,
  37851. const String& button3Text = String::empty);
  37852. /** Shows an operating-system native dialog box.
  37853. @param title the title to use at the top
  37854. @param bodyText the longer message to show
  37855. @param isOkCancel if true, this will show an ok/cancel box, if false,
  37856. it'll show a box with just an ok button
  37857. @returns true if the ok button was pressed, false if they pressed cancel.
  37858. */
  37859. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  37860. const String& bodyText,
  37861. bool isOkCancel);
  37862. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  37863. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37864. methods.
  37865. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37866. */
  37867. enum ColourIds
  37868. {
  37869. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  37870. textColourId = 0x1001810, /**< The colour for the text. */
  37871. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  37872. };
  37873. juce_UseDebuggingNewOperator
  37874. protected:
  37875. /** @internal */
  37876. void paint (Graphics& g);
  37877. /** @internal */
  37878. void mouseDown (const MouseEvent& e);
  37879. /** @internal */
  37880. void mouseDrag (const MouseEvent& e);
  37881. /** @internal */
  37882. bool keyPressed (const KeyPress& key);
  37883. /** @internal */
  37884. void buttonClicked (Button* button);
  37885. /** @internal */
  37886. void lookAndFeelChanged();
  37887. /** @internal */
  37888. void userTriedToCloseWindow();
  37889. private:
  37890. String text;
  37891. TextLayout textLayout;
  37892. AlertIconType alertIconType;
  37893. ComponentBoundsConstrainer constrainer;
  37894. ComponentDragger dragger;
  37895. Rectangle textArea;
  37896. VoidArray buttons, textBoxes, comboBoxes;
  37897. VoidArray progressBars, customComps, textBlocks, allComps;
  37898. StringArray textboxNames, comboBoxNames;
  37899. Font font;
  37900. void updateLayout (const bool onlyIncreaseSize);
  37901. // disable copy constructor
  37902. AlertWindow (const AlertWindow&);
  37903. const AlertWindow& operator= (const AlertWindow&);
  37904. };
  37905. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  37906. /********* End of inlined file: juce_AlertWindow.h *********/
  37907. #endif
  37908. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  37909. #endif
  37910. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37911. /********* Start of inlined file: juce_DialogWindow.h *********/
  37912. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  37913. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  37914. /**
  37915. A dialog-box style window.
  37916. This class is a convenient way of creating a DocumentWindow with a close button
  37917. that can be triggered by pressing the escape key.
  37918. Any of the methods available to a DocumentWindow or ResizableWindow are also
  37919. available to this, so it can be made resizable, have a menu bar, etc.
  37920. To add items to the box, see the ResizableWindow::setContentComponent() method.
  37921. Don't add components directly to this class - always put them in a content component!
  37922. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  37923. the user clicking the close button - for more info, see the DocumentWindow
  37924. help.
  37925. @see DocumentWindow, ResizableWindow
  37926. */
  37927. class JUCE_API DialogWindow : public DocumentWindow
  37928. {
  37929. public:
  37930. /** Creates a DialogWindow.
  37931. @param name the name to give the component - this is also
  37932. the title shown at the top of the window. To change
  37933. this later, use setName()
  37934. @param backgroundColour the colour to use for filling the window's background.
  37935. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37936. close button to be triggered
  37937. @param addToDesktop if true, the window will be automatically added to the
  37938. desktop; if false, you can use it as a child component
  37939. */
  37940. DialogWindow (const String& name,
  37941. const Colour& backgroundColour,
  37942. const bool escapeKeyTriggersCloseButton,
  37943. const bool addToDesktop = true);
  37944. /** Destructor.
  37945. If a content component has been set with setContentComponent(), it
  37946. will be deleted.
  37947. */
  37948. ~DialogWindow();
  37949. /** Easy way of quickly showing a dialog box containing a given component.
  37950. This will open and display a DialogWindow containing a given component, returning
  37951. when the user clicks its close button.
  37952. It returns the value that was returned by the dialog box's runModalLoop() call.
  37953. To close the dialog programatically, you should call exitModalState (returnValue) on
  37954. the DialogWindow that is created. To find a pointer to this window from your
  37955. contentComponent, you can do something like this:
  37956. @code
  37957. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  37958. if (dw != 0)
  37959. dw->exitModalState (1234);
  37960. @endcode
  37961. @param dialogTitle the dialog box's title
  37962. @param contentComponent the content component for the dialog box. Make sure
  37963. that this has been set to the size you want it to
  37964. be before calling this method. The component won't
  37965. be deleted by this call, so you can re-use it or delete
  37966. it afterwards
  37967. @param componentToCentreAround if this is non-zero, it indicates a component that
  37968. you'd like to show this dialog box in front of. See the
  37969. DocumentWindow::centreAroundComponent() method for more
  37970. info on this parameter
  37971. @param backgroundColour a colour to use for the dialog box's background colour
  37972. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  37973. close button to be triggered
  37974. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  37975. a corner resizer
  37976. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  37977. to use a border or corner resizer component. See ResizableWindow::setResizable()
  37978. */
  37979. static int showModalDialog (const String& dialogTitle,
  37980. Component* contentComponent,
  37981. Component* componentToCentreAround,
  37982. const Colour& backgroundColour,
  37983. const bool escapeKeyTriggersCloseButton,
  37984. const bool shouldBeResizable = false,
  37985. const bool useBottomRightCornerResizer = false);
  37986. juce_UseDebuggingNewOperator
  37987. protected:
  37988. /** @internal */
  37989. void resized();
  37990. private:
  37991. bool escapeKeyTriggersCloseButton;
  37992. DialogWindow (const DialogWindow&);
  37993. const DialogWindow& operator= (const DialogWindow&);
  37994. };
  37995. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  37996. /********* End of inlined file: juce_DialogWindow.h *********/
  37997. #endif
  37998. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37999. #endif
  38000. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  38001. #endif
  38002. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38003. /********* Start of inlined file: juce_SplashScreen.h *********/
  38004. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38005. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  38006. /** A component for showing a splash screen while your app starts up.
  38007. This will automatically position itself, and delete itself when the app has
  38008. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  38009. this).
  38010. To use it, just create one of these in your JUCEApplication::initialise() method,
  38011. call its show() method and let the object delete itself later.
  38012. E.g. @code
  38013. void MyApp::initialise (const String& commandLine)
  38014. {
  38015. SplashScreen* splash = new SplashScreen();
  38016. splash->show (T("welcome to my app"),
  38017. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  38018. 4000, false);
  38019. .. no need to delete the splash screen - it'll do that itself.
  38020. }
  38021. @endcode
  38022. */
  38023. class JUCE_API SplashScreen : public Component,
  38024. public Timer,
  38025. private DeletedAtShutdown
  38026. {
  38027. public:
  38028. /** Creates a SplashScreen object.
  38029. After creating one of these (or your subclass of it), call one of the show()
  38030. methods to display it.
  38031. */
  38032. SplashScreen();
  38033. /** Destructor. */
  38034. ~SplashScreen();
  38035. /** Creates a SplashScreen object that will display an image.
  38036. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38037. screen. This method will also dispatch any pending messages to make sure that when
  38038. it returns, the splash screen has been completely drawn, and your initialisation
  38039. code can carry on.
  38040. @param title the name to give the component
  38041. @param backgroundImage an image to draw on the component. The component's size
  38042. will be set to the size of this image, and if the image is
  38043. semi-transparent, the component will be made semi-transparent
  38044. too. This image will be deleted (or released from the ImageCache
  38045. if that's how it was created) by the splash screen object when
  38046. it is itself deleted.
  38047. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38048. should stay visible for. If the initialisation takes longer than
  38049. this time, the splash screen will wait for it to finish before
  38050. disappearing, but if initialisation is very quick, this lets
  38051. you make sure that people get a good look at your splash.
  38052. @param useDropShadow if true, the window will have a drop shadow
  38053. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38054. the mouse (anywhere)
  38055. */
  38056. void show (const String& title,
  38057. Image* const backgroundImage,
  38058. const int minimumTimeToDisplayFor,
  38059. const bool useDropShadow,
  38060. const bool removeOnMouseClick = true);
  38061. /** Creates a SplashScreen object with a specified size.
  38062. For a custom splash screen, you can use this method to display it at a certain size
  38063. and then override the paint() method yourself to do whatever's necessary.
  38064. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38065. screen. This method will also dispatch any pending messages to make sure that when
  38066. it returns, the splash screen has been completely drawn, and your initialisation
  38067. code can carry on.
  38068. @param title the name to give the component
  38069. @param width the width to use
  38070. @param height the height to use
  38071. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38072. should stay visible for. If the initialisation takes longer than
  38073. this time, the splash screen will wait for it to finish before
  38074. disappearing, but if initialisation is very quick, this lets
  38075. you make sure that people get a good look at your splash.
  38076. @param useDropShadow if true, the window will have a drop shadow
  38077. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38078. the mouse (anywhere)
  38079. */
  38080. void show (const String& title,
  38081. const int width,
  38082. const int height,
  38083. const int minimumTimeToDisplayFor,
  38084. const bool useDropShadow,
  38085. const bool removeOnMouseClick = true);
  38086. /** @internal */
  38087. void paint (Graphics& g);
  38088. /** @internal */
  38089. void timerCallback();
  38090. juce_UseDebuggingNewOperator
  38091. private:
  38092. Image* backgroundImage;
  38093. Time earliestTimeToDelete;
  38094. int originalClickCounter;
  38095. bool isImageInCache;
  38096. SplashScreen (const SplashScreen&);
  38097. const SplashScreen& operator= (const SplashScreen&);
  38098. };
  38099. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  38100. /********* End of inlined file: juce_SplashScreen.h *********/
  38101. #endif
  38102. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38103. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  38104. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38105. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38106. /**
  38107. A thread that automatically pops up a modal dialog box with a progress bar
  38108. and cancel button while it's busy running.
  38109. These are handy for performing some sort of task while giving the user feedback
  38110. about how long there is to go, etc.
  38111. E.g. @code
  38112. class MyTask : public ThreadWithProgressWindow
  38113. {
  38114. public:
  38115. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  38116. {
  38117. }
  38118. ~MyTask()
  38119. {
  38120. }
  38121. void run()
  38122. {
  38123. for (int i = 0; i < thingsToDo; ++i)
  38124. {
  38125. // must check this as often as possible, because this is
  38126. // how we know if the user's pressed 'cancel'
  38127. if (threadShouldExit())
  38128. break;
  38129. // this will update the progress bar on the dialog box
  38130. setProgress (i / (double) thingsToDo);
  38131. // ... do the business here...
  38132. }
  38133. }
  38134. };
  38135. void doTheTask()
  38136. {
  38137. MyTask m;
  38138. if (m.runThread())
  38139. {
  38140. // thread finished normally..
  38141. }
  38142. else
  38143. {
  38144. // user pressed the cancel button..
  38145. }
  38146. }
  38147. @endcode
  38148. @see Thread, AlertWindow
  38149. */
  38150. class JUCE_API ThreadWithProgressWindow : public Thread,
  38151. private Timer
  38152. {
  38153. public:
  38154. /** Creates the thread.
  38155. Initially, the dialog box won't be visible, it'll only appear when the
  38156. runThread() method is called.
  38157. @param windowTitle the title to go at the top of the dialog box
  38158. @param hasProgressBar whether the dialog box should have a progress bar (see
  38159. setProgress() )
  38160. @param hasCancelButton whether the dialog box should have a cancel button
  38161. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  38162. the thread to stop before killing it forcibly (see
  38163. Thread::stopThread() )
  38164. @param cancelButtonText the text that should be shown in the cancel button
  38165. (if it has one)
  38166. */
  38167. ThreadWithProgressWindow (const String& windowTitle,
  38168. const bool hasProgressBar,
  38169. const bool hasCancelButton,
  38170. const int timeOutMsWhenCancelling = 10000,
  38171. const String& cancelButtonText = JUCE_T("Cancel"));
  38172. /** Destructor. */
  38173. ~ThreadWithProgressWindow();
  38174. /** Starts the thread and waits for it to finish.
  38175. This will start the thread, make the dialog box appear, and wait until either
  38176. the thread finishes normally, or until the cancel button is pressed.
  38177. Before returning, the dialog box will be hidden.
  38178. @param threadPriority the priority to use when starting the thread - see
  38179. Thread::startThread() for values
  38180. @returns true if the thread finished normally; false if the user pressed cancel
  38181. */
  38182. bool runThread (const int threadPriority = 5);
  38183. /** The thread should call this periodically to update the position of the progress bar.
  38184. @param newProgress the progress, from 0.0 to 1.0
  38185. @see setStatusMessage
  38186. */
  38187. void setProgress (const double newProgress);
  38188. /** The thread can call this to change the message that's displayed in the dialog box.
  38189. */
  38190. void setStatusMessage (const String& newStatusMessage);
  38191. juce_UseDebuggingNewOperator
  38192. private:
  38193. void timerCallback();
  38194. double progress;
  38195. AlertWindow alertWindow;
  38196. String message;
  38197. CriticalSection messageLock;
  38198. const int timeOutMsWhenCancelling;
  38199. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  38200. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  38201. };
  38202. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38203. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  38204. #endif
  38205. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  38206. #endif
  38207. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  38208. #endif
  38209. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38210. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  38211. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38212. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38213. #if JUCE_WIN32 || DOXYGEN
  38214. /**
  38215. A Windows-specific class that can create and embed an ActiveX control inside
  38216. itself.
  38217. To use it, create one of these, put it in place and make sure it's visible in a
  38218. window, then use createControl() to instantiate an ActiveX control. The control
  38219. will then be moved and resized to follow the movements of this component.
  38220. Of course, since the control is a heavyweight window, it'll obliterate any
  38221. juce components that may overlap this component, but that's life.
  38222. */
  38223. class JUCE_API ActiveXControlComponent : public Component
  38224. {
  38225. public:
  38226. /** Create an initially-empty container. */
  38227. ActiveXControlComponent();
  38228. /** Destructor. */
  38229. ~ActiveXControlComponent();
  38230. /** Tries to create an ActiveX control and embed it in this peer.
  38231. The peer controlIID is a pointer to an IID structure - it's treated
  38232. as a void* because when including the Juce headers, you might not always
  38233. have included windows.h first, in which case IID wouldn't be defined.
  38234. e.g. @code
  38235. const IID myIID = __uuidof (QTControl);
  38236. myControlComp->createControl (&myIID);
  38237. @endcode
  38238. */
  38239. bool createControl (const void* controlIID);
  38240. /** Deletes the ActiveX control, if one has been created.
  38241. */
  38242. void deleteControl();
  38243. /** Returns true if a control is currently in use. */
  38244. bool isControlOpen() const throw() { return control != 0; }
  38245. /** Does a QueryInterface call on the embedded control object.
  38246. This allows you to cast the control to whatever type of COM object you need.
  38247. The iid parameter is a pointer to an IID structure - it's treated
  38248. as a void* because when including the Juce headers, you might not always
  38249. have included windows.h first, in which case IID wouldn't be defined, but
  38250. you should just pass a pointer to an IID.
  38251. e.g. @code
  38252. const IID iid = __uuidof (IOleWindow);
  38253. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  38254. if (oleWindow != 0)
  38255. {
  38256. HWND hwnd;
  38257. oleWindow->GetWindow (&hwnd);
  38258. ...
  38259. oleWindow->Release();
  38260. }
  38261. @endcode
  38262. */
  38263. void* queryInterface (const void* iid) const;
  38264. /** Set this to false to stop mouse events being allowed through to the control.
  38265. */
  38266. void setMouseEventsAllowed (const bool eventsCanReachControl);
  38267. /** Returns true if mouse events are allowed to get through to the control.
  38268. */
  38269. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  38270. /** @internal */
  38271. void paint (Graphics& g);
  38272. /** @internal */
  38273. void* originalWndProc;
  38274. juce_UseDebuggingNewOperator
  38275. private:
  38276. friend class ActiveXControlData;
  38277. void* control;
  38278. bool mouseEventsAllowed;
  38279. ActiveXControlComponent (const ActiveXControlComponent&);
  38280. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  38281. void setControlBounds (const Rectangle& bounds) const;
  38282. void setControlVisible (const bool b) const;
  38283. };
  38284. #endif
  38285. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38286. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  38287. #endif
  38288. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38289. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  38290. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38291. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38292. class MidiInputSelectorComponentListBox;
  38293. /**
  38294. A component containing controls to let the user change the audio settings of
  38295. an AudioDeviceManager object.
  38296. Very easy to use - just create one of these and show it to the user.
  38297. @see AudioDeviceManager
  38298. */
  38299. class JUCE_API AudioDeviceSelectorComponent : public Component,
  38300. public ComboBoxListener,
  38301. public ButtonListener,
  38302. public ChangeListener
  38303. {
  38304. public:
  38305. /** Creates the component.
  38306. If your app needs only output channels, you might ask for a maximum of 0 input
  38307. channels, and the component won't display any options for choosing the input
  38308. channels. And likewise if you're doing an input-only app.
  38309. @param deviceManager the device manager that this component should control
  38310. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  38311. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  38312. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  38313. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  38314. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  38315. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  38316. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  38317. treated as a set of separate mono channels.
  38318. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  38319. are shown, with an "advanced" button that shows the rest of them
  38320. */
  38321. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  38322. const int minAudioInputChannels,
  38323. const int maxAudioInputChannels,
  38324. const int minAudioOutputChannels,
  38325. const int maxAudioOutputChannels,
  38326. const bool showMidiInputOptions,
  38327. const bool showMidiOutputSelector,
  38328. const bool showChannelsAsStereoPairs,
  38329. const bool hideAdvancedOptionsWithButton);
  38330. /** Destructor */
  38331. ~AudioDeviceSelectorComponent();
  38332. /** @internal */
  38333. void resized();
  38334. /** @internal */
  38335. void comboBoxChanged (ComboBox*);
  38336. /** @internal */
  38337. void buttonClicked (Button*);
  38338. /** @internal */
  38339. void changeListenerCallback (void*);
  38340. juce_UseDebuggingNewOperator
  38341. private:
  38342. AudioDeviceManager& deviceManager;
  38343. ComboBox* deviceTypeDropDown;
  38344. Label* deviceTypeDropDownLabel;
  38345. Component* audioDeviceSettingsComp;
  38346. String audioDeviceSettingsCompType;
  38347. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  38348. const bool showChannelsAsStereoPairs;
  38349. const bool hideAdvancedOptionsWithButton;
  38350. MidiInputSelectorComponentListBox* midiInputsList;
  38351. Label* midiInputsLabel;
  38352. ComboBox* midiOutputSelector;
  38353. Label* midiOutputLabel;
  38354. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  38355. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  38356. };
  38357. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  38358. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  38359. #endif
  38360. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38361. /********* Start of inlined file: juce_BubbleComponent.h *********/
  38362. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38363. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38364. /**
  38365. A component for showing a message or other graphics inside a speech-bubble-shaped
  38366. outline, pointing at a location on the screen.
  38367. This is a base class that just draws and positions the bubble shape, but leaves
  38368. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  38369. that draws a text message.
  38370. To use it, create your subclass, then either add it to a parent component or
  38371. put it on the desktop with addToDesktop (0), use setPosition() to
  38372. resize and position it, then make it visible.
  38373. @see BubbleMessageComponent
  38374. */
  38375. class JUCE_API BubbleComponent : public Component
  38376. {
  38377. protected:
  38378. /** Creates a BubbleComponent.
  38379. Your subclass will need to implement the getContentSize() and paintContent()
  38380. methods to draw the bubble's contents.
  38381. */
  38382. BubbleComponent();
  38383. public:
  38384. /** Destructor. */
  38385. ~BubbleComponent();
  38386. /** A list of permitted placements for the bubble, relative to the co-ordinates
  38387. at which it should be pointing.
  38388. @see setAllowedPlacement
  38389. */
  38390. enum BubblePlacement
  38391. {
  38392. above = 1,
  38393. below = 2,
  38394. left = 4,
  38395. right = 8
  38396. };
  38397. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  38398. point at which it's pointing.
  38399. By default when setPosition() is called, the bubble will place itself either
  38400. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  38401. the values in BubblePlacement to restrict this choice.
  38402. E.g. if you only want your bubble to appear above or below the target area,
  38403. use setAllowedPlacement (above | below);
  38404. @see BubblePlacement
  38405. */
  38406. void setAllowedPlacement (const int newPlacement);
  38407. /** Moves and resizes the bubble to point at a given component.
  38408. This will resize the bubble to fit its content, then find a position for it
  38409. so that it's next to, but doesn't overlap the given component.
  38410. It'll put itself either above, below, or to the side of the component depending
  38411. on where there's the most space, honouring any restrictions that were set
  38412. with setAllowedPlacement().
  38413. */
  38414. void setPosition (Component* componentToPointTo);
  38415. /** Moves and resizes the bubble to point at a given point.
  38416. This will resize the bubble to fit its content, then position it
  38417. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  38418. are relative to either the bubble component's parent component if it has one, or
  38419. they are screen co-ordinates if not.
  38420. It'll put itself either above, below, or to the side of this point, depending
  38421. on where there's the most space, honouring any restrictions that were set
  38422. with setAllowedPlacement().
  38423. */
  38424. void setPosition (const int arrowTipX,
  38425. const int arrowTipY);
  38426. /** Moves and resizes the bubble to point at a given rectangle.
  38427. This will resize the bubble to fit its content, then find a position for it
  38428. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  38429. co-ordinates are relative to either the bubble component's parent component
  38430. if it has one, or they are screen co-ordinates if not.
  38431. It'll put itself either above, below, or to the side of the component depending
  38432. on where there's the most space, honouring any restrictions that were set
  38433. with setAllowedPlacement().
  38434. */
  38435. void setPosition (const Rectangle& rectangleToPointTo);
  38436. protected:
  38437. /** Subclasses should override this to return the size of the content they
  38438. want to draw inside the bubble.
  38439. */
  38440. virtual void getContentSize (int& width, int& height) = 0;
  38441. /** Subclasses should override this to draw their bubble's contents.
  38442. The graphics object's clip region and the dimensions passed in here are
  38443. set up to paint just the rectangle inside the bubble.
  38444. */
  38445. virtual void paintContent (Graphics& g, int width, int height) = 0;
  38446. public:
  38447. /** @internal */
  38448. void paint (Graphics& g);
  38449. juce_UseDebuggingNewOperator
  38450. private:
  38451. Rectangle content;
  38452. int side, allowablePlacements;
  38453. float arrowTipX, arrowTipY;
  38454. DropShadowEffect shadow;
  38455. BubbleComponent (const BubbleComponent&);
  38456. const BubbleComponent& operator= (const BubbleComponent&);
  38457. };
  38458. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  38459. /********* End of inlined file: juce_BubbleComponent.h *********/
  38460. #endif
  38461. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38462. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  38463. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38464. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38465. /**
  38466. A speech-bubble component that displays a short message.
  38467. This can be used to show a message with the tail of the speech bubble
  38468. pointing to a particular component or location on the screen.
  38469. @see BubbleComponent
  38470. */
  38471. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  38472. private Timer
  38473. {
  38474. public:
  38475. /** Creates a bubble component.
  38476. After creating one a BubbleComponent, do the following:
  38477. - add it to an appropriate parent component, or put it on the
  38478. desktop with Component::addToDesktop (0).
  38479. - use the showAt() method to show a message.
  38480. - it will make itself invisible after it times-out (and can optionally
  38481. also delete itself), or you can reuse it somewhere else by calling
  38482. showAt() again.
  38483. */
  38484. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  38485. /** Destructor. */
  38486. ~BubbleMessageComponent();
  38487. /** Shows a message bubble at a particular position.
  38488. This shows the bubble with its stem pointing to the given location
  38489. (co-ordinates being relative to its parent component).
  38490. For details about exactly how it decides where to position itself, see
  38491. BubbleComponent::updatePosition().
  38492. @param x the x co-ordinate of end of the bubble's tail
  38493. @param y the y co-ordinate of end of the bubble's tail
  38494. @param message the text to display
  38495. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38496. from its parent compnent. If this is 0 or less, it
  38497. will stay there until manually removed.
  38498. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38499. mouse button is pressed (anywhere on the screen)
  38500. @param deleteSelfAfterUse if true, then the component will delete itself after
  38501. it becomes invisible
  38502. */
  38503. void showAt (int x, int y,
  38504. const String& message,
  38505. const int numMillisecondsBeforeRemoving,
  38506. const bool removeWhenMouseClicked = true,
  38507. const bool deleteSelfAfterUse = false);
  38508. /** Shows a message bubble next to a particular component.
  38509. This shows the bubble with its stem pointing at the given component.
  38510. For details about exactly how it decides where to position itself, see
  38511. BubbleComponent::updatePosition().
  38512. @param component the component that you want to point at
  38513. @param message the text to display
  38514. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  38515. from its parent compnent. If this is 0 or less, it
  38516. will stay there until manually removed.
  38517. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  38518. mouse button is pressed (anywhere on the screen)
  38519. @param deleteSelfAfterUse if true, then the component will delete itself after
  38520. it becomes invisible
  38521. */
  38522. void showAt (Component* const component,
  38523. const String& message,
  38524. const int numMillisecondsBeforeRemoving,
  38525. const bool removeWhenMouseClicked = true,
  38526. const bool deleteSelfAfterUse = false);
  38527. /** @internal */
  38528. void getContentSize (int& w, int& h);
  38529. /** @internal */
  38530. void paintContent (Graphics& g, int w, int h);
  38531. /** @internal */
  38532. void timerCallback();
  38533. juce_UseDebuggingNewOperator
  38534. private:
  38535. int fadeOutLength, mouseClickCounter;
  38536. TextLayout textLayout;
  38537. int64 expiryTime;
  38538. bool deleteAfterUse;
  38539. void init (const int numMillisecondsBeforeRemoving,
  38540. const bool removeWhenMouseClicked,
  38541. const bool deleteSelfAfterUse);
  38542. BubbleMessageComponent (const BubbleMessageComponent&);
  38543. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  38544. };
  38545. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  38546. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  38547. #endif
  38548. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38549. /********* Start of inlined file: juce_ColourSelector.h *********/
  38550. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  38551. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  38552. /**
  38553. A component that lets the user choose a colour.
  38554. This shows RGB sliders and a colourspace that the user can pick colours from.
  38555. This class is also a ChangeBroadcaster, so listeners can register to be told
  38556. when the colour changes.
  38557. */
  38558. class JUCE_API ColourSelector : public Component,
  38559. public ChangeBroadcaster,
  38560. protected SliderListener
  38561. {
  38562. public:
  38563. /** Options for the type of selector to show. These are passed into the constructor. */
  38564. enum ColourSelectorOptions
  38565. {
  38566. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  38567. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  38568. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  38569. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  38570. };
  38571. /** Creates a ColourSelector object.
  38572. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  38573. which of the selector's features should be visible.
  38574. The edgeGap value specifies the amount of space to leave around the edge.
  38575. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  38576. colourspace and hue selector components.
  38577. */
  38578. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  38579. const int edgeGap = 4,
  38580. const int gapAroundColourSpaceComponent = 7);
  38581. /** Destructor. */
  38582. ~ColourSelector();
  38583. /** Returns the colour that the user has currently selected.
  38584. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  38585. register to be told when the colour changes.
  38586. @see setCurrentColour
  38587. */
  38588. const Colour getCurrentColour() const;
  38589. /** Changes the colour that is currently being shown.
  38590. */
  38591. void setCurrentColour (const Colour& newColour);
  38592. /** Tells the selector how many preset colour swatches you want to have on the component.
  38593. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38594. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38595. their values.
  38596. */
  38597. virtual int getNumSwatches() const;
  38598. /** Called by the selector to find out the colour of one of the swatches.
  38599. Your subclass should return the colour of the swatch with the given index.
  38600. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38601. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38602. their values.
  38603. */
  38604. virtual const Colour getSwatchColour (const int index) const;
  38605. /** Called by the selector when the user puts a new colour into one of the swatches.
  38606. Your subclass should change the colour of the swatch with the given index.
  38607. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  38608. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  38609. their values.
  38610. */
  38611. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  38612. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38613. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38614. methods.
  38615. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38616. */
  38617. enum ColourIds
  38618. {
  38619. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  38620. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  38621. };
  38622. juce_UseDebuggingNewOperator
  38623. private:
  38624. friend class ColourSpaceView;
  38625. friend class HueSelectorComp;
  38626. Colour colour;
  38627. float h, s, v;
  38628. Slider* sliders[4];
  38629. Component* colourSpace;
  38630. Component* hueSelector;
  38631. VoidArray swatchComponents;
  38632. const int flags;
  38633. int topSpace, edgeGap;
  38634. void setHue (float newH);
  38635. void setSV (float newS, float newV);
  38636. void updateHSV();
  38637. void update();
  38638. void sliderValueChanged (Slider*);
  38639. void paint (Graphics& g);
  38640. void resized();
  38641. ColourSelector (const ColourSelector&);
  38642. const ColourSelector& operator= (const ColourSelector&);
  38643. // this constructor is here temporarily to prevent old code compiling, because the parameters
  38644. // have changed - if you get an error here, update your code to use the new constructor instead..
  38645. // (xxx - note to self: remember to remove this at some point in the future)
  38646. ColourSelector (const bool);
  38647. };
  38648. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  38649. /********* End of inlined file: juce_ColourSelector.h *********/
  38650. #endif
  38651. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  38652. #endif
  38653. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38654. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  38655. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38656. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38657. /**
  38658. A component that contains another component, and can magnify or shrink it.
  38659. This component will continually update its size so that it fits the zoomed
  38660. version of the content component that you put inside it, so don't try to
  38661. change the size of this component directly - instead change that of the
  38662. content component.
  38663. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  38664. to remap mouse events correctly. This means that the content component won't
  38665. appear to be a direct child of this component, and instead will think its
  38666. on the desktop.
  38667. */
  38668. class JUCE_API MagnifierComponent : public Component
  38669. {
  38670. public:
  38671. /** Creates a MagnifierComponent.
  38672. This component will continually update its size so that it fits the zoomed
  38673. version of the content component that you put inside it, so don't try to
  38674. change the size of this component directly - instead change that of the
  38675. content component.
  38676. @param contentComponent the component to add as the magnified one
  38677. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  38678. be deleted when this component is deleted. If false,
  38679. it's the caller's responsibility to delete it later.
  38680. */
  38681. MagnifierComponent (Component* const contentComponent,
  38682. const bool deleteContentCompWhenNoLongerNeeded);
  38683. /** Destructor. */
  38684. ~MagnifierComponent();
  38685. /** Returns the current content component. */
  38686. Component* getContentComponent() const throw() { return content; }
  38687. /** Changes the zoom level.
  38688. The scale factor must be greater than zero. Values less than 1 will shrink the
  38689. image; values greater than 1 will multiply its size by this amount.
  38690. When this is called, this component will change its size to fit the full extent
  38691. of the newly zoomed content.
  38692. */
  38693. void setScaleFactor (double newScaleFactor);
  38694. /** Returns the current zoom factor. */
  38695. double getScaleFactor() const throw() { return scaleFactor; }
  38696. juce_UseDebuggingNewOperator
  38697. /** @internal */
  38698. void childBoundsChanged (Component*);
  38699. private:
  38700. Component* content;
  38701. Component* holderComp;
  38702. double scaleFactor;
  38703. ComponentPeer* peer;
  38704. bool deleteContent;
  38705. void paint (Graphics& g);
  38706. void mouseDown (const MouseEvent& e);
  38707. void mouseUp (const MouseEvent& e);
  38708. void mouseDrag (const MouseEvent& e);
  38709. void mouseMove (const MouseEvent& e);
  38710. void mouseEnter (const MouseEvent& e);
  38711. void mouseExit (const MouseEvent& e);
  38712. void mouseWheelMove (const MouseEvent& e, float, float);
  38713. int scaleInt (const int n) const throw();
  38714. MagnifierComponent (const MagnifierComponent&);
  38715. const MagnifierComponent& operator= (const MagnifierComponent&);
  38716. };
  38717. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  38718. /********* End of inlined file: juce_MagnifierComponent.h *********/
  38719. #endif
  38720. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38721. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  38722. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38723. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  38724. /**
  38725. A component that displays a piano keyboard, whose notes can be clicked on.
  38726. This component will mimic a physical midi keyboard, showing the current state of
  38727. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  38728. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  38729. Another feature is that the computer keyboard can also be used to play notes. By
  38730. default it maps the top two rows of a standard querty keyboard to the notes, but
  38731. these can be remapped if needed. It will only respond to keypresses when it has
  38732. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  38733. The component is also a ChangeBroadcaster, so if you want to be informed when the
  38734. keyboard is scrolled, you can register a ChangeListener for callbacks.
  38735. @see MidiKeyboardState
  38736. */
  38737. class JUCE_API MidiKeyboardComponent : public Component,
  38738. public MidiKeyboardStateListener,
  38739. public ChangeBroadcaster,
  38740. private Timer,
  38741. private AsyncUpdater
  38742. {
  38743. public:
  38744. /** The direction of the keyboard.
  38745. @see setOrientation
  38746. */
  38747. enum Orientation
  38748. {
  38749. horizontalKeyboard,
  38750. verticalKeyboardFacingLeft,
  38751. verticalKeyboardFacingRight,
  38752. };
  38753. /** Creates a MidiKeyboardComponent.
  38754. @param state the midi keyboard model that this component will represent
  38755. @param orientation whether the keyboard is horizonal or vertical
  38756. */
  38757. MidiKeyboardComponent (MidiKeyboardState& state,
  38758. const Orientation orientation);
  38759. /** Destructor. */
  38760. ~MidiKeyboardComponent();
  38761. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  38762. on the component.
  38763. Values are 0 to 1.0, where 1.0 is the heaviest.
  38764. @see setMidiChannel
  38765. */
  38766. void setVelocity (const float velocity);
  38767. /** Changes the midi channel number that will be used for events triggered by clicking
  38768. on the component.
  38769. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  38770. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  38771. Although this is the channel used for outgoing events, the component can display
  38772. incoming events from more than one channel - see setMidiChannelsToDisplay()
  38773. @see setVelocity
  38774. */
  38775. void setMidiChannel (const int midiChannelNumber);
  38776. /** Returns the midi channel that the keyboard is using for midi messages.
  38777. @see setMidiChannel
  38778. */
  38779. int getMidiChannel() const throw() { return midiChannel; }
  38780. /** Sets a mask to indicate which incoming midi channels should be represented by
  38781. key movements.
  38782. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  38783. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  38784. in this mask, the on-screen keys will also go down.
  38785. By default, this mask is set to 0xffff (all channels displayed).
  38786. @see setMidiChannel
  38787. */
  38788. void setMidiChannelsToDisplay (const int midiChannelMask);
  38789. /** Returns the current set of midi channels represented by the component.
  38790. This is the value that was set with setMidiChannelsToDisplay().
  38791. */
  38792. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  38793. /** Changes the width used to draw the white keys. */
  38794. void setKeyWidth (const float widthInPixels);
  38795. /** Returns the width that was set by setKeyWidth(). */
  38796. float getKeyWidth() const throw() { return keyWidth; }
  38797. /** Changes the keyboard's current direction. */
  38798. void setOrientation (const Orientation newOrientation);
  38799. /** Returns the keyboard's current direction. */
  38800. const Orientation getOrientation() const throw() { return orientation; }
  38801. /** Sets the range of midi notes that the keyboard will be limited to.
  38802. By default the range is 0 to 127 (inclusive), but you can limit this if you
  38803. only want a restricted set of the keys to be shown.
  38804. Note that the values here are inclusive and must be between 0 and 127.
  38805. */
  38806. void setAvailableRange (const int lowestNote,
  38807. const int highestNote);
  38808. /** Returns the first note in the available range.
  38809. @see setAvailableRange
  38810. */
  38811. int getRangeStart() const throw() { return rangeStart; }
  38812. /** Returns the last note in the available range.
  38813. @see setAvailableRange
  38814. */
  38815. int getRangeEnd() const throw() { return rangeEnd; }
  38816. /** If the keyboard extends beyond the size of the component, this will scroll
  38817. it to show the given key at the start.
  38818. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  38819. base class to send a callback to any ChangeListeners that have been registered.
  38820. */
  38821. void setLowestVisibleKey (int noteNumber);
  38822. /** Returns the number of the first key shown in the component.
  38823. @see setLowestVisibleKey
  38824. */
  38825. int getLowestVisibleKey() const throw() { return firstKey; }
  38826. /** Returns the length of the black notes.
  38827. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  38828. */
  38829. int getBlackNoteLength() const throw() { return blackNoteLength; }
  38830. /** If set to true, then scroll buttons will appear at either end of the keyboard
  38831. if there are too many notes to fit them all in the component at once.
  38832. */
  38833. void setScrollButtonsVisible (const bool canScroll);
  38834. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  38835. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38836. methods.
  38837. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38838. */
  38839. enum ColourIds
  38840. {
  38841. whiteNoteColourId = 0x1005000,
  38842. blackNoteColourId = 0x1005001,
  38843. keySeparatorLineColourId = 0x1005002,
  38844. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  38845. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  38846. textLabelColourId = 0x1005005,
  38847. upDownButtonBackgroundColourId = 0x1005006,
  38848. upDownButtonArrowColourId = 0x1005007
  38849. };
  38850. /** Returns the position within the component of the left-hand edge of a key.
  38851. Depending on the keyboard's orientation, this may be a horizontal or vertical
  38852. distance, in either direction.
  38853. */
  38854. int getKeyStartPosition (const int midiNoteNumber) const;
  38855. /** Deletes all key-mappings.
  38856. @see setKeyPressForNote
  38857. */
  38858. void clearKeyMappings();
  38859. /** Maps a key-press to a given note.
  38860. @param key the key that should trigger the note
  38861. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  38862. be. The actual midi note that gets played will be
  38863. this value + (12 * the current base octave). To change
  38864. the base octave, see setKeyPressBaseOctave()
  38865. */
  38866. void setKeyPressForNote (const KeyPress& key,
  38867. const int midiNoteOffsetFromC);
  38868. /** Removes any key-mappings for a given note.
  38869. For a description of what the note number means, see setKeyPressForNote().
  38870. */
  38871. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  38872. /** Changes the base note above which key-press-triggered notes are played.
  38873. The set of key-mappings that trigger notes can be moved up and down to cover
  38874. the entire scale using this method.
  38875. The value passed in is an octave number between 0 and 10 (inclusive), and
  38876. indicates which C is the base note to which the key-mapped notes are
  38877. relative.
  38878. */
  38879. void setKeyPressBaseOctave (const int newOctaveNumber);
  38880. /** This sets the octave number which is shown as the octave number for middle C.
  38881. This affects only the default implementation of getWhiteNoteText(), which
  38882. passes this octave number to MidiMessage::getMidiNoteName() in order to
  38883. get the note text. See MidiMessage::getMidiNoteName() for more info about
  38884. the parameter.
  38885. By default this value is set to 3.
  38886. @see getOctaveForMiddleC
  38887. */
  38888. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  38889. /** This returns the value set by setOctaveForMiddleC().
  38890. @see setOctaveForMiddleC
  38891. */
  38892. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  38893. /** @internal */
  38894. void paint (Graphics& g);
  38895. /** @internal */
  38896. void resized();
  38897. /** @internal */
  38898. void mouseMove (const MouseEvent& e);
  38899. /** @internal */
  38900. void mouseDrag (const MouseEvent& e);
  38901. /** @internal */
  38902. void mouseDown (const MouseEvent& e);
  38903. /** @internal */
  38904. void mouseUp (const MouseEvent& e);
  38905. /** @internal */
  38906. void mouseEnter (const MouseEvent& e);
  38907. /** @internal */
  38908. void mouseExit (const MouseEvent& e);
  38909. /** @internal */
  38910. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  38911. /** @internal */
  38912. void timerCallback();
  38913. /** @internal */
  38914. bool keyStateChanged();
  38915. /** @internal */
  38916. void focusLost (FocusChangeType cause);
  38917. /** @internal */
  38918. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  38919. /** @internal */
  38920. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  38921. /** @internal */
  38922. void handleAsyncUpdate();
  38923. /** @internal */
  38924. void colourChanged();
  38925. juce_UseDebuggingNewOperator
  38926. protected:
  38927. friend class MidiKeyboardUpDownButton;
  38928. /** Draws a white note in the given rectangle.
  38929. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38930. currently pressed down.
  38931. When doing this, be sure to note the keyboard's orientation.
  38932. */
  38933. virtual void drawWhiteNote (int midiNoteNumber,
  38934. Graphics& g,
  38935. int x, int y, int w, int h,
  38936. bool isDown, bool isOver,
  38937. const Colour& lineColour,
  38938. const Colour& textColour);
  38939. /** Draws a black note in the given rectangle.
  38940. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  38941. currently pressed down.
  38942. When doing this, be sure to note the keyboard's orientation.
  38943. */
  38944. virtual void drawBlackNote (int midiNoteNumber,
  38945. Graphics& g,
  38946. int x, int y, int w, int h,
  38947. bool isDown, bool isOver,
  38948. const Colour& noteFillColour);
  38949. /** Allows text to be drawn on the white notes.
  38950. By default this is used to label the C in each octave, but could be used for other things.
  38951. @see setOctaveForMiddleC
  38952. */
  38953. virtual const String getWhiteNoteText (const int midiNoteNumber);
  38954. /** Draws the up and down buttons that change the base note. */
  38955. virtual void drawUpDownButton (Graphics& g, int w, int h,
  38956. const bool isMouseOver,
  38957. const bool isButtonPressed,
  38958. const bool movesOctavesUp);
  38959. /** Callback when the mouse is clicked on a key.
  38960. You could use this to do things like handle right-clicks on keys, etc.
  38961. Return true if you want the click to trigger the note, or false if you
  38962. want to handle it yourself and not have the note played.
  38963. @see mouseDraggedToKey
  38964. */
  38965. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  38966. /** Callback when the mouse is dragged from one key onto another.
  38967. @see mouseDownOnKey
  38968. */
  38969. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  38970. /** Calculates the positon of a given midi-note.
  38971. This can be overridden to create layouts with custom key-widths.
  38972. @param midiNoteNumber the note to find
  38973. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  38974. @param x the x position of the left-hand edge of the key (this method
  38975. always works in terms of a horizontal keyboard)
  38976. @param w the width of the key
  38977. */
  38978. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  38979. int& x, int& w) const;
  38980. private:
  38981. MidiKeyboardState& state;
  38982. int xOffset, blackNoteLength;
  38983. float keyWidth;
  38984. Orientation orientation;
  38985. int midiChannel, midiInChannelMask;
  38986. float velocity;
  38987. int noteUnderMouse, mouseDownNote;
  38988. BitArray keysPressed, keysCurrentlyDrawnDown;
  38989. int rangeStart, rangeEnd, firstKey;
  38990. bool canScroll, mouseDragging;
  38991. Button* scrollDown;
  38992. Button* scrollUp;
  38993. Array <KeyPress> keyPresses;
  38994. Array <int> keyPressNotes;
  38995. int keyMappingOctave;
  38996. int octaveNumForMiddleC;
  38997. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  38998. int xyToNote (int x, int y);
  38999. int remappedXYToNote (int x, int y) const;
  39000. void resetAnyKeysInUse();
  39001. void updateNoteUnderMouse (int x, int y);
  39002. void repaintNote (const int midiNoteNumber);
  39003. MidiKeyboardComponent (const MidiKeyboardComponent&);
  39004. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  39005. };
  39006. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39007. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  39008. #endif
  39009. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39010. /********* Start of inlined file: juce_NSViewComponent.h *********/
  39011. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39012. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39013. #if ! DOXYGEN
  39014. class NSViewComponentInternal;
  39015. #endif
  39016. #if JUCE_MAC || DOXYGEN
  39017. /**
  39018. A Mac-specific class that can create and embed an NSView inside itself.
  39019. To use it, create one of these, put it in place and make sure it's visible in a
  39020. window, then use setView() to assign an NSView to it. The view will then be
  39021. moved and resized to follow the movements of this component.
  39022. Of course, since the view is a native object, it'll obliterate any
  39023. juce components that may overlap this component, but that's life.
  39024. */
  39025. class JUCE_API NSViewComponent : public Component
  39026. {
  39027. public:
  39028. /** Create an initially-empty container. */
  39029. NSViewComponent();
  39030. /** Destructor. */
  39031. ~NSViewComponent();
  39032. /** Assigns an NSView to this peer.
  39033. The view will be retained and released by this component for as long as
  39034. it is needed. To remove the current view, just call setView (0).
  39035. Note: a void* is used here to avoid including the cocoa headers as
  39036. part of the juce.h, but the method expects an NSView*.
  39037. */
  39038. void setView (void* nsView);
  39039. /** Returns the current NSView.
  39040. Note: a void* is returned here to avoid including the cocoa headers as
  39041. a requirement of juce.h, so you should just cast the object to an NSView*.
  39042. */
  39043. void* getView() const;
  39044. /** @internal */
  39045. void paint (Graphics& g);
  39046. juce_UseDebuggingNewOperator
  39047. private:
  39048. friend class NSViewComponentInternal;
  39049. NSViewComponentInternal* info;
  39050. NSViewComponent (const NSViewComponent&);
  39051. const NSViewComponent& operator= (const NSViewComponent&);
  39052. };
  39053. #endif
  39054. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39055. /********* End of inlined file: juce_NSViewComponent.h *********/
  39056. #endif
  39057. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39058. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  39059. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39060. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39061. // this is used to disable OpenGL, and is defined in juce_Config.h
  39062. #if JUCE_OPENGL || DOXYGEN
  39063. class OpenGLComponentWatcher;
  39064. /**
  39065. Represents the various properties of an OpenGL bitmap format.
  39066. @see OpenGLComponent::setPixelFormat
  39067. */
  39068. struct OpenGLPixelFormat
  39069. {
  39070. /** Creates an OpenGLPixelFormat.
  39071. The default constructor just initialises the object as a simple 8-bit
  39072. RGBA format.
  39073. */
  39074. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  39075. const int alphaBits = 8,
  39076. const int depthBufferBits = 16,
  39077. const int stencilBufferBits = 0) throw();
  39078. int redBits; /**< The number of bits per pixel to use for the red channel. */
  39079. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  39080. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  39081. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  39082. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  39083. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  39084. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  39085. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  39086. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  39087. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  39088. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  39089. /** Returns a list of all the pixel formats that can be used in this system.
  39090. A reference component is needed in case there are multiple screens with different
  39091. capabilities - in which case, the one that the component is on will be used.
  39092. */
  39093. static void getAvailablePixelFormats (Component* component,
  39094. OwnedArray <OpenGLPixelFormat>& results);
  39095. bool operator== (const OpenGLPixelFormat&) const throw();
  39096. juce_UseDebuggingNewOperator
  39097. };
  39098. /**
  39099. A base class for types of OpenGL context.
  39100. An OpenGLComponent will supply its own context for drawing in its window.
  39101. */
  39102. class OpenGLContext
  39103. {
  39104. public:
  39105. /** Destructor. */
  39106. virtual ~OpenGLContext();
  39107. /** Makes this context the currently active one. */
  39108. virtual bool makeActive() const throw() = 0;
  39109. /** If this context is currently active, it is disactivated. */
  39110. virtual bool makeInactive() const throw() = 0;
  39111. /** Returns true if this context is currently active. */
  39112. virtual bool isActive() const throw() = 0;
  39113. /** Swaps the buffers (if the context can do this). */
  39114. virtual void swapBuffers() = 0;
  39115. /** Sets whether the context checks the vertical sync before swapping.
  39116. The value is the number of frames to allow between buffer-swapping. This is
  39117. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  39118. and greater numbers indicate that it should swap less often.
  39119. Returns true if it sets the value successfully.
  39120. */
  39121. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  39122. /** Returns the current swap-sync interval.
  39123. See setSwapInterval() for info about the value returned.
  39124. */
  39125. virtual int getSwapInterval() const = 0;
  39126. /** Returns the pixel format being used by this context. */
  39127. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  39128. /** For windowed contexts, this moves the context within the bounds of
  39129. its parent window.
  39130. */
  39131. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  39132. /** For windowed contexts, this triggers a repaint of the window.
  39133. (Not relevent on all platforms).
  39134. */
  39135. virtual void repaint() = 0;
  39136. /** Returns an OS-dependent handle to the raw GL context.
  39137. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  39138. a GLXContext.
  39139. */
  39140. virtual void* getRawContext() const throw() = 0;
  39141. /** This tries to create a context that can be used for drawing into the
  39142. area occupied by the specified component.
  39143. Note that you probably shouldn't use this method directly unless you know what
  39144. you're doing - the OpenGLComponent calls this and manages the context for you.
  39145. */
  39146. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  39147. const OpenGLPixelFormat& pixelFormat,
  39148. const OpenGLContext* const contextToShareWith);
  39149. /** Returns the context that's currently in active use by the calling thread.
  39150. Returns 0 if there isn't an active context.
  39151. */
  39152. static OpenGLContext* getCurrentContext();
  39153. juce_UseDebuggingNewOperator
  39154. protected:
  39155. OpenGLContext() throw();
  39156. };
  39157. /**
  39158. A component that contains an OpenGL canvas.
  39159. Override this, add it to whatever component you want to, and use the renderOpenGL()
  39160. method to draw its contents.
  39161. */
  39162. class JUCE_API OpenGLComponent : public Component
  39163. {
  39164. public:
  39165. /** Creates an OpenGLComponent.
  39166. */
  39167. OpenGLComponent();
  39168. /** Destructor. */
  39169. ~OpenGLComponent();
  39170. /** Changes the pixel format used by this component.
  39171. @see OpenGLPixelFormat::getAvailablePixelFormats()
  39172. */
  39173. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  39174. /** Returns the pixel format that this component is currently using. */
  39175. const OpenGLPixelFormat getPixelFormat() const;
  39176. /** Specifies an OpenGL context which should be shared with the one that this
  39177. component is using.
  39178. This is an OpenGL feature that lets two contexts share their texture data.
  39179. Note that this pointer is stored by the component, and when the component
  39180. needs to recreate its internal context for some reason, the same context
  39181. will be used again to share lists. So if you pass a context in here,
  39182. don't delete the context while this component is still using it! You can
  39183. call shareWith (0) to stop this component from sharing with it.
  39184. */
  39185. void shareWith (OpenGLContext* contextToShareListsWith);
  39186. /** Returns the context that this component is sharing with.
  39187. @see shareWith
  39188. */
  39189. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  39190. /** Flips the openGL buffers over. */
  39191. void swapBuffers();
  39192. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  39193. When this is called, makeCurrentContextActive() will already have been called
  39194. for you, so you just need to draw.
  39195. */
  39196. virtual void renderOpenGL() = 0;
  39197. /** This method is called when the component creates a new OpenGL context.
  39198. A new context may be created when the component is first used, or when it
  39199. is moved to a different window, or when the window is hidden and re-shown,
  39200. etc.
  39201. You can use this callback as an opportunity to set up things like textures
  39202. that your context needs.
  39203. New contexts are created on-demand by the makeCurrentContextActive() method - so
  39204. if the context is deleted, e.g. by changing the pixel format or window, no context
  39205. will be created until the next call to makeCurrentContextActive(), which will
  39206. synchronously create one and call this method. This means that if you're using
  39207. a non-GUI thread for rendering, you can make sure this method is be called by
  39208. your renderer thread.
  39209. When this callback happens, the context will already have been made current
  39210. using the makeCurrentContextActive() method, so there's no need to call it
  39211. again in your code.
  39212. */
  39213. virtual void newOpenGLContextCreated() = 0;
  39214. /** Returns the context that will draw into this component.
  39215. This may return 0 if the component is currently invisible or hasn't currently
  39216. got a context. The context object can be deleted and a new one created during
  39217. the lifetime of this component, and there may be times when it doesn't have one.
  39218. @see newOpenGLContextCreated()
  39219. */
  39220. OpenGLContext* getCurrentContext() const throw() { return context; }
  39221. /** Makes this component the current openGL context.
  39222. You might want to use this in things like your resize() method, before calling
  39223. GL commands.
  39224. If this returns false, then the context isn't active, so you should avoid
  39225. making any calls.
  39226. This call may actually create a context if one isn't currently initialised. If
  39227. it does this, it will also synchronously call the newOpenGLContextCreated()
  39228. method to let you initialise it as necessary.
  39229. @see OpenGLContext::makeActive
  39230. */
  39231. bool makeCurrentContextActive();
  39232. /** Stops the current component being the active OpenGL context.
  39233. This is the opposite of makeCurrentContextActive()
  39234. @see OpenGLContext::makeInactive
  39235. */
  39236. void makeCurrentContextInactive();
  39237. /** Returns true if this component is the active openGL context for the
  39238. current thread.
  39239. @see OpenGLContext::isActive
  39240. */
  39241. bool isActiveContext() const throw();
  39242. /** Calls the rendering callback, and swaps the buffers afterwards.
  39243. This is called automatically by paint() when the component needs to be rendered.
  39244. It can be overridden if you need to decouple the rendering from the paint callback
  39245. and render with a custom thread.
  39246. Returns true if the operation succeeded.
  39247. */
  39248. virtual bool renderAndSwapBuffers();
  39249. /** This returns a critical section that can be used to lock the current context.
  39250. Because the context that is used by this component can change, e.g. when the
  39251. component is shown or hidden, then if you're rendering to it on a background
  39252. thread, this allows you to lock the context for the duration of your rendering
  39253. routine.
  39254. */
  39255. CriticalSection& getContextLock() throw() { return contextLock; }
  39256. /** @internal */
  39257. void paint (Graphics& g);
  39258. /** Returns the native handle of an embedded heavyweight window, if there is one.
  39259. E.g. On windows, this will return the HWND of the sub-window containing
  39260. the opengl context, on the mac it'll be the NSOpenGLView.
  39261. */
  39262. void* getNativeWindowHandle() const;
  39263. juce_UseDebuggingNewOperator
  39264. private:
  39265. friend class OpenGLComponentWatcher;
  39266. OpenGLComponentWatcher* componentWatcher;
  39267. OpenGLContext* context;
  39268. OpenGLContext* contextToShareListsWith;
  39269. CriticalSection contextLock;
  39270. OpenGLPixelFormat preferredPixelFormat;
  39271. bool needToUpdateViewport;
  39272. void deleteContext();
  39273. void updateContextPosition();
  39274. void internalRepaint (int x, int y, int w, int h);
  39275. OpenGLComponent (const OpenGLComponent&);
  39276. const OpenGLComponent& operator= (const OpenGLComponent&);
  39277. };
  39278. #endif
  39279. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39280. /********* End of inlined file: juce_OpenGLComponent.h *********/
  39281. #endif
  39282. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39283. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  39284. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39285. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39286. /**
  39287. A component with a set of buttons at the top for changing between pages of
  39288. preferences.
  39289. This is just a handy way of writing a Mac-style preferences panel where you
  39290. have a row of buttons along the top for the different preference categories,
  39291. each button having an icon above its name. Clicking these will show an
  39292. appropriate prefs page below it.
  39293. You can either put one of these inside your own component, or just use the
  39294. showInDialogBox() method to show it in a window and run it modally.
  39295. To use it, just add a set of named pages with the addSettingsPage() method,
  39296. and implement the createComponentForPage() method to create suitable components
  39297. for each of these pages.
  39298. */
  39299. class JUCE_API PreferencesPanel : public Component,
  39300. private ButtonListener
  39301. {
  39302. public:
  39303. /** Creates an empty panel.
  39304. Use addSettingsPage() to add some pages to it in your constructor.
  39305. */
  39306. PreferencesPanel();
  39307. /** Destructor. */
  39308. ~PreferencesPanel();
  39309. /** Creates a page using a set of drawables to define the page's icon.
  39310. Note that the other version of this method is much easier if you're using
  39311. an image instead of a custom drawable.
  39312. @param pageTitle the name of this preferences page - you'll need to
  39313. make sure your createComponentForPage() method creates
  39314. a suitable component when it is passed this name
  39315. @param normalIcon the drawable to display in the page's button normally
  39316. @param overIcon the drawable to display in the page's button when the mouse is over
  39317. @param downIcon the drawable to display in the page's button when the button is down
  39318. @see DrawableButton
  39319. */
  39320. void addSettingsPage (const String& pageTitle,
  39321. const Drawable* normalIcon,
  39322. const Drawable* overIcon,
  39323. const Drawable* downIcon);
  39324. /** Creates a page using a set of drawables to define the page's icon.
  39325. The other version of this method gives you more control over the icon, but this
  39326. one is much easier if you're just loading it from a file.
  39327. @param pageTitle the name of this preferences page - you'll need to
  39328. make sure your createComponentForPage() method creates
  39329. a suitable component when it is passed this name
  39330. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  39331. For this to look good, you'll probably want to use a nice
  39332. transparent png file.
  39333. @param imageDataSize the size of the image data, in bytes
  39334. */
  39335. void addSettingsPage (const String& pageTitle,
  39336. const char* imageData,
  39337. const int imageDataSize);
  39338. /** Utility method to display this panel in a DialogWindow.
  39339. Calling this will create a DialogWindow containing this panel with the
  39340. given size and title, and will run it modally, returning when the user
  39341. closes the dialog box.
  39342. */
  39343. void showInDialogBox (const String& dialogtitle,
  39344. int dialogWidth,
  39345. int dialogHeight,
  39346. const Colour& backgroundColour = Colours::white);
  39347. /** Subclasses must override this to return a component for each preferences page.
  39348. The subclass should return a pointer to a new component representing the named
  39349. page, which the panel will then display.
  39350. The panel will delete the component later when the user goes to another page
  39351. or deletes the panel.
  39352. */
  39353. virtual Component* createComponentForPage (const String& pageName) = 0;
  39354. /** Changes the current page being displayed. */
  39355. void setCurrentPage (const String& pageName);
  39356. /** @internal */
  39357. void resized();
  39358. /** @internal */
  39359. void paint (Graphics& g);
  39360. /** @internal */
  39361. void buttonClicked (Button* button);
  39362. juce_UseDebuggingNewOperator
  39363. private:
  39364. String currentPageName;
  39365. Component* currentPage;
  39366. int buttonSize;
  39367. PreferencesPanel (const PreferencesPanel&);
  39368. const PreferencesPanel& operator= (const PreferencesPanel&);
  39369. };
  39370. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39371. /********* End of inlined file: juce_PreferencesPanel.h *********/
  39372. #endif
  39373. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39374. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  39375. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39376. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39377. // this is used to disable QuickTime, and is defined in juce_Config.h
  39378. #if JUCE_QUICKTIME || DOXYGEN
  39379. #if JUCE_WIN32
  39380. typedef ActiveXControlComponent QTCompBaseClass;
  39381. #else
  39382. typedef NSViewComponent QTCompBaseClass;
  39383. #endif
  39384. /**
  39385. A window that can play back a QuickTime movie.
  39386. */
  39387. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  39388. {
  39389. public:
  39390. /** Creates a QuickTimeMovieComponent, initially blank.
  39391. Use the loadMovie() method to load a movie once you've added the
  39392. component to a window, (or put it on the desktop as a heavyweight window).
  39393. Loading a movie when the component isn't visible can cause problems, as
  39394. QuickTime needs a window handle to initialise properly.
  39395. */
  39396. QuickTimeMovieComponent();
  39397. /** Destructor. */
  39398. ~QuickTimeMovieComponent();
  39399. /** Returns true if QT is installed and working on this machine.
  39400. */
  39401. static bool isQuickTimeAvailable() throw();
  39402. /** Tries to load a QuickTime movie into the player.
  39403. It's best to call this function once you've added the component to a window,
  39404. (or put it on the desktop as a heavyweight window). Loading a movie when the
  39405. component isn't visible can cause problems, because QuickTime needs a window
  39406. handle to do its stuff.
  39407. @param movieFile the .mov file to open
  39408. @param isControllerVisible whether to show a controller bar at the bottom
  39409. @returns true if the movie opens successfully
  39410. */
  39411. bool loadMovie (const File& movieFile,
  39412. const bool isControllerVisible);
  39413. bool loadMovie (InputStream* movieStream,
  39414. const bool isControllerVisible);
  39415. /** Closes the movie, if one is open. */
  39416. void closeMovie();
  39417. /** Returns the movie file that is currently open.
  39418. If there isn't one, this returns File::nonexistent
  39419. */
  39420. const File getCurrentMovieFile() const;
  39421. /** Returns true if there's currently a movie open. */
  39422. bool isMovieOpen() const;
  39423. /** Returns the length of the movie, in seconds. */
  39424. double getMovieDuration() const;
  39425. /** Returns the movie's natural size, in pixels.
  39426. You can use this to resize the component to show the movie at its preferred
  39427. scale.
  39428. If no movie is loaded, the size returned will be 0 x 0.
  39429. */
  39430. void getMovieNormalSize (int& width, int& height) const;
  39431. /** This will position the component within a given area, keeping its aspect
  39432. ratio correct according to the movie's normal size.
  39433. The component will be made as large as it can go within the space, and will
  39434. be aligned according to the justification value if this means there are gaps at
  39435. the top or sides.
  39436. */
  39437. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  39438. const RectanglePlacement& placement);
  39439. /** Starts the movie playing. */
  39440. void play();
  39441. /** Stops the movie playing. */
  39442. void stop();
  39443. /** Returns true if the movie is currently playing. */
  39444. bool isPlaying() const;
  39445. /** Moves the movie's position back to the start. */
  39446. void goToStart();
  39447. /** Sets the movie's position to a given time. */
  39448. void setPosition (const double seconds);
  39449. /** Returns the current play position of the movie. */
  39450. double getPosition() const;
  39451. /** Changes the movie playback rate.
  39452. A value of 1 is normal speed, greater values play it proportionately faster,
  39453. smaller values play it slower.
  39454. */
  39455. void setSpeed (const float newSpeed);
  39456. /** Changes the movie's playback volume.
  39457. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  39458. */
  39459. void setMovieVolume (const float newVolume);
  39460. /** Returns the movie's playback volume.
  39461. @returns the volume in the range 0 (silent) to 1.0 (full)
  39462. */
  39463. float getMovieVolume() const;
  39464. /** Tells the movie whether it should loop. */
  39465. void setLooping (const bool shouldLoop);
  39466. /** Returns true if the movie is currently looping.
  39467. @see setLooping
  39468. */
  39469. bool isLooping() const;
  39470. /** True if the native QuickTime controller bar is shown in the window.
  39471. @see loadMovie
  39472. */
  39473. bool isControllerVisible() const;
  39474. /** @internal */
  39475. void paint (Graphics& g);
  39476. juce_UseDebuggingNewOperator
  39477. private:
  39478. File movieFile;
  39479. bool movieLoaded, controllerVisible, looping;
  39480. #if JUCE_WIN32
  39481. /** @internal */
  39482. void parentHierarchyChanged();
  39483. /** @internal */
  39484. void visibilityChanged();
  39485. void createControlIfNeeded();
  39486. bool isControlCreated() const;
  39487. void* internal;
  39488. #else
  39489. void* movie;
  39490. #endif
  39491. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  39492. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  39493. };
  39494. #endif
  39495. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  39496. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  39497. #endif
  39498. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39499. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  39500. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39501. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39502. #if JUCE_WIN32 || JUCE_LINUX
  39503. /**
  39504. On Windows only, this component sits in the taskbar tray as a small icon.
  39505. To use it, just create one of these components, but don't attempt to make it
  39506. visible, add it to a parent, or put it on the desktop.
  39507. You can then call setIconImage() to create an icon for it in the taskbar.
  39508. To change the icon's tooltip, you can use setIconTooltip().
  39509. To respond to mouse-events, you can override the normal mouseDown(),
  39510. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  39511. position will not be valid, you can use this to respond to clicks. Traditionally
  39512. you'd use a left-click to show your application's window, and a right-click
  39513. to show a pop-up menu.
  39514. */
  39515. class JUCE_API SystemTrayIconComponent : public Component
  39516. {
  39517. public:
  39518. SystemTrayIconComponent();
  39519. /** Destructor. */
  39520. ~SystemTrayIconComponent();
  39521. /** Changes the image shown in the taskbar.
  39522. */
  39523. void setIconImage (const Image& newImage);
  39524. /** Changes the tooltip that Windows shows above the icon. */
  39525. void setIconTooltip (const String& tooltip);
  39526. #if JUCE_LINUX
  39527. /** @internal */
  39528. void paint (Graphics& g);
  39529. #endif
  39530. juce_UseDebuggingNewOperator
  39531. private:
  39532. SystemTrayIconComponent (const SystemTrayIconComponent&);
  39533. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  39534. };
  39535. #endif
  39536. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  39537. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  39538. #endif
  39539. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39540. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  39541. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39542. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39543. #if JUCE_WEB_BROWSER
  39544. class WebBrowserComponentInternal;
  39545. /**
  39546. A component that displays an embedded web browser.
  39547. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  39548. Windows, probably IE.
  39549. */
  39550. class WebBrowserComponent : public Component
  39551. {
  39552. public:
  39553. /** Creates a WebBrowserComponent.
  39554. Once it's created and visible, send the browser to a URL using goToURL().
  39555. */
  39556. WebBrowserComponent();
  39557. /** Destructor. */
  39558. ~WebBrowserComponent();
  39559. /** Sends the browser to a particular URL.
  39560. @param url the URL to go to.
  39561. @param headers an optional set of parameters to put in the HTTP header. If
  39562. you supply this, it should be a set of string in the form
  39563. "HeaderKey: HeaderValue"
  39564. @param postData an optional block of data that will be attached to the HTTP
  39565. POST request
  39566. */
  39567. void goToURL (const String& url,
  39568. const StringArray* headers = 0,
  39569. const MemoryBlock* postData = 0);
  39570. /** Stops the current page loading.
  39571. */
  39572. void stop();
  39573. /** Sends the browser back one page.
  39574. */
  39575. void goBack();
  39576. /** Sends the browser forward one page.
  39577. */
  39578. void goForward();
  39579. /** Refreshes the browser.
  39580. */
  39581. void refresh();
  39582. /** This callback is called when the browser is about to navigate
  39583. to a new location.
  39584. You can override this method to perform some action when the user
  39585. tries to go to a particular URL. To allow the operation to carry on,
  39586. return true, or return false to stop the navigation happening.
  39587. */
  39588. virtual bool pageAboutToLoad (const String& newURL);
  39589. /** @internal */
  39590. void paint (Graphics& g);
  39591. /** @internal */
  39592. void resized();
  39593. /** @internal */
  39594. void parentHierarchyChanged();
  39595. /** @internal */
  39596. void visibilityChanged();
  39597. juce_UseDebuggingNewOperator
  39598. private:
  39599. WebBrowserComponentInternal* browser;
  39600. bool blankPageShown;
  39601. String lastURL;
  39602. StringArray lastHeaders;
  39603. MemoryBlock lastPostData;
  39604. void reloadLastURL();
  39605. void checkWindowAssociation();
  39606. WebBrowserComponent (const WebBrowserComponent&);
  39607. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  39608. };
  39609. #endif
  39610. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  39611. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  39612. #endif
  39613. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39614. /********* Start of inlined file: juce_LookAndFeel.h *********/
  39615. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39616. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39617. class ToggleButton;
  39618. class TextButton;
  39619. class AlertWindow;
  39620. class TextLayout;
  39621. class ScrollBar;
  39622. class BubbleComponent;
  39623. class ComboBox;
  39624. class Button;
  39625. class FilenameComponent;
  39626. class DocumentWindow;
  39627. class ResizableWindow;
  39628. class GroupComponent;
  39629. class MenuBarComponent;
  39630. class DropShadower;
  39631. class GlyphArrangement;
  39632. class PropertyComponent;
  39633. class TableHeaderComponent;
  39634. class Toolbar;
  39635. class ToolbarItemComponent;
  39636. class PopupMenu;
  39637. class ProgressBar;
  39638. class FileBrowserComponent;
  39639. class DirectoryContentsDisplayComponent;
  39640. class FilePreviewComponent;
  39641. /**
  39642. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  39643. can be used to apply different 'skins' to the application.
  39644. */
  39645. class JUCE_API LookAndFeel
  39646. {
  39647. public:
  39648. /** Creates the default JUCE look and feel. */
  39649. LookAndFeel();
  39650. /** Destructor. */
  39651. virtual ~LookAndFeel();
  39652. /** Returns the current default look-and-feel for a component to use when it
  39653. hasn't got one explicitly set.
  39654. @see setDefaultLookAndFeel
  39655. */
  39656. static LookAndFeel& getDefaultLookAndFeel() throw();
  39657. /** Changes the default look-and-feel.
  39658. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  39659. set to 0, it will revert to using the default one. The
  39660. object passed-in must be deleted by the caller when
  39661. it's no longer needed.
  39662. @see getDefaultLookAndFeel
  39663. */
  39664. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  39665. /** Looks for a colour that has been registered with the given colour ID number.
  39666. If a colour has been set for this ID number using setColour(), then it is
  39667. returned. If none has been set, it will just return Colours::black.
  39668. The colour IDs for various purposes are stored as enums in the components that
  39669. they are relevent to - for an example, see Slider::ColourIds,
  39670. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  39671. If you're looking up a colour for use in drawing a component, it's usually
  39672. best not to call this directly, but to use the Component::findColour() method
  39673. instead. That will first check whether a suitable colour has been registered
  39674. directly with the component, and will fall-back on calling the component's
  39675. LookAndFeel's findColour() method if none is found.
  39676. @see setColour, Component::findColour, Component::setColour
  39677. */
  39678. const Colour findColour (const int colourId) const throw();
  39679. /** Registers a colour to be used for a particular purpose.
  39680. For more details, see the comments for findColour().
  39681. @see findColour, Component::findColour, Component::setColour
  39682. */
  39683. void setColour (const int colourId, const Colour& colour) throw();
  39684. /** Returns true if the specified colour ID has been explicitly set using the
  39685. setColour() method.
  39686. */
  39687. bool isColourSpecified (const int colourId) const throw();
  39688. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  39689. /** Allows you to change the default sans-serif font.
  39690. If you need to supply your own Typeface object for any of the default fonts, rather
  39691. than just supplying the name (e.g. if you want to use an embedded font), then
  39692. you should instead override getTypefaceForFont() to create and return the typeface.
  39693. */
  39694. void setDefaultSansSerifTypefaceName (const String& newName);
  39695. /** Draws the lozenge-shaped background for a standard button. */
  39696. virtual void drawButtonBackground (Graphics& g,
  39697. Button& button,
  39698. const Colour& backgroundColour,
  39699. bool isMouseOverButton,
  39700. bool isButtonDown);
  39701. /** Draws the text for a TextButton. */
  39702. virtual void drawButtonText (Graphics& g,
  39703. TextButton& button,
  39704. bool isMouseOverButton,
  39705. bool isButtonDown);
  39706. /** Draws the contents of a standard ToggleButton. */
  39707. virtual void drawToggleButton (Graphics& g,
  39708. ToggleButton& button,
  39709. bool isMouseOverButton,
  39710. bool isButtonDown);
  39711. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  39712. virtual void drawTickBox (Graphics& g,
  39713. Component& component,
  39714. int x, int y, int w, int h,
  39715. const bool ticked,
  39716. const bool isEnabled,
  39717. const bool isMouseOverButton,
  39718. const bool isButtonDown);
  39719. /** Draws the contents of a message box.
  39720. */
  39721. virtual void drawAlertBox (Graphics& g,
  39722. AlertWindow& alert,
  39723. const Rectangle& textArea,
  39724. TextLayout& textLayout);
  39725. virtual int getAlertBoxWindowFlags();
  39726. virtual int getAlertWindowButtonHeight();
  39727. virtual const Font getAlertWindowFont();
  39728. /** Draws a progress bar.
  39729. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  39730. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  39731. isn't known). It can use the current time as a basis for playing an animation.
  39732. (Used by progress bars in AlertWindow).
  39733. */
  39734. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39735. int width, int height,
  39736. double progress, const String& textToShow);
  39737. /** Draws one of the buttons on a scrollbar.
  39738. @param g the context to draw into
  39739. @param scrollbar the bar itself
  39740. @param width the width of the button
  39741. @param height the height of the button
  39742. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  39743. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39744. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  39745. @param isButtonDown whether the mouse button's held down
  39746. */
  39747. virtual void drawScrollbarButton (Graphics& g,
  39748. ScrollBar& scrollbar,
  39749. int width, int height,
  39750. int buttonDirection,
  39751. bool isScrollbarVertical,
  39752. bool isMouseOverButton,
  39753. bool isButtonDown);
  39754. /** Draws the thumb area of a scrollbar.
  39755. @param g the context to draw into
  39756. @param scrollbar the bar itself
  39757. @param x the x position of the left edge of the thumb area to draw in
  39758. @param y the y position of the top edge of the thumb area to draw in
  39759. @param width the width of the thumb area to draw in
  39760. @param height the height of the thumb area to draw in
  39761. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39762. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  39763. thumb, or its x position for horizontal bars
  39764. @param thumbSize for vertical bars, the height of the thumb, or its width for
  39765. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  39766. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  39767. currently dragging the thumb
  39768. @param isMouseDown whether the mouse is currently dragging the scrollbar
  39769. */
  39770. virtual void drawScrollbar (Graphics& g,
  39771. ScrollBar& scrollbar,
  39772. int x, int y,
  39773. int width, int height,
  39774. bool isScrollbarVertical,
  39775. int thumbStartPosition,
  39776. int thumbSize,
  39777. bool isMouseOver,
  39778. bool isMouseDown);
  39779. /** Returns the component effect to use for a scrollbar */
  39780. virtual ImageEffectFilter* getScrollbarEffect();
  39781. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  39782. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  39783. /** Returns the default thickness to use for a scrollbar. */
  39784. virtual int getDefaultScrollbarWidth();
  39785. /** Returns the length in pixels to use for a scrollbar button. */
  39786. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  39787. /** Returns a tick shape for use in yes/no boxes, etc. */
  39788. virtual const Path getTickShape (const float height);
  39789. /** Returns a cross shape for use in yes/no boxes, etc. */
  39790. virtual const Path getCrossShape (const float height);
  39791. /** Draws the + or - box in a treeview. */
  39792. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  39793. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  39794. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  39795. // these return an image from the ImageCache, so use ImageCache::release() to free it
  39796. virtual Image* getDefaultFolderImage();
  39797. virtual Image* getDefaultDocumentFileImage();
  39798. virtual void createFileChooserHeaderText (const String& title,
  39799. const String& instructions,
  39800. GlyphArrangement& destArrangement,
  39801. int width);
  39802. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  39803. const String& filename, Image* icon,
  39804. const String& fileSizeDescription,
  39805. const String& fileTimeDescription,
  39806. const bool isDirectory,
  39807. const bool isItemSelected,
  39808. const int itemIndex);
  39809. virtual Button* createFileBrowserGoUpButton();
  39810. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  39811. DirectoryContentsDisplayComponent* fileListComponent,
  39812. FilePreviewComponent* previewComp,
  39813. ComboBox* currentPathBox,
  39814. TextEditor* filenameBox,
  39815. Button* goUpButton);
  39816. virtual void drawBubble (Graphics& g,
  39817. float tipX, float tipY,
  39818. float boxX, float boxY, float boxW, float boxH);
  39819. /** Fills the background of a popup menu component. */
  39820. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39821. /** Draws one of the items in a popup menu. */
  39822. virtual void drawPopupMenuItem (Graphics& g,
  39823. int width, int height,
  39824. const bool isSeparator,
  39825. const bool isActive,
  39826. const bool isHighlighted,
  39827. const bool isTicked,
  39828. const bool hasSubMenu,
  39829. const String& text,
  39830. const String& shortcutKeyText,
  39831. Image* image,
  39832. const Colour* const textColour);
  39833. /** Returns the size and style of font to use in popup menus. */
  39834. virtual const Font getPopupMenuFont();
  39835. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  39836. int width, int height,
  39837. bool isScrollUpArrow);
  39838. /** Finds the best size for an item in a popup menu. */
  39839. virtual void getIdealPopupMenuItemSize (const String& text,
  39840. const bool isSeparator,
  39841. int standardMenuItemHeight,
  39842. int& idealWidth,
  39843. int& idealHeight);
  39844. virtual int getMenuWindowFlags();
  39845. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  39846. bool isMouseOverBar,
  39847. MenuBarComponent& menuBar);
  39848. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39849. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  39850. virtual void drawMenuBarItem (Graphics& g,
  39851. int width, int height,
  39852. int itemIndex,
  39853. const String& itemText,
  39854. bool isMouseOverItem,
  39855. bool isMenuOpen,
  39856. bool isMouseOverBar,
  39857. MenuBarComponent& menuBar);
  39858. virtual void drawComboBox (Graphics& g, int width, int height,
  39859. const bool isButtonDown,
  39860. int buttonX, int buttonY,
  39861. int buttonW, int buttonH,
  39862. ComboBox& box);
  39863. virtual const Font getComboBoxFont (ComboBox& box);
  39864. virtual Label* createComboBoxTextBox (ComboBox& box);
  39865. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  39866. virtual void drawLabel (Graphics& g, Label& label);
  39867. virtual void drawLinearSlider (Graphics& g,
  39868. int x, int y,
  39869. int width, int height,
  39870. float sliderPos,
  39871. float minSliderPos,
  39872. float maxSliderPos,
  39873. const Slider::SliderStyle style,
  39874. Slider& slider);
  39875. virtual void drawLinearSliderBackground (Graphics& g,
  39876. int x, int y,
  39877. int width, int height,
  39878. float sliderPos,
  39879. float minSliderPos,
  39880. float maxSliderPos,
  39881. const Slider::SliderStyle style,
  39882. Slider& slider);
  39883. virtual void drawLinearSliderThumb (Graphics& g,
  39884. int x, int y,
  39885. int width, int height,
  39886. float sliderPos,
  39887. float minSliderPos,
  39888. float maxSliderPos,
  39889. const Slider::SliderStyle style,
  39890. Slider& slider);
  39891. virtual int getSliderThumbRadius (Slider& slider);
  39892. virtual void drawRotarySlider (Graphics& g,
  39893. int x, int y,
  39894. int width, int height,
  39895. float sliderPosProportional,
  39896. const float rotaryStartAngle,
  39897. const float rotaryEndAngle,
  39898. Slider& slider);
  39899. virtual Button* createSliderButton (const bool isIncrement);
  39900. virtual Label* createSliderTextBox (Slider& slider);
  39901. virtual ImageEffectFilter* getSliderEffect();
  39902. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  39903. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  39904. virtual Button* createFilenameComponentBrowseButton (const String& text);
  39905. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  39906. ComboBox* filenameBox, Button* browseButton);
  39907. virtual void drawCornerResizer (Graphics& g,
  39908. int w, int h,
  39909. bool isMouseOver,
  39910. bool isMouseDragging);
  39911. virtual void drawResizableFrame (Graphics& g,
  39912. int w, int h,
  39913. const BorderSize& borders);
  39914. virtual void drawResizableWindowBorder (Graphics& g,
  39915. int w, int h,
  39916. const BorderSize& border,
  39917. ResizableWindow& window);
  39918. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  39919. Graphics& g, int w, int h,
  39920. int titleSpaceX, int titleSpaceW,
  39921. const Image* icon,
  39922. bool drawTitleTextOnLeft);
  39923. virtual Button* createDocumentWindowButton (int buttonType);
  39924. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  39925. int titleBarX, int titleBarY,
  39926. int titleBarW, int titleBarH,
  39927. Button* minimiseButton,
  39928. Button* maximiseButton,
  39929. Button* closeButton,
  39930. bool positionTitleBarButtonsOnLeft);
  39931. virtual int getDefaultMenuBarHeight();
  39932. virtual DropShadower* createDropShadowerForComponent (Component* component);
  39933. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  39934. int w, int h,
  39935. bool isVerticalBar,
  39936. bool isMouseOver,
  39937. bool isMouseDragging);
  39938. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  39939. const String& text,
  39940. const Justification& position,
  39941. GroupComponent& group);
  39942. virtual void createTabButtonShape (Path& p,
  39943. int width, int height,
  39944. int tabIndex,
  39945. const String& text,
  39946. Button& button,
  39947. TabbedButtonBar::Orientation orientation,
  39948. const bool isMouseOver,
  39949. const bool isMouseDown,
  39950. const bool isFrontTab);
  39951. virtual void fillTabButtonShape (Graphics& g,
  39952. const Path& path,
  39953. const Colour& preferredBackgroundColour,
  39954. int tabIndex,
  39955. const String& text,
  39956. Button& button,
  39957. TabbedButtonBar::Orientation orientation,
  39958. const bool isMouseOver,
  39959. const bool isMouseDown,
  39960. const bool isFrontTab);
  39961. virtual void drawTabButtonText (Graphics& g,
  39962. int x, int y, int w, int h,
  39963. const Colour& preferredBackgroundColour,
  39964. int tabIndex,
  39965. const String& text,
  39966. Button& button,
  39967. TabbedButtonBar::Orientation orientation,
  39968. const bool isMouseOver,
  39969. const bool isMouseDown,
  39970. const bool isFrontTab);
  39971. virtual int getTabButtonOverlap (int tabDepth);
  39972. virtual int getTabButtonSpaceAroundImage();
  39973. virtual int getTabButtonBestWidth (int tabIndex,
  39974. const String& text,
  39975. int tabDepth,
  39976. Button& button);
  39977. virtual void drawTabButton (Graphics& g,
  39978. int w, int h,
  39979. const Colour& preferredColour,
  39980. int tabIndex,
  39981. const String& text,
  39982. Button& button,
  39983. TabbedButtonBar::Orientation orientation,
  39984. const bool isMouseOver,
  39985. const bool isMouseDown,
  39986. const bool isFrontTab);
  39987. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  39988. int w, int h,
  39989. TabbedButtonBar& tabBar,
  39990. TabbedButtonBar::Orientation orientation);
  39991. virtual Button* createTabBarExtrasButton();
  39992. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  39993. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  39994. int width, int height,
  39995. bool isMouseOver, bool isMouseDown,
  39996. int columnFlags);
  39997. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  39998. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  39999. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40000. bool isMouseOver, bool isMouseDown,
  40001. ToolbarItemComponent& component);
  40002. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40003. const String& text, ToolbarItemComponent& component);
  40004. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40005. bool isOpen, int width, int height);
  40006. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40007. PropertyComponent& component);
  40008. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40009. PropertyComponent& component);
  40010. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  40011. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40012. /**
  40013. */
  40014. virtual void playAlertSound();
  40015. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40016. static void drawGlassSphere (Graphics& g,
  40017. const float x, const float y,
  40018. const float diameter,
  40019. const Colour& colour,
  40020. const float outlineThickness) throw();
  40021. static void drawGlassPointer (Graphics& g,
  40022. const float x, const float y,
  40023. const float diameter,
  40024. const Colour& colour, const float outlineThickness,
  40025. const int direction) throw();
  40026. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40027. static void drawGlassLozenge (Graphics& g,
  40028. const float x, const float y,
  40029. const float width, const float height,
  40030. const Colour& colour,
  40031. const float outlineThickness,
  40032. const float cornerSize,
  40033. const bool flatOnLeft, const bool flatOnRight,
  40034. const bool flatOnTop, const bool flatOnBottom) throw();
  40035. juce_UseDebuggingNewOperator
  40036. protected:
  40037. // xxx the following methods are only here to cause a compiler error, because they've been
  40038. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  40039. // error if you try to build a subclass with the old versions.
  40040. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  40041. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  40042. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  40043. virtual void getTabButtonBestWidth (int, const String&, int) {}
  40044. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  40045. private:
  40046. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40047. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40048. Array <int> colourIds;
  40049. Array <Colour> colours;
  40050. // default typeface names
  40051. String defaultSans, defaultSerif, defaultFixed;
  40052. void drawShinyButtonShape (Graphics& g,
  40053. float x, float y, float w, float h, float maxCornerSize,
  40054. const Colour& baseColour,
  40055. const float strokeWidth,
  40056. const bool flatOnLeft,
  40057. const bool flatOnRight,
  40058. const bool flatOnTop,
  40059. const bool flatOnBottom) throw();
  40060. LookAndFeel (const LookAndFeel&);
  40061. const LookAndFeel& operator= (const LookAndFeel&);
  40062. };
  40063. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40064. /********* End of inlined file: juce_LookAndFeel.h *********/
  40065. #endif
  40066. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40067. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40068. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40069. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40070. /**
  40071. The original Juce look-and-feel.
  40072. */
  40073. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40074. {
  40075. public:
  40076. /** Creates the default JUCE look and feel. */
  40077. OldSchoolLookAndFeel();
  40078. /** Destructor. */
  40079. virtual ~OldSchoolLookAndFeel();
  40080. /** Draws the lozenge-shaped background for a standard button. */
  40081. virtual void drawButtonBackground (Graphics& g,
  40082. Button& button,
  40083. const Colour& backgroundColour,
  40084. bool isMouseOverButton,
  40085. bool isButtonDown);
  40086. /** Draws the contents of a standard ToggleButton. */
  40087. virtual void drawToggleButton (Graphics& g,
  40088. ToggleButton& button,
  40089. bool isMouseOverButton,
  40090. bool isButtonDown);
  40091. virtual void drawTickBox (Graphics& g,
  40092. Component& component,
  40093. int x, int y, int w, int h,
  40094. const bool ticked,
  40095. const bool isEnabled,
  40096. const bool isMouseOverButton,
  40097. const bool isButtonDown);
  40098. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40099. int width, int height,
  40100. double progress, const String& textToShow);
  40101. virtual void drawScrollbarButton (Graphics& g,
  40102. ScrollBar& scrollbar,
  40103. int width, int height,
  40104. int buttonDirection,
  40105. bool isScrollbarVertical,
  40106. bool isMouseOverButton,
  40107. bool isButtonDown);
  40108. virtual void drawScrollbar (Graphics& g,
  40109. ScrollBar& scrollbar,
  40110. int x, int y,
  40111. int width, int height,
  40112. bool isScrollbarVertical,
  40113. int thumbStartPosition,
  40114. int thumbSize,
  40115. bool isMouseOver,
  40116. bool isMouseDown);
  40117. virtual ImageEffectFilter* getScrollbarEffect();
  40118. virtual void drawTextEditorOutline (Graphics& g,
  40119. int width, int height,
  40120. TextEditor& textEditor);
  40121. /** Fills the background of a popup menu component. */
  40122. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40123. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40124. bool isMouseOverBar,
  40125. MenuBarComponent& menuBar);
  40126. virtual void drawComboBox (Graphics& g, int width, int height,
  40127. const bool isButtonDown,
  40128. int buttonX, int buttonY,
  40129. int buttonW, int buttonH,
  40130. ComboBox& box);
  40131. virtual const Font getComboBoxFont (ComboBox& box);
  40132. virtual void drawLinearSlider (Graphics& g,
  40133. int x, int y,
  40134. int width, int height,
  40135. float sliderPos,
  40136. float minSliderPos,
  40137. float maxSliderPos,
  40138. const Slider::SliderStyle style,
  40139. Slider& slider);
  40140. virtual int getSliderThumbRadius (Slider& slider);
  40141. virtual Button* createSliderButton (const bool isIncrement);
  40142. virtual ImageEffectFilter* getSliderEffect();
  40143. virtual void drawCornerResizer (Graphics& g,
  40144. int w, int h,
  40145. bool isMouseOver,
  40146. bool isMouseDragging);
  40147. virtual Button* createDocumentWindowButton (int buttonType);
  40148. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40149. int titleBarX, int titleBarY,
  40150. int titleBarW, int titleBarH,
  40151. Button* minimiseButton,
  40152. Button* maximiseButton,
  40153. Button* closeButton,
  40154. bool positionTitleBarButtonsOnLeft);
  40155. juce_UseDebuggingNewOperator
  40156. private:
  40157. DropShadowEffect scrollbarShadow;
  40158. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40159. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40160. };
  40161. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40162. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40163. #endif
  40164. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40165. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  40166. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40167. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40168. /**
  40169. A class to take care of the logic involved with the loading/saving of some kind
  40170. of document.
  40171. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  40172. functions you need for documents that get saved to a file, so this class attempts
  40173. to abstract most of the boring stuff.
  40174. Your subclass should just implement all the pure virtual methods, and you can
  40175. then use the higher-level public methods to do the load/save dialogs, to warn the user
  40176. about overwriting files, etc.
  40177. The document object keeps track of whether it has changed since it was last saved or
  40178. loaded, so when you change something, call its changed() method. This will set a
  40179. flag so it knows it needs saving, and will also broadcast a change message using the
  40180. ChangeBroadcaster base class.
  40181. @see ChangeBroadcaster
  40182. */
  40183. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  40184. {
  40185. public:
  40186. /** Creates a FileBasedDocument.
  40187. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  40188. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  40189. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  40190. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  40191. */
  40192. FileBasedDocument (const String& fileExtension,
  40193. const String& fileWildCard,
  40194. const String& openFileDialogTitle,
  40195. const String& saveFileDialogTitle);
  40196. /** Destructor. */
  40197. virtual ~FileBasedDocument();
  40198. /** Returns true if the changed() method has been called since the file was
  40199. last saved or loaded.
  40200. @see resetChangedFlag, changed
  40201. */
  40202. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  40203. /** Called to indicate that the document has changed and needs saving.
  40204. This method will also trigger a change message to be sent out using the
  40205. ChangeBroadcaster base class.
  40206. After calling the method, the hasChangedSinceSaved() method will return true, until
  40207. it is reset either by saving to a file or using the resetChangedFlag() method.
  40208. @see hasChangedSinceSaved, resetChangedFlag
  40209. */
  40210. virtual void changed();
  40211. /** Sets the state of the 'changed' flag.
  40212. The 'changed' flag is set to true when the changed() method is called - use this method
  40213. to reset it or to set it without also broadcasting a change message.
  40214. @see changed, hasChangedSinceSaved
  40215. */
  40216. void setChangedFlag (const bool hasChanged);
  40217. /** Tries to open a file.
  40218. If the file opens correctly, the document's file (see the getFile() method) is set
  40219. to this new one; if it fails, the document's file is left unchanged, and optionally
  40220. a message box is shown telling the user there was an error.
  40221. @returns true if the new file loaded successfully
  40222. @see loadDocument, loadFromUserSpecifiedFile
  40223. */
  40224. bool loadFrom (const File& fileToLoadFrom,
  40225. const bool showMessageOnFailure);
  40226. /** Asks the user for a file and tries to load it.
  40227. This will pop up a dialog box using the title, file extension and
  40228. wildcard specified in the document's constructor, and asks the user
  40229. for a file. If they pick one, the loadFrom() method is used to
  40230. try to load it, optionally showing a message if it fails.
  40231. @returns true if a file was loaded; false if the user cancelled or if they
  40232. picked a file which failed to load correctly
  40233. @see loadFrom
  40234. */
  40235. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  40236. /** A set of possible outcomes of one of the save() methods
  40237. */
  40238. enum SaveResult
  40239. {
  40240. savedOk = 0, /**< indicates that a file was saved successfully. */
  40241. userCancelledSave, /**< indicates that the user aborted the save operation. */
  40242. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  40243. };
  40244. /** Tries to save the document to the last file it was saved or loaded from.
  40245. This will always try to write to the file, even if the document isn't flagged as
  40246. having changed.
  40247. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  40248. true, it will prompt the user to pick a file, as if
  40249. saveAsInteractive() was called.
  40250. @param showMessageOnFailure if true it will show a warning message when if the
  40251. save operation fails
  40252. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  40253. */
  40254. SaveResult save (const bool askUserForFileIfNotSpecified,
  40255. const bool showMessageOnFailure);
  40256. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  40257. it if they say yes.
  40258. If you've got a document open and want to close it (e.g. to quit the app), this is the
  40259. method to call.
  40260. If the document doesn't need saving it'll return the value savedOk so
  40261. you can go ahead and delete the document.
  40262. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  40263. return savedOk, so again, you can safely delete the document.
  40264. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  40265. close-document operation.
  40266. And if they click "save changes", it'll try to save and either return savedOk, or
  40267. failedToWriteToFile if there was a problem.
  40268. @see save, saveAs, saveAsInteractive
  40269. */
  40270. SaveResult saveIfNeededAndUserAgrees();
  40271. /** Tries to save the document to a specified file.
  40272. If this succeeds, it'll also change the document's internal file (as returned by
  40273. the getFile() method). If it fails, the file will be left unchanged.
  40274. @param newFile the file to try to write to
  40275. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  40276. the user first if they want to overwrite it
  40277. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  40278. use the saveAsInteractive() method to ask the user for a
  40279. filename
  40280. @param showMessageOnFailure if true and the write operation fails, it'll show
  40281. a message box to warn the user
  40282. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  40283. */
  40284. SaveResult saveAs (const File& newFile,
  40285. const bool warnAboutOverwritingExistingFiles,
  40286. const bool askUserForFileIfNotSpecified,
  40287. const bool showMessageOnFailure);
  40288. /** Prompts the user for a filename and tries to save to it.
  40289. This will pop up a dialog box using the title, file extension and
  40290. wildcard specified in the document's constructor, and asks the user
  40291. for a file. If they pick one, the saveAs() method is used to try to save
  40292. to this file.
  40293. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  40294. the user first if they want to overwrite it
  40295. @see saveIfNeededAndUserAgrees, save, saveAs
  40296. */
  40297. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  40298. /** Returns the file that this document was last successfully saved or loaded from.
  40299. When the document object is created, this will be set to File::nonexistent.
  40300. It is changed when one of the load or save methods is used, or when setFile()
  40301. is used to explicitly set it.
  40302. */
  40303. const File getFile() const throw() { return documentFile; }
  40304. /** Sets the file that this document thinks it was loaded from.
  40305. This won't actually load anything - it just changes the file stored internally.
  40306. @see getFile
  40307. */
  40308. void setFile (const File& newFile);
  40309. protected:
  40310. /** Overload this to return the title of the document.
  40311. This is used in message boxes, filenames and file choosers, so it should be
  40312. something sensible.
  40313. */
  40314. virtual const String getDocumentTitle() = 0;
  40315. /** This method should try to load your document from the given file.
  40316. If it fails, it should return an error message. If it succeeds, it should return
  40317. an empty string.
  40318. */
  40319. virtual const String loadDocument (const File& file) = 0;
  40320. /** This method should try to write your document to the given file.
  40321. If it fails, it should return an error message. If it succeeds, it should return
  40322. an empty string.
  40323. */
  40324. virtual const String saveDocument (const File& file) = 0;
  40325. /** This is used for dialog boxes to make them open at the last folder you
  40326. were using.
  40327. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  40328. the last document that was used - you might want to store this value
  40329. in a static variable, or even in your application's properties. It should
  40330. be a global setting rather than a property of this object.
  40331. This method works very well in conjunction with a RecentlyOpenedFilesList
  40332. object to manage your recent-files list.
  40333. As a default value, it's ok to return File::nonexistent, and the document
  40334. object will use a sensible one instead.
  40335. @see RecentlyOpenedFilesList
  40336. */
  40337. virtual const File getLastDocumentOpened() = 0;
  40338. /** This is used for dialog boxes to make them open at the last folder you
  40339. were using.
  40340. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  40341. the last document that was used - you might want to store this value
  40342. in a static variable, or even in your application's properties. It should
  40343. be a global setting rather than a property of this object.
  40344. This method works very well in conjunction with a RecentlyOpenedFilesList
  40345. object to manage your recent-files list.
  40346. @see RecentlyOpenedFilesList
  40347. */
  40348. virtual void setLastDocumentOpened (const File& file) = 0;
  40349. public:
  40350. juce_UseDebuggingNewOperator
  40351. private:
  40352. File documentFile;
  40353. bool changedSinceSave;
  40354. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  40355. FileBasedDocument (const FileBasedDocument&);
  40356. const FileBasedDocument& operator= (const FileBasedDocument&);
  40357. };
  40358. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40359. /********* End of inlined file: juce_FileBasedDocument.h *********/
  40360. #endif
  40361. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40362. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40363. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40364. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40365. /**
  40366. Manages a set of files for use as a list of recently-opened documents.
  40367. This is a handy class for holding your list of recently-opened documents, with
  40368. helpful methods for things like purging any non-existent files, automatically
  40369. adding them to a menu, and making persistence easy.
  40370. @see File, FileBasedDocument
  40371. */
  40372. class JUCE_API RecentlyOpenedFilesList
  40373. {
  40374. public:
  40375. /** Creates an empty list.
  40376. */
  40377. RecentlyOpenedFilesList();
  40378. /** Destructor. */
  40379. ~RecentlyOpenedFilesList();
  40380. /** Sets a limit for the number of files that will be stored in the list.
  40381. When addFile() is called, then if there is no more space in the list, the
  40382. least-recently added file will be dropped.
  40383. @see getMaxNumberOfItems
  40384. */
  40385. void setMaxNumberOfItems (const int newMaxNumber);
  40386. /** Returns the number of items that this list will store.
  40387. @see setMaxNumberOfItems
  40388. */
  40389. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  40390. /** Returns the number of files in the list.
  40391. The most recently added file is always at index 0.
  40392. */
  40393. int getNumFiles() const;
  40394. /** Returns one of the files in the list.
  40395. The most recently added file is always at index 0.
  40396. */
  40397. const File getFile (const int index) const;
  40398. /** Returns an array of all the absolute pathnames in the list.
  40399. */
  40400. const StringArray& getAllFilenames() const throw() { return files; }
  40401. /** Clears all the files from the list. */
  40402. void clear();
  40403. /** Adds a file to the list.
  40404. The file will be added at index 0. If this file is already in the list, it will
  40405. be moved up to index 0, but a file can only appear once in the list.
  40406. If the list already contains the maximum number of items that is permitted, the
  40407. least-recently added file will be dropped from the end.
  40408. */
  40409. void addFile (const File& file);
  40410. /** Checks each of the files in the list, removing any that don't exist.
  40411. You might want to call this after reloading a list of files, or before putting them
  40412. on a menu.
  40413. */
  40414. void removeNonExistentFiles();
  40415. /** Adds entries to a menu, representing each of the files in the list.
  40416. This is handy for creating an "open recent file..." menu in your app. The
  40417. menu items are numbered consecutively starting with the baseItemId value,
  40418. and can either be added as complete pathnames, or just the last part of the
  40419. filename.
  40420. If dontAddNonExistentFiles is true, then each file will be checked and only those
  40421. that exist will be added.
  40422. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  40423. pointers to file objects. Any files that appear in this list will not be added to the
  40424. menu - the reason for this is that you might have a number of files already open, so
  40425. might not want these to be shown in the menu.
  40426. It returns the number of items that were added.
  40427. */
  40428. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  40429. const int baseItemId,
  40430. const bool showFullPaths,
  40431. const bool dontAddNonExistentFiles,
  40432. const File** filesToAvoid = 0);
  40433. /** Returns a string that encapsulates all the files in the list.
  40434. The string that is returned can later be passed into restoreFromString() in
  40435. order to recreate the list. This is handy for persisting your list, e.g. in
  40436. a PropertiesFile object.
  40437. @see restoreFromString
  40438. */
  40439. const String toString() const;
  40440. /** Restores the list from a previously stringified version of the list.
  40441. Pass in a stringified version created with toString() in order to persist/restore
  40442. your list.
  40443. @see toString
  40444. */
  40445. void restoreFromString (const String& stringifiedVersion);
  40446. juce_UseDebuggingNewOperator
  40447. private:
  40448. StringArray files;
  40449. int maxNumberOfItems;
  40450. };
  40451. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  40452. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  40453. #endif
  40454. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40455. #endif
  40456. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  40457. #endif
  40458. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  40459. #endif
  40460. #endif
  40461. /********* End of inlined file: juce_app_includes.h *********/
  40462. #endif
  40463. #if JUCE_MSVC
  40464. #pragma warning (pop)
  40465. #pragma pack (pop)
  40466. #endif
  40467. #if JUCE_MAC
  40468. #pragma align=reset
  40469. #endif
  40470. END_JUCE_NAMESPACE
  40471. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  40472. #ifdef JUCE_NAMESPACE
  40473. // this will obviously save a lot of typing, but can be disabled by
  40474. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  40475. using namespace JUCE_NAMESPACE;
  40476. /* On the Mac, these symbols are defined in the Mac libraries, so
  40477. these macros make it easier to reference them without writing out
  40478. the namespace every time.
  40479. If you run into difficulties where these macros interfere with the contents
  40480. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  40481. the comments in that file for more information.
  40482. */
  40483. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  40484. #define Component JUCE_NAMESPACE::Component
  40485. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  40486. #define Point JUCE_NAMESPACE::Point
  40487. #define Button JUCE_NAMESPACE::Button
  40488. #endif
  40489. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  40490. it easier to use the juce version explicitly.
  40491. If you run into difficulties where this macro interferes with other 3rd party header
  40492. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  40493. file for more information.
  40494. */
  40495. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  40496. #define Rectangle JUCE_NAMESPACE::Rectangle
  40497. #endif
  40498. #endif
  40499. #endif
  40500. /* Easy autolinking to the right JUCE libraries under win32.
  40501. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  40502. including this header file.
  40503. */
  40504. #if JUCE_MSVC
  40505. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  40506. /** If you want your application to link to Juce as a DLL instead of
  40507. a static library (on win32), just define the JUCE_DLL macro before
  40508. including juce.h
  40509. */
  40510. #ifdef JUCE_DLL
  40511. #ifdef JUCE_DEBUG
  40512. #define AUTOLINKEDLIB "JUCE_debug.lib"
  40513. #else
  40514. #define AUTOLINKEDLIB "JUCE.lib"
  40515. #endif
  40516. #else
  40517. #ifdef JUCE_DEBUG
  40518. #ifdef _WIN64
  40519. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  40520. #else
  40521. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  40522. #endif
  40523. #else
  40524. #ifdef _WIN64
  40525. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  40526. #else
  40527. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  40528. #endif
  40529. #endif
  40530. #endif
  40531. #pragma comment(lib, AUTOLINKEDLIB)
  40532. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  40533. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  40534. #endif
  40535. // Auto-link the other win32 libs that are needed by library calls..
  40536. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  40537. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40538. // Auto-links to various win32 libs that are needed by library calls..
  40539. #pragma comment(lib, "kernel32.lib")
  40540. #pragma comment(lib, "user32.lib")
  40541. #pragma comment(lib, "shell32.lib")
  40542. #pragma comment(lib, "gdi32.lib")
  40543. #pragma comment(lib, "vfw32.lib")
  40544. #pragma comment(lib, "comdlg32.lib")
  40545. #pragma comment(lib, "winmm.lib")
  40546. #pragma comment(lib, "wininet.lib")
  40547. #pragma comment(lib, "ole32.lib")
  40548. #pragma comment(lib, "advapi32.lib")
  40549. #pragma comment(lib, "ws2_32.lib")
  40550. #pragma comment(lib, "comsupp.lib")
  40551. #if JUCE_OPENGL
  40552. #pragma comment(lib, "OpenGL32.Lib")
  40553. #pragma comment(lib, "GlU32.Lib")
  40554. #endif
  40555. #if JUCE_QUICKTIME
  40556. #pragma comment (lib, "QTMLClient.lib")
  40557. #endif
  40558. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  40559. #endif
  40560. #endif
  40561. #endif
  40562. /*
  40563. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  40564. AppSubClass is the name of a class derived from JUCEApplication.
  40565. See the JUCEApplication class documentation (juce_Application.h) for more details.
  40566. */
  40567. #if defined (JUCE_GCC) || defined (__MWERKS__)
  40568. #define START_JUCE_APPLICATION(AppClass) \
  40569. int main (int argc, char* argv[]) \
  40570. { \
  40571. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  40572. }
  40573. #elif JUCE_WIN32
  40574. #ifdef _CONSOLE
  40575. #define START_JUCE_APPLICATION(AppClass) \
  40576. int main (int, char* argv[]) \
  40577. { \
  40578. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40579. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40580. }
  40581. #elif ! defined (_AFXDLL)
  40582. #ifdef _WINDOWS_
  40583. #define START_JUCE_APPLICATION(AppClass) \
  40584. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  40585. { \
  40586. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40587. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40588. }
  40589. #else
  40590. #define START_JUCE_APPLICATION(AppClass) \
  40591. int __stdcall WinMain (int, int, const char*, int) \
  40592. { \
  40593. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  40594. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  40595. }
  40596. #endif
  40597. #endif
  40598. #endif
  40599. #endif // __JUCE_JUCEHEADER__
  40600. /********* End of inlined file: juce.h *********/
  40601. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__