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.

55170 lines
2.0MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. ==============================================================================
  20. This header contains the entire Juce source tree, and can be #included in
  21. all your source files.
  22. As well as including this in your files, you should also add juce_inline.cpp
  23. to your project (or juce_inline.mm on the Mac).
  24. ==============================================================================
  25. */
  26. #ifndef __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  27. #define __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__
  28. #define DONT_AUTOLINK_TO_JUCE_LIBRARY 1
  29. /********* Start of inlined file: juce.h *********/
  30. #ifndef __JUCE_JUCEHEADER__
  31. #define __JUCE_JUCEHEADER__
  32. /*
  33. This is the main JUCE header file that applications need to include.
  34. */
  35. // (this includes things that need defining outside of the JUCE namespace)
  36. /********* Start of inlined file: juce_StandardHeader.h *********/
  37. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  38. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  39. /** Current Juce version number.
  40. See also SystemStats::getJUCEVersion() for a string version.
  41. */
  42. #define JUCE_MAJOR_VERSION 1
  43. #define JUCE_MINOR_VERSION 50
  44. /** Current Juce version number.
  45. Bits 16 to 32 = major version.
  46. Bits 8 to 16 = minor version.
  47. Bits 0 to 8 = point release (not currently used).
  48. See also SystemStats::getJUCEVersion() for a string version.
  49. */
  50. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8))
  51. /********* Start of inlined file: juce_Config.h *********/
  52. #ifndef __JUCE_CONFIG_JUCEHEADER__
  53. #define __JUCE_CONFIG_JUCEHEADER__
  54. /*
  55. This file contains macros that enable/disable various JUCE features.
  56. */
  57. /** The name of the namespace that all Juce classes and functions will be
  58. put inside. If this is not defined, no namespace will be used.
  59. */
  60. #ifndef JUCE_NAMESPACE
  61. #define JUCE_NAMESPACE juce
  62. #endif
  63. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  64. but if you define this value, you can override this can force it to be true or
  65. false.
  66. */
  67. #ifndef JUCE_FORCE_DEBUG
  68. //#define JUCE_FORCE_DEBUG 1
  69. #endif
  70. /** If this flag is enabled, the the jassert and jassertfalse macros will
  71. always use Logger::writeToLog() to write a message when an assertion happens.
  72. Enabling it will also leave this turned on in release builds. When it's disabled,
  73. however, the jassert and jassertfalse macros will not be compiled in a
  74. release build.
  75. @see jassert, jassertfalse, Logger
  76. */
  77. #ifndef JUCE_LOG_ASSERTIONS
  78. // #define JUCE_LOG_ASSERTIONS 1
  79. #endif
  80. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  81. which the ASIOAudioIODevice class can't be built. See the comments in the
  82. ASIOAudioIODevice class's header file for more info about this.
  83. (This only affects a Win32 build)
  84. */
  85. #ifndef JUCE_ASIO
  86. #define JUCE_ASIO 1
  87. #endif
  88. /** Comment out this macro to disable the Windows WASAPI audio device type.
  89. */
  90. #ifndef JUCE_WASAPI
  91. // #define JUCE_WASAPI 1
  92. #endif
  93. /** Comment out this macro to disable the Windows WASAPI audio device type.
  94. */
  95. #ifndef JUCE_DIRECTSOUND
  96. #define JUCE_DIRECTSOUND 1
  97. #endif
  98. /** Comment out this macro to disable building of ALSA device support on Linux.
  99. */
  100. #ifndef JUCE_ALSA
  101. #define JUCE_ALSA 1
  102. #endif
  103. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  104. have the SDK installed.
  105. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  106. classes will be unavailable.
  107. On Windows, if you enable this, you'll need to have the QuickTime SDK
  108. installed, and its header files will need to be on your include path.
  109. */
  110. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  111. #define JUCE_QUICKTIME 1
  112. #endif
  113. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  114. have the appropriate headers and libraries available. If it's not enabled, the
  115. OpenGLComponent class will be unavailable.
  116. */
  117. #ifndef JUCE_OPENGL
  118. #define JUCE_OPENGL 1
  119. #endif
  120. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  121. If you're not going to need either of these formats, turn off the flags to
  122. avoid bloating your codebase with them.
  123. */
  124. #ifndef JUCE_USE_FLAC
  125. #define JUCE_USE_FLAC 1
  126. #endif
  127. #ifndef JUCE_USE_OGGVORBIS
  128. #define JUCE_USE_OGGVORBIS 1
  129. #endif
  130. /** This flag lets you enable support for CD-burning. You might want to disable
  131. it to build without the MS SDK under windows.
  132. */
  133. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  134. #define JUCE_USE_CDBURNER 1
  135. #endif
  136. /** Enabling this provides support for cameras, using the CameraDevice class
  137. */
  138. #if JUCE_QUICKTIME && ! defined (JUCE_USE_CAMERA)
  139. // #define JUCE_USE_CAMERA 1
  140. #endif
  141. /** Enabling this macro means that all regions that get repainted will have a coloured
  142. line drawn around them.
  143. This is handy if you're trying to optimise drawing, because it lets you easily see
  144. when anything is being repainted unnecessarily.
  145. */
  146. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  147. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  148. #endif
  149. /** Enable this under Linux to use Xinerama for multi-monitor support.
  150. */
  151. #ifndef JUCE_USE_XINERAMA
  152. #define JUCE_USE_XINERAMA 1
  153. #endif
  154. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  155. */
  156. #ifndef JUCE_USE_XSHM
  157. #define JUCE_USE_XSHM 1
  158. #endif
  159. /** Enabling this builds support for VST audio plugins.
  160. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  161. */
  162. #ifndef JUCE_PLUGINHOST_VST
  163. // #define JUCE_PLUGINHOST_VST 1
  164. #endif
  165. /** Enabling this builds support for AudioUnit audio plugins.
  166. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  167. */
  168. #ifndef JUCE_PLUGINHOST_AU
  169. // #define JUCE_PLUGINHOST_AU 1
  170. #endif
  171. /** Enabling this will avoid including any UI code in the build. This is handy for
  172. writing command-line utilities, e.g. on linux boxes which don't have some
  173. of the UI libraries installed.
  174. */
  175. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  176. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  177. #endif
  178. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  179. */
  180. #ifndef JUCE_WEB_BROWSER
  181. #define JUCE_WEB_BROWSER 1
  182. #endif
  183. /** Setting this allows the build to use old Carbon libraries that will be
  184. deprecated in newer versions of OSX. This is handy for some backwards-compatibility
  185. reasons.
  186. */
  187. #ifndef JUCE_SUPPORT_CARBON
  188. #define JUCE_SUPPORT_CARBON 1
  189. #endif
  190. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  191. codebase - you might need to use this if you're linking to some of these libraries
  192. yourself.
  193. */
  194. #ifndef JUCE_INCLUDE_ZLIB_CODE
  195. #define JUCE_INCLUDE_ZLIB_CODE 1
  196. #endif
  197. #ifndef JUCE_INCLUDE_FLAC_CODE
  198. #define JUCE_INCLUDE_FLAC_CODE 1
  199. #endif
  200. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  201. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  202. #endif
  203. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  204. #define JUCE_INCLUDE_PNGLIB_CODE 1
  205. #endif
  206. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  207. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  208. #endif
  209. /** Enable this to add extra memory-leak info to the new and delete operators.
  210. (Currently, this only affects Windows builds in debug mode).
  211. */
  212. #ifndef JUCE_CHECK_MEMORY_LEAKS
  213. #define JUCE_CHECK_MEMORY_LEAKS 1
  214. #endif
  215. /** Enable this to turn on juce's internal catching of exceptions.
  216. Turning it off will avoid any exception catching. With it on, all exceptions
  217. are passed to the JUCEApplication::unhandledException() callback for logging.
  218. */
  219. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  220. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  221. #endif
  222. /** If this macro is set, the Juce String class will use unicode as its
  223. internal representation. If it isn't set, it'll use ANSI.
  224. */
  225. #ifndef JUCE_STRINGS_ARE_UNICODE
  226. #define JUCE_STRINGS_ARE_UNICODE 1
  227. #endif
  228. #endif
  229. /********* End of inlined file: juce_Config.h *********/
  230. #ifdef JUCE_NAMESPACE
  231. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  232. #define END_JUCE_NAMESPACE }
  233. #else
  234. #define BEGIN_JUCE_NAMESPACE
  235. #define END_JUCE_NAMESPACE
  236. #endif
  237. // This sets up the JUCE_WIN32, JUCE_MAC, or JUCE_LINUX macros
  238. /********* Start of inlined file: juce_PlatformDefs.h *********/
  239. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  240. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  241. /* This file figures out which platform is being built, and defines some macros
  242. that the rest of the code can use for OS-specific compilation.
  243. Macros that will be set here are:
  244. - One of JUCE_WIN32, JUCE_MAC or JUCE_LINUX.
  245. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  246. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  247. - Either JUCE_INTEL or JUCE_PPC
  248. - Either JUCE_GCC or JUCE_MSVC
  249. It also includes a set of macros for debug console output and assertions.
  250. */
  251. #if (defined (_WIN32) || defined (_WIN64))
  252. #define JUCE_WIN32 1
  253. #else
  254. #if defined (LINUX) || defined (__linux__)
  255. #define JUCE_LINUX 1
  256. #else
  257. #define JUCE_MAC 1
  258. #endif
  259. #endif
  260. #if JUCE_WIN32
  261. #ifdef _MSC_VER
  262. #ifdef _WIN64
  263. #define JUCE_64BIT 1
  264. #else
  265. #define JUCE_32BIT 1
  266. #endif
  267. #endif
  268. #ifdef _DEBUG
  269. #define JUCE_DEBUG 1
  270. #endif
  271. /** If defined, this indicates that the processor is little-endian. */
  272. #define JUCE_LITTLE_ENDIAN 1
  273. #define JUCE_INTEL 1
  274. #endif
  275. #if JUCE_MAC
  276. #include <CoreFoundation/CoreFoundation.h>
  277. #ifndef NDEBUG
  278. #define JUCE_DEBUG 1
  279. #endif
  280. #ifdef __LITTLE_ENDIAN__
  281. #define JUCE_LITTLE_ENDIAN 1
  282. #else
  283. #define JUCE_BIG_ENDIAN 1
  284. #endif
  285. #if defined (__ppc__) || defined (__ppc64__)
  286. #define JUCE_PPC 1
  287. #else
  288. #define JUCE_INTEL 1
  289. #endif
  290. #ifdef __LP64__
  291. #define JUCE_64BIT 1
  292. #else
  293. #define JUCE_32BIT 1
  294. #endif
  295. #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
  296. #error "Building for OSX 10.2 is no longer supported!"
  297. #endif
  298. #if (! defined (MAC_OS_X_VERSION_10_4)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
  299. #define MACOS_10_3_OR_EARLIER 1
  300. #endif
  301. #if (! defined (MAC_OS_X_VERSION_10_5)) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
  302. #define MACOS_10_4_OR_EARLIER 1
  303. #endif
  304. #endif
  305. #if JUCE_LINUX
  306. #ifdef _DEBUG
  307. #define JUCE_DEBUG 1
  308. #endif
  309. // Allow override for big-endian Linux platforms
  310. #ifndef JUCE_BIG_ENDIAN
  311. #define JUCE_LITTLE_ENDIAN 1
  312. #endif
  313. #if defined (__LP64__) || defined (_LP64)
  314. #define JUCE_64BIT 1
  315. #else
  316. #define JUCE_32BIT 1
  317. #endif
  318. #define JUCE_INTEL 1
  319. #endif
  320. #ifdef JUCE_FORCE_DEBUG
  321. #undef JUCE_DEBUG
  322. #if JUCE_FORCE_DEBUG
  323. #define JUCE_DEBUG 1
  324. #endif
  325. #endif
  326. // Compiler type macros.
  327. #ifdef __GNUC__
  328. #define JUCE_GCC 1
  329. #elif defined (_MSC_VER)
  330. #define JUCE_MSVC 1
  331. #if _MSC_VER >= 1400
  332. #define JUCE_USE_INTRINSICS 1
  333. #endif
  334. #else
  335. #error unknown compiler
  336. #endif
  337. /** This macro defines the C calling convention used as the standard for Juce calls. */
  338. #if JUCE_MSVC
  339. #define JUCE_CALLTYPE __stdcall
  340. #else
  341. #define JUCE_CALLTYPE
  342. #endif
  343. // Debugging and assertion macros
  344. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  345. #if JUCE_LOG_ASSERTIONS
  346. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  347. #elif defined (JUCE_DEBUG)
  348. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  349. #else
  350. #define juce_LogCurrentAssertion
  351. #endif
  352. #ifdef JUCE_DEBUG
  353. // If debugging is enabled..
  354. /** Writes a string to the standard error stream.
  355. This is only compiled in a debug build.
  356. @see Logger::outputDebugString
  357. */
  358. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  359. /** Printf's a string to the standard error stream.
  360. This is only compiled in a debug build.
  361. @see Logger::outputDebugString
  362. */
  363. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  364. // Assertions..
  365. #if JUCE_WIN32 || DOXYGEN
  366. #if JUCE_USE_INTRINSICS
  367. #pragma intrinsic (__debugbreak)
  368. /** This will try to break the debugger if one is currently hosting this app.
  369. @see jassert()
  370. */
  371. #define juce_breakDebugger __debugbreak();
  372. #elif JUCE_GCC
  373. /** This will try to break the debugger if one is currently hosting this app.
  374. @see jassert()
  375. */
  376. #define juce_breakDebugger asm("int $3");
  377. #else
  378. /** This will try to break the debugger if one is currently hosting this app.
  379. @see jassert()
  380. */
  381. #define juce_breakDebugger { __asm int 3 }
  382. #endif
  383. #elif JUCE_MAC
  384. #define juce_breakDebugger Debugger();
  385. #elif JUCE_LINUX
  386. #define juce_breakDebugger kill (0, SIGTRAP);
  387. #endif
  388. /** This will always cause an assertion failure.
  389. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  390. in juce_Config.h).
  391. @see jassert()
  392. */
  393. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  394. /** Platform-independent assertion macro.
  395. This gets optimised out when not being built with debugging turned on.
  396. Be careful not to call any functions within its arguments that are vital to
  397. the behaviour of the program, because these won't get called in the release
  398. build.
  399. @see jassertfalse
  400. */
  401. #define jassert(expression) { if (! (expression)) jassertfalse }
  402. #else
  403. // If debugging is disabled, these dummy debug and assertion macros are used..
  404. #define DBG(dbgtext)
  405. #define DBG_PRINTF(dbgprintf)
  406. #define jassertfalse { juce_LogCurrentAssertion }
  407. #if JUCE_LOG_ASSERTIONS
  408. #define jassert(expression) { if (! (expression)) jassertfalse }
  409. #else
  410. #define jassert(a) { }
  411. #endif
  412. #endif
  413. #ifndef DOXYGEN
  414. template <bool b> struct JuceStaticAssert;
  415. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  416. #endif
  417. /** A compile-time assertion macro.
  418. If the expression parameter is false, the macro will cause a compile error.
  419. */
  420. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  421. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  422. #define JUCE_TRY try
  423. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  424. object so they can be logged by the application if it wants to.
  425. */
  426. #define JUCE_CATCH_EXCEPTION \
  427. catch (const std::exception& e) \
  428. { \
  429. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  430. } \
  431. catch (...) \
  432. { \
  433. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  434. }
  435. #define JUCE_CATCH_ALL catch (...) {}
  436. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  437. #else
  438. #define JUCE_TRY
  439. #define JUCE_CATCH_EXCEPTION
  440. #define JUCE_CATCH_ALL
  441. #define JUCE_CATCH_ALL_ASSERT
  442. #endif
  443. // Macros for inlining.
  444. #if JUCE_MSVC
  445. /** A platform-independent way of forcing an inline function.
  446. Use the syntax: @code
  447. forcedinline void myfunction (int x)
  448. @endcode
  449. */
  450. #ifdef JUCE_DEBUG
  451. #define forcedinline __forceinline
  452. #else
  453. #define forcedinline inline
  454. #endif
  455. /** A platform-independent way of stopping the compiler inlining a function.
  456. Use the syntax: @code
  457. juce_noinline void myfunction (int x)
  458. @endcode
  459. */
  460. #define juce_noinline
  461. #else
  462. /** A platform-independent way of forcing an inline function.
  463. Use the syntax: @code
  464. forcedinline void myfunction (int x)
  465. @endcode
  466. */
  467. #ifndef JUCE_DEBUG
  468. #define forcedinline inline __attribute__((always_inline))
  469. #else
  470. #define forcedinline inline
  471. #endif
  472. /** A platform-independent way of stopping the compiler inlining a function.
  473. Use the syntax: @code
  474. juce_noinline void myfunction (int x)
  475. @endcode
  476. */
  477. #define juce_noinline __attribute__((noinline))
  478. #endif
  479. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  480. /********* End of inlined file: juce_PlatformDefs.h *********/
  481. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  482. #if JUCE_MSVC
  483. #pragma warning (push)
  484. #pragma warning (disable: 4514 4245 4100)
  485. #endif
  486. #include <cstdlib>
  487. #include <cstdarg>
  488. #include <climits>
  489. #include <cmath>
  490. #include <cwchar>
  491. #include <stdexcept>
  492. #include <typeinfo>
  493. #include <cstring>
  494. #include <cstdio>
  495. #if JUCE_USE_INTRINSICS
  496. #include <intrin.h>
  497. #endif
  498. #if JUCE_MAC
  499. #if MACOS_10_3_OR_EARLIER
  500. #include <CoreServices/CoreServices.h>
  501. #else
  502. #include <libkern/OSAtomic.h>
  503. #endif
  504. #endif
  505. #if JUCE_LINUX
  506. #include <signal.h>
  507. #endif
  508. #if JUCE_MSVC && JUCE_DEBUG
  509. #include <crtdbg.h>
  510. #endif
  511. #if JUCE_MSVC
  512. #pragma warning (pop)
  513. #endif
  514. // DLL building settings on Win32
  515. #if JUCE_MSVC
  516. #ifdef JUCE_DLL_BUILD
  517. #define JUCE_API __declspec (dllexport)
  518. #pragma warning (disable: 4251)
  519. #elif defined (JUCE_DLL)
  520. #define JUCE_API __declspec (dllimport)
  521. #pragma warning (disable: 4251)
  522. #endif
  523. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  524. #ifdef JUCE_DLL_BUILD
  525. #define JUCE_API __attribute__ ((visibility("default")))
  526. #endif
  527. #endif
  528. #ifndef JUCE_API
  529. /** This macro is added to all juce public class declarations. */
  530. #define JUCE_API
  531. #endif
  532. /** This macro is added to all juce public function declarations. */
  533. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  534. // Now include some basics that are needed by most of the Juce classes...
  535. BEGIN_JUCE_NAMESPACE
  536. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  537. #if JUCE_LOG_ASSERTIONS
  538. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  539. #endif
  540. /********* Start of inlined file: juce_Memory.h *********/
  541. #ifndef __JUCE_MEMORY_JUCEHEADER__
  542. #define __JUCE_MEMORY_JUCEHEADER__
  543. /*
  544. This file defines the various juce_malloc(), juce_free() macros that should be used in
  545. preference to the standard calls.
  546. */
  547. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  548. #ifndef JUCE_DLL
  549. // Win32 debug non-DLL versions..
  550. /** This should be used instead of calling malloc directly. */
  551. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  552. /** This should be used instead of calling calloc directly. */
  553. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  554. /** This should be used instead of calling realloc directly. */
  555. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  556. /** This should be used instead of calling free directly. */
  557. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  558. #else
  559. // Win32 debug DLL versions..
  560. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  561. // way all juce calls in the DLL and in the host API will all use the same allocator.
  562. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  563. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  564. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  565. extern JUCE_API void juce_DebugFree (void* const block);
  566. /** This should be used instead of calling malloc directly. */
  567. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  568. /** This should be used instead of calling calloc directly. */
  569. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  570. /** This should be used instead of calling realloc directly. */
  571. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  572. /** This should be used instead of calling free directly. */
  573. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  574. #endif
  575. #if ! defined (_AFXDLL)
  576. /** This macro can be added to classes to add extra debugging information to the memory
  577. allocated for them, so you can see the type of objects involved when there's a dump
  578. of leaked objects at program shutdown. (Only works on win32 at the moment).
  579. */
  580. #define juce_UseDebuggingNewOperator \
  581. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  582. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  583. static void operator delete (void* p) { juce_free (p); }
  584. #endif
  585. #elif defined (JUCE_DLL)
  586. // Win32 DLL (release) versions..
  587. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  588. // way all juce calls in the DLL and in the host API will all use the same allocator.
  589. extern JUCE_API void* juce_Malloc (const int size);
  590. extern JUCE_API void* juce_Calloc (const int size);
  591. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  592. extern JUCE_API void juce_Free (void* const block);
  593. /** This should be used instead of calling malloc directly. */
  594. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  595. /** This should be used instead of calling calloc directly. */
  596. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  597. /** This should be used instead of calling realloc directly. */
  598. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  599. /** This should be used instead of calling free directly. */
  600. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  601. #define juce_UseDebuggingNewOperator \
  602. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  603. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  604. static void operator delete (void* p) { juce_free (p); }
  605. #else
  606. // Mac, Linux and Win32 (release) versions..
  607. /** This should be used instead of calling malloc directly. */
  608. #define juce_malloc(numBytes) malloc (numBytes)
  609. /** This should be used instead of calling calloc directly. */
  610. #define juce_calloc(numBytes) calloc (1, numBytes)
  611. /** This should be used instead of calling realloc directly. */
  612. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  613. /** This should be used instead of calling free directly. */
  614. #define juce_free(location) free (location)
  615. #endif
  616. /** This macro can be added to classes to add extra debugging information to the memory
  617. allocated for them, so you can see the type of objects involved when there's a dump
  618. of leaked objects at program shutdown. (Only works on win32 at the moment).
  619. Note that if you create a class that inherits from a class that uses this macro,
  620. your class must also use the macro, otherwise you'll probably get compile errors
  621. because of ambiguous new operators.
  622. Most of the JUCE classes use it, so see these for examples of where it should go.
  623. */
  624. #ifndef juce_UseDebuggingNewOperator
  625. #define juce_UseDebuggingNewOperator
  626. #endif
  627. #if JUCE_MSVC
  628. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  629. E.g.
  630. @code
  631. juce_ThreadLocal int myVariable;
  632. @endcode
  633. */
  634. #define juce_ThreadLocal __declspec(thread)
  635. #else
  636. #define juce_ThreadLocal __thread
  637. #endif
  638. /** Clears a block of memory. */
  639. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  640. /** Clears a reference to a local structure. */
  641. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  642. /** A handy macro that calls delete on a pointer if it's non-zero, and
  643. then sets the pointer to null.
  644. */
  645. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  646. #endif // __JUCE_MEMORY_JUCEHEADER__
  647. /********* End of inlined file: juce_Memory.h *********/
  648. /********* Start of inlined file: juce_MathsFunctions.h *********/
  649. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  650. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  651. /*
  652. This file sets up some handy mathematical typdefs and functions.
  653. */
  654. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  655. /** A platform-independent 8-bit signed integer type. */
  656. typedef signed char int8;
  657. /** A platform-independent 8-bit unsigned integer type. */
  658. typedef unsigned char uint8;
  659. /** A platform-independent 16-bit signed integer type. */
  660. typedef signed short int16;
  661. /** A platform-independent 16-bit unsigned integer type. */
  662. typedef unsigned short uint16;
  663. /** A platform-independent 32-bit signed integer type. */
  664. typedef signed int int32;
  665. /** A platform-independent 32-bit unsigned integer type. */
  666. typedef unsigned int uint32;
  667. #if JUCE_MSVC
  668. /** A platform-independent 64-bit integer type. */
  669. typedef __int64 int64;
  670. /** A platform-independent 64-bit unsigned integer type. */
  671. typedef unsigned __int64 uint64;
  672. /** A platform-independent macro for writing 64-bit literals, needed because
  673. different compilers have different syntaxes for this.
  674. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  675. GCC, or 0x1000000000 for MSVC.
  676. */
  677. #define literal64bit(longLiteral) ((__int64) longLiteral)
  678. #else
  679. /** A platform-independent 64-bit integer type. */
  680. typedef long long int64;
  681. /** A platform-independent 64-bit unsigned integer type. */
  682. typedef unsigned long long uint64;
  683. /** A platform-independent macro for writing 64-bit literals, needed because
  684. different compilers have different syntaxes for this.
  685. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  686. GCC, or 0x1000000000 for MSVC.
  687. */
  688. #define literal64bit(longLiteral) (longLiteral##LL)
  689. #endif
  690. #if JUCE_64BIT
  691. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  692. typedef int64 pointer_sized_int;
  693. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  694. typedef uint64 pointer_sized_uint;
  695. #elif _MSC_VER >= 1300
  696. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  697. typedef _W64 int pointer_sized_int;
  698. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  699. typedef _W64 unsigned int pointer_sized_uint;
  700. #else
  701. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  702. typedef int pointer_sized_int;
  703. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  704. typedef unsigned int pointer_sized_uint;
  705. #endif
  706. /** A platform-independent unicode character type. */
  707. typedef wchar_t juce_wchar;
  708. // Some indispensible min/max functions
  709. /** Returns the larger of two values. */
  710. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  711. /** Returns the larger of two values. */
  712. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  713. /** Returns the larger of two values. */
  714. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  715. /** Returns the larger of two values. */
  716. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  717. /** Returns the larger of three values. */
  718. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  719. /** Returns the larger of three values. */
  720. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  721. /** Returns the larger of three values. */
  722. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  723. /** Returns the larger of three values. */
  724. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  725. /** Returns the larger of four values. */
  726. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  727. /** Returns the larger of four values. */
  728. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  729. /** Returns the larger of four values. */
  730. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  731. /** Returns the larger of four values. */
  732. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  733. /** Returns the smaller of two values. */
  734. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  735. /** Returns the smaller of two values. */
  736. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  737. /** Returns the smaller of two values. */
  738. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  739. /** Returns the smaller of two values. */
  740. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  741. /** Returns the smaller of three values. */
  742. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  743. /** Returns the smaller of three values. */
  744. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  745. /** Returns the smaller of three values. */
  746. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  747. /** Returns the smaller of three values. */
  748. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  749. /** Returns the smaller of four values. */
  750. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  751. /** Returns the smaller of four values. */
  752. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  753. /** Returns the smaller of four values. */
  754. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  755. /** Returns the smaller of four values. */
  756. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  757. /** Constrains a value to keep it within a given range.
  758. This will check that the specified value lies between the lower and upper bounds
  759. specified, and if not, will return the nearest value that would be in-range. Effectively,
  760. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  761. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  762. the results will be unpredictable.
  763. @param lowerLimit the minimum value to return
  764. @param upperLimit the maximum value to return
  765. @param valueToConstrain the value to try to return
  766. @returns the closest value to valueToConstrain which lies between lowerLimit
  767. and upperLimit (inclusive)
  768. @see jlimit0To, jmin, jmax
  769. */
  770. template <class Type>
  771. inline Type jlimit (const Type lowerLimit,
  772. const Type upperLimit,
  773. const Type valueToConstrain) throw()
  774. {
  775. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  776. return (valueToConstrain < lowerLimit) ? lowerLimit
  777. : ((valueToConstrain > upperLimit) ? upperLimit
  778. : valueToConstrain);
  779. }
  780. /** Handy function to swap two values over.
  781. */
  782. template <class Type>
  783. inline void swapVariables (Type& variable1, Type& variable2) throw()
  784. {
  785. const Type tempVal = variable1;
  786. variable1 = variable2;
  787. variable2 = tempVal;
  788. }
  789. /** Handy macro for getting the number of elements in a simple const C array.
  790. E.g.
  791. @code
  792. static int myArray[] = { 1, 2, 3 };
  793. int numElements = numElementsInArray (myArray) // returns 3
  794. @endcode
  795. */
  796. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  797. // Some useful maths functions that aren't always present with all compilers and build settings.
  798. #if JUCE_WIN32 || defined (DOXYGEN)
  799. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  800. versions of these functions of various platforms and compilers. */
  801. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  802. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  803. versions of these functions of various platforms and compilers. */
  804. forcedinline float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  805. #else
  806. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  807. versions of these functions of various platforms and compilers. */
  808. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  809. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  810. versions of these functions of various platforms and compilers. */
  811. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  812. #endif
  813. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  814. /** A predefined value for Pi, at double-precision.
  815. @see float_Pi
  816. */
  817. const double double_Pi = 3.1415926535897932384626433832795;
  818. /** A predefined value for Pi, at sngle-precision.
  819. @see double_Pi
  820. */
  821. const float float_Pi = 3.14159265358979323846f;
  822. /** The isfinite() method seems to vary greatly between platforms, so this is a
  823. platform-independent macro for it.
  824. */
  825. #if JUCE_LINUX
  826. #define juce_isfinite(v) std::isfinite(v)
  827. #elif JUCE_MAC
  828. #if MACOS_10_3_OR_EARLIER
  829. #ifdef isfinite
  830. #define juce_isfinite(v) isfinite(v)
  831. #else
  832. // no idea why the isfinite macro is sometimes impossible to include, so just copy the built-in one..
  833. static __inline__ int juce_isfinite (double __x) { return __x == __x && __builtin_fabs (__x) != __builtin_inf(); }
  834. #endif
  835. #else
  836. #define juce_isfinite(v) std::isfinite(v)
  837. #endif
  838. #elif JUCE_WIN32 && ! defined (isfinite)
  839. #define juce_isfinite(v) _finite(v)
  840. #else
  841. #define juce_isfinite(v) isfinite(v)
  842. #endif
  843. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  844. /********* End of inlined file: juce_MathsFunctions.h *********/
  845. /********* Start of inlined file: juce_DataConversions.h *********/
  846. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  847. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  848. #if JUCE_USE_INTRINSICS
  849. #pragma intrinsic (_byteswap_ulong)
  850. #endif
  851. // Endianness conversions..
  852. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  853. forcedinline uint32 swapByteOrder (uint32 n) throw()
  854. {
  855. #if JUCE_MAC
  856. // Mac version
  857. return CFSwapInt32 (n);
  858. #elif JUCE_GCC
  859. // Inpenetrable GCC version..
  860. asm("bswap %%eax" : "=a"(n) : "a"(n));
  861. return n;
  862. #elif JUCE_USE_INTRINSICS
  863. // Win32 intrinsics version..
  864. return _byteswap_ulong (n);
  865. #else
  866. // Win32 version..
  867. __asm {
  868. mov eax, n
  869. bswap eax
  870. mov n, eax
  871. }
  872. return n;
  873. #endif
  874. }
  875. /** Swaps the byte-order of a 16-bit short. */
  876. inline uint16 swapByteOrder (const uint16 n) throw()
  877. {
  878. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  879. // Win32 intrinsics version..
  880. return (uint16) _byteswap_ushort (n);
  881. #else
  882. return (uint16) ((n << 8) | (n >> 8));
  883. #endif
  884. }
  885. inline uint64 swapByteOrder (const uint64 value) throw()
  886. {
  887. #if JUCE_MAC
  888. return CFSwapInt64 (value);
  889. #elif JUCE_USE_INTRINSICS
  890. return _byteswap_uint64 (value);
  891. #else
  892. return (((int64) swapByteOrder ((uint32) value)) << 32)
  893. | swapByteOrder ((uint32) (value >> 32));
  894. #endif
  895. }
  896. #if JUCE_LITTLE_ENDIAN
  897. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  898. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  899. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  900. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  901. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  902. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  903. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  904. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  905. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  906. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  907. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  908. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  909. /** Turns 4 bytes into a little-endian integer. */
  910. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  911. /** Turns 2 bytes into a little-endian integer. */
  912. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  913. /** Turns 4 bytes into a big-endian integer. */
  914. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  915. /** Turns 2 bytes into a big-endian integer. */
  916. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  917. #else
  918. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  919. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  920. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  921. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  922. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  923. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  924. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  925. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  926. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  927. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  928. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  929. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  930. /** Turns 4 bytes into a little-endian integer. */
  931. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  932. /** Turns 2 bytes into a little-endian integer. */
  933. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  934. /** Turns 4 bytes into a big-endian integer. */
  935. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  936. /** Turns 2 bytes into a big-endian integer. */
  937. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  938. #endif
  939. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  940. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  941. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  942. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  943. /** Copies a 24-bit number to 3 little-endian bytes. */
  944. 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); }
  945. /** Copies a 24-bit number to 3 big-endian bytes. */
  946. 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); }
  947. /** Fast floating-point-to-integer conversion.
  948. This is faster than using the normal c++ cast to convert a double to an int, and
  949. it will round the value to the nearest integer, rather than rounding it down
  950. like the normal cast does.
  951. Note that this routine gets its speed at the expense of some accuracy, and when
  952. rounding values whose floating point component is exactly 0.5, odd numbers and
  953. even numbers will be rounded up or down differently. For a more accurate conversion,
  954. see roundDoubleToIntAccurate().
  955. */
  956. inline int roundDoubleToInt (const double value) throw()
  957. {
  958. union { int asInt[2]; double asDouble; } n;
  959. n.asDouble = value + 6755399441055744.0;
  960. #if JUCE_BIG_ENDIAN
  961. return n.asInt [1];
  962. #else
  963. return n.asInt [0];
  964. #endif
  965. }
  966. /** Fast floating-point-to-integer conversion.
  967. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  968. fine for values above zero, but negative numbers are rounded the wrong way.
  969. */
  970. inline int roundDoubleToIntAccurate (const double value) throw()
  971. {
  972. return roundDoubleToInt (value + 1.5e-8);
  973. }
  974. /** Fast floating-point-to-integer conversion.
  975. This is faster than using the normal c++ cast to convert a float to an int, and
  976. it will round the value to the nearest integer, rather than rounding it down
  977. like the normal cast does.
  978. Note that this routine gets its speed at the expense of some accuracy, and when
  979. rounding values whose floating point component is exactly 0.5, odd numbers and
  980. even numbers will be rounded up or down differently.
  981. */
  982. inline int roundFloatToInt (const float value) throw()
  983. {
  984. union { int asInt[2]; double asDouble; } n;
  985. n.asDouble = value + 6755399441055744.0;
  986. #if JUCE_BIG_ENDIAN
  987. return n.asInt [1];
  988. #else
  989. return n.asInt [0];
  990. #endif
  991. }
  992. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  993. /********* End of inlined file: juce_DataConversions.h *********/
  994. /********* Start of inlined file: juce_Logger.h *********/
  995. #ifndef __JUCE_LOGGER_JUCEHEADER__
  996. #define __JUCE_LOGGER_JUCEHEADER__
  997. /********* Start of inlined file: juce_String.h *********/
  998. #ifndef __JUCE_STRING_JUCEHEADER__
  999. #define __JUCE_STRING_JUCEHEADER__
  1000. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1001. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1002. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1003. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1004. (in the default system encoding) as its internal representation.
  1005. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1006. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1007. literals in the T("abcd") macro, so that it all works nicely either way round.
  1008. */
  1009. #if JUCE_STRINGS_ARE_UNICODE
  1010. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1011. typedef juce_wchar tchar;
  1012. #define juce_tcharToWideChar(c) (c)
  1013. #else
  1014. #define JUCE_T(stringLiteral) (stringLiteral)
  1015. typedef char tchar;
  1016. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1017. #endif
  1018. #if ! JUCE_DONT_DEFINE_MACROS
  1019. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1020. or unicode.
  1021. If you write your string literals in the form T("xyz"), this will either be compiled
  1022. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1023. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1024. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1025. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1026. the juce/src directory) to avoid defining this macro. See the comments in
  1027. juce_withoutMacros.h for more info.
  1028. */
  1029. #define T(stringLiteral) JUCE_T(stringLiteral)
  1030. #endif
  1031. /**
  1032. A set of methods for manipulating characters and character strings, with
  1033. duplicate methods to handle 8-bit and unicode characters.
  1034. These are defined as wrappers around the basic C string handlers, to provide
  1035. a clean, cross-platform layer, (because various platforms differ in the
  1036. range of C library calls that they provide).
  1037. @see String
  1038. */
  1039. class JUCE_API CharacterFunctions
  1040. {
  1041. public:
  1042. static int length (const char* const s) throw();
  1043. static int length (const juce_wchar* const s) throw();
  1044. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1045. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1046. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1047. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1048. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1049. static void append (char* dest, const char* src) throw();
  1050. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1051. static int compare (const char* const s1, const char* const s2) throw();
  1052. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1053. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1054. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1055. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1056. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1057. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1058. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1059. static const char* find (const char* const haystack, const char* const needle) throw();
  1060. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1061. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1062. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1063. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1064. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1065. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1066. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1067. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1068. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1069. static int getIntValue (const char* const s) throw();
  1070. static int getIntValue (const juce_wchar* s) throw();
  1071. static int64 getInt64Value (const char* s) throw();
  1072. static int64 getInt64Value (const juce_wchar* s) throw();
  1073. static double getDoubleValue (const char* const s) throw();
  1074. static double getDoubleValue (const juce_wchar* const s) throw();
  1075. static char toUpperCase (const char character) throw();
  1076. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1077. static void toUpperCase (char* s) throw();
  1078. static void toUpperCase (juce_wchar* s) throw();
  1079. static bool isUpperCase (const char character) throw();
  1080. static bool isUpperCase (const juce_wchar character) throw();
  1081. static char toLowerCase (const char character) throw();
  1082. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1083. static void toLowerCase (char* s) throw();
  1084. static void toLowerCase (juce_wchar* s) throw();
  1085. static bool isLowerCase (const char character) throw();
  1086. static bool isLowerCase (const juce_wchar character) throw();
  1087. static bool isWhitespace (const char character) throw();
  1088. static bool isWhitespace (const juce_wchar character) throw();
  1089. static bool isDigit (const char character) throw();
  1090. static bool isDigit (const juce_wchar character) throw();
  1091. static bool isLetter (const char character) throw();
  1092. static bool isLetter (const juce_wchar character) throw();
  1093. static bool isLetterOrDigit (const char character) throw();
  1094. static bool isLetterOrDigit (const juce_wchar character) throw();
  1095. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1096. hex digit.
  1097. */
  1098. static int getHexDigitValue (const tchar digit) throw();
  1099. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1100. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1101. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1102. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1103. };
  1104. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1105. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1106. /**
  1107. The JUCE String class!
  1108. Using a reference-counted internal representation, these strings are fast
  1109. and efficient, and there are methods to do just about any operation you'll ever
  1110. dream of.
  1111. @see StringArray, StringPairArray
  1112. */
  1113. class JUCE_API String
  1114. {
  1115. public:
  1116. /** Creates an empty string.
  1117. @see empty
  1118. */
  1119. String() throw();
  1120. /** Creates a copy of another string. */
  1121. String (const String& other) throw();
  1122. /** Creates a string from a zero-terminated text string.
  1123. The string is assumed to be stored in the default system encoding.
  1124. */
  1125. String (const char* const text) throw();
  1126. /** Creates a string from an string of characters.
  1127. This will use up the the first maxChars characters of the string (or
  1128. less if the string is actually shorter)
  1129. */
  1130. String (const char* const text,
  1131. const int maxChars) throw();
  1132. /** Creates a string from a zero-terminated unicode text string. */
  1133. String (const juce_wchar* const unicodeText) throw();
  1134. /** Creates a string from a unicode text string.
  1135. This will use up the the first maxChars characters of the string (or
  1136. less if the string is actually shorter)
  1137. */
  1138. String (const juce_wchar* const unicodeText,
  1139. const int maxChars) throw();
  1140. /** Creates a string from a single character. */
  1141. static const String charToString (const tchar character) throw();
  1142. /** Destructor. */
  1143. ~String() throw();
  1144. /** This is an empty string that can be used whenever one is needed.
  1145. It's better to use this than String() because it explains what's going on
  1146. and is more efficient.
  1147. */
  1148. static const String empty;
  1149. /** Generates a probably-unique 32-bit hashcode from this string. */
  1150. int hashCode() const throw();
  1151. /** Generates a probably-unique 64-bit hashcode from this string. */
  1152. int64 hashCode64() const throw();
  1153. /** Returns the number of characters in the string. */
  1154. int length() const throw();
  1155. // Assignment and concatenation operators..
  1156. /** Replaces this string's contents with another string. */
  1157. const String& operator= (const tchar* const other) throw();
  1158. /** Replaces this string's contents with another string. */
  1159. const String& operator= (const String& other) throw();
  1160. /** Appends another string at the end of this one. */
  1161. const String& operator+= (const tchar* const textToAppend) throw();
  1162. /** Appends another string at the end of this one. */
  1163. const String& operator+= (const String& stringToAppend) throw();
  1164. /** Appends a character at the end of this string. */
  1165. const String& operator+= (const char characterToAppend) throw();
  1166. /** Appends a character at the end of this string. */
  1167. const String& operator+= (const juce_wchar characterToAppend) throw();
  1168. /** Appends a string at the end of this one.
  1169. @param textToAppend the string to add
  1170. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1171. */
  1172. void append (const tchar* const textToAppend,
  1173. const int maxCharsToTake) throw();
  1174. /** Appends a string at the end of this one.
  1175. @returns the concatenated string
  1176. */
  1177. const String operator+ (const String& stringToAppend) const throw();
  1178. /** Appends a string at the end of this one.
  1179. @returns the concatenated string
  1180. */
  1181. const String operator+ (const tchar* const textToAppend) const throw();
  1182. /** Appends a character at the end of this one.
  1183. @returns the concatenated string
  1184. */
  1185. const String operator+ (const tchar characterToAppend) const throw();
  1186. /** Appends a character at the end of this string. */
  1187. String& operator<< (const char n) throw();
  1188. /** Appends a character at the end of this string. */
  1189. String& operator<< (const juce_wchar n) throw();
  1190. /** Appends another string at the end of this one. */
  1191. String& operator<< (const char* const text) throw();
  1192. /** Appends another string at the end of this one. */
  1193. String& operator<< (const juce_wchar* const text) throw();
  1194. /** Appends another string at the end of this one. */
  1195. String& operator<< (const String& text) throw();
  1196. /** Appends a decimal number at the end of this string. */
  1197. String& operator<< (const short number) throw();
  1198. /** Appends a decimal number at the end of this string. */
  1199. String& operator<< (const int number) throw();
  1200. /** Appends a decimal number at the end of this string. */
  1201. String& operator<< (const unsigned int number) throw();
  1202. /** Appends a decimal number at the end of this string. */
  1203. String& operator<< (const float number) throw();
  1204. /** Appends a decimal number at the end of this string. */
  1205. String& operator<< (const double number) throw();
  1206. // Comparison methods..
  1207. /** Returns true if the string contains no characters.
  1208. Note that there's also an isNotEmpty() method to help write readable code.
  1209. @see containsNonWhitespaceChars()
  1210. */
  1211. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1212. /** Returns true if the string contains at least one character.
  1213. Note that there's also an isEmpty() method to help write readable code.
  1214. @see containsNonWhitespaceChars()
  1215. */
  1216. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1217. /** Case-sensitive comparison with another string. */
  1218. bool operator== (const String& other) const throw();
  1219. /** Case-sensitive comparison with another string. */
  1220. bool operator== (const tchar* const other) const throw();
  1221. /** Case-sensitive comparison with another string. */
  1222. bool operator!= (const String& other) const throw();
  1223. /** Case-sensitive comparison with another string. */
  1224. bool operator!= (const tchar* const other) const throw();
  1225. /** Case-insensitive comparison with another string. */
  1226. bool equalsIgnoreCase (const String& other) const throw();
  1227. /** Case-insensitive comparison with another string. */
  1228. bool equalsIgnoreCase (const tchar* const other) const throw();
  1229. /** Case-sensitive comparison with another string. */
  1230. bool operator> (const String& other) const throw();
  1231. /** Case-sensitive comparison with another string. */
  1232. bool operator< (const tchar* const other) const throw();
  1233. /** Case-sensitive comparison with another string. */
  1234. bool operator>= (const String& other) const throw();
  1235. /** Case-sensitive comparison with another string. */
  1236. bool operator<= (const tchar* const other) const throw();
  1237. /** Case-sensitive comparison with another string.
  1238. @returns 0 if the two strings are identical; negative if this string
  1239. comes before the other one alphabetically, or positive if it
  1240. comes after it.
  1241. */
  1242. int compare (const tchar* const other) const throw();
  1243. /** Case-insensitive comparison with another string.
  1244. @returns 0 if the two strings are identical; negative if this string
  1245. comes before the other one alphabetically, or positive if it
  1246. comes after it.
  1247. */
  1248. int compareIgnoreCase (const tchar* const other) const throw();
  1249. /** Lexicographic comparison with another string.
  1250. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1251. characters, making it good for sorting human-readable strings.
  1252. @returns 0 if the two strings are identical; negative if this string
  1253. comes before the other one alphabetically, or positive if it
  1254. comes after it.
  1255. */
  1256. int compareLexicographically (const tchar* const other) const throw();
  1257. /** Tests whether the string begins with another string.
  1258. Uses a case-sensitive comparison.
  1259. */
  1260. bool startsWith (const tchar* const text) const throw();
  1261. /** Tests whether the string begins with a particular character.
  1262. Uses a case-sensitive comparison.
  1263. */
  1264. bool startsWithChar (const tchar character) const throw();
  1265. /** Tests whether the string begins with another string.
  1266. Uses a case-insensitive comparison.
  1267. */
  1268. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1269. /** Tests whether the string ends with another string.
  1270. Uses a case-sensitive comparison.
  1271. */
  1272. bool endsWith (const tchar* const text) const throw();
  1273. /** Tests whether the string ends with a particular character.
  1274. Uses a case-sensitive comparison.
  1275. */
  1276. bool endsWithChar (const tchar character) const throw();
  1277. /** Tests whether the string ends with another string.
  1278. Uses a case-insensitive comparison.
  1279. */
  1280. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1281. /** Tests whether the string contains another substring.
  1282. Uses a case-sensitive comparison.
  1283. */
  1284. bool contains (const tchar* const text) const throw();
  1285. /** Tests whether the string contains a particular character.
  1286. Uses a case-sensitive comparison.
  1287. */
  1288. bool containsChar (const tchar character) const throw();
  1289. /** Tests whether the string contains another substring.
  1290. Uses a case-insensitive comparison.
  1291. */
  1292. bool containsIgnoreCase (const tchar* const text) const throw();
  1293. /** Tests whether the string contains another substring as a distict word.
  1294. @returns true if the string contains this word, surrounded by
  1295. non-alphanumeric characters
  1296. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1297. */
  1298. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1299. /** Tests whether the string contains another substring as a distict word.
  1300. @returns true if the string contains this word, surrounded by
  1301. non-alphanumeric characters
  1302. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1303. */
  1304. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1305. /** Finds an instance of another substring if it exists as a distict word.
  1306. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1307. then this will return the index of the start of the substring. If it isn't
  1308. found, then it will return -1
  1309. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1310. */
  1311. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1312. /** Finds an instance of another substring if it exists as a distict word.
  1313. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1314. then this will return the index of the start of the substring. If it isn't
  1315. found, then it will return -1
  1316. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1317. */
  1318. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1319. /** Looks for any of a set of characters in the string.
  1320. Uses a case-sensitive comparison.
  1321. @returns true if the string contains any of the characters from
  1322. the string that is passed in.
  1323. */
  1324. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1325. /** Looks for a set of characters in the string.
  1326. Uses a case-sensitive comparison.
  1327. @returns true if the all the characters in the string are also found in the
  1328. string that is passed in.
  1329. */
  1330. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1331. /** Returns true if this string contains any non-whitespace characters.
  1332. This will return false if the string contains only whitespace characters, or
  1333. if it's empty.
  1334. It is equivalent to calling "myString.trim().isNotEmpty()".
  1335. */
  1336. bool containsNonWhitespaceChars() const throw();
  1337. /** Returns true if the string matches this simple wildcard expression.
  1338. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1339. This isn't a full-blown regex though! The only wildcard characters supported
  1340. are "*" and "?". It's mainly intended for filename pattern matching.
  1341. */
  1342. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1343. // Substring location methods..
  1344. /** Searches for a character inside this string.
  1345. Uses a case-sensitive comparison.
  1346. @returns the index of the first occurrence of the character in this
  1347. string, or -1 if it's not found.
  1348. */
  1349. int indexOfChar (const tchar characterToLookFor) const throw();
  1350. /** Searches for a character inside this string.
  1351. Uses a case-sensitive comparison.
  1352. @param startIndex the index from which the search should proceed
  1353. @param characterToLookFor the character to look for
  1354. @returns the index of the first occurrence of the character in this
  1355. string, or -1 if it's not found.
  1356. */
  1357. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1358. /** Returns the index of the first character that matches one of the characters
  1359. passed-in to this method.
  1360. This scans the string, beginning from the startIndex supplied, and if it finds
  1361. a character that appears in the string charactersToLookFor, it returns its index.
  1362. If none of these characters are found, it returns -1.
  1363. If ignoreCase is true, the comparison will be case-insensitive.
  1364. @see indexOfChar, lastIndexOfAnyOf
  1365. */
  1366. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1367. const int startIndex = 0,
  1368. const bool ignoreCase = false) const throw();
  1369. /** Searches for a substring within this string.
  1370. Uses a case-sensitive comparison.
  1371. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1372. */
  1373. int indexOf (const tchar* const text) const throw();
  1374. /** Searches for a substring within this string.
  1375. Uses a case-sensitive comparison.
  1376. @param startIndex the index from which the search should proceed
  1377. @param textToLookFor the string to search for
  1378. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1379. */
  1380. int indexOf (const int startIndex,
  1381. const tchar* const textToLookFor) const throw();
  1382. /** Searches for a substring within this string.
  1383. Uses a case-insensitive comparison.
  1384. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1385. */
  1386. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1387. /** Searches for a substring within this string.
  1388. Uses a case-insensitive comparison.
  1389. @param startIndex the index from which the search should proceed
  1390. @param textToLookFor the string to search for
  1391. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1392. */
  1393. int indexOfIgnoreCase (const int startIndex,
  1394. const tchar* const textToLookFor) const throw();
  1395. /** Searches for a character inside this string (working backwards from the end of the string).
  1396. Uses a case-sensitive comparison.
  1397. @returns the index of the last occurrence of the character in this
  1398. string, or -1 if it's not found.
  1399. */
  1400. int lastIndexOfChar (const tchar character) const throw();
  1401. /** Searches for a substring inside this string (working backwards from the end of the string).
  1402. Uses a case-sensitive comparison.
  1403. @returns the index of the start of the last occurrence of the
  1404. substring within this string, or -1 if it's not found.
  1405. */
  1406. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1407. /** Searches for a substring inside this string (working backwards from the end of the string).
  1408. Uses a case-insensitive comparison.
  1409. @returns the index of the start of the last occurrence of the
  1410. substring within this string, or -1 if it's not found.
  1411. */
  1412. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1413. /** Returns the index of the last character in this string that matches one of the
  1414. characters passed-in to this method.
  1415. This scans the string backwards, starting from its end, and if it finds
  1416. a character that appears in the string charactersToLookFor, it returns its index.
  1417. If none of these characters are found, it returns -1.
  1418. If ignoreCase is true, the comparison will be case-insensitive.
  1419. @see lastIndexOf, indexOfAnyOf
  1420. */
  1421. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1422. const bool ignoreCase = false) const throw();
  1423. // Substring extraction and manipulation methods..
  1424. /** Returns the character at this index in the string.
  1425. No checks are made to see if the index is within a valid range, so be careful!
  1426. */
  1427. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1428. /** Returns a character from the string such that it can also be altered.
  1429. This can be used as a way of easily changing characters in the string.
  1430. Note that the index passed-in is not checked to see whether it's in-range, so
  1431. be careful when using this.
  1432. */
  1433. tchar& operator[] (const int index) throw();
  1434. /** Returns the final character of the string.
  1435. If the string is empty this will return 0.
  1436. */
  1437. tchar getLastCharacter() const throw();
  1438. /** Returns a subsection of the string.
  1439. If the range specified is beyond the limits of the string, as much as
  1440. possible is returned.
  1441. @param startIndex the index of the start of the substring needed
  1442. @param endIndex all characters from startIndex up to (but not including)
  1443. this index are returned
  1444. @see fromFirstOccurrenceOf, dropLastCharacters, upToFirstOccurrenceOf
  1445. */
  1446. const String substring (int startIndex,
  1447. int endIndex) const throw();
  1448. /** Returns a section of the string, starting from a given position.
  1449. @param startIndex the first character to include. If this is beyond the end
  1450. of the string, an empty string is returned. If it is zero or
  1451. less, the whole string is returned.
  1452. @returns the substring from startIndex up to the end of the string
  1453. @see dropLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1454. */
  1455. const String substring (const int startIndex) const throw();
  1456. /** Returns a version of this string with a number of characters removed
  1457. from the end.
  1458. @param numberToDrop the number of characters to drop from the end of the
  1459. string. If this is greater than the length of the string,
  1460. an empty string will be returned. If zero or less, the
  1461. original string will be returned.
  1462. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1463. */
  1464. const String dropLastCharacters (const int numberToDrop) const throw();
  1465. /** Returns a section of the string starting from a given substring.
  1466. This will search for the first occurrence of the given substring, and
  1467. return the section of the string starting from the point where this is
  1468. found (optionally not including the substring itself).
  1469. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1470. fromFirstOccurrenceOf ("34", false) would return "56".
  1471. If the substring isn't found, the method will return an empty string.
  1472. If ignoreCase is true, the comparison will be case-insensitive.
  1473. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1474. */
  1475. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1476. const bool includeSubStringInResult,
  1477. const bool ignoreCase) const throw();
  1478. /** Returns a section of the string starting from the last occurrence of a given substring.
  1479. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1480. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1481. return the whole of the original string.
  1482. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1483. */
  1484. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1485. const bool includeSubStringInResult,
  1486. const bool ignoreCase) const throw();
  1487. /** Returns the start of this string, up to the first occurrence of a substring.
  1488. This will search for the first occurrence of a given substring, and then
  1489. return a copy of the string, up to the position of this substring,
  1490. optionally including or excluding the substring itself in the result.
  1491. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1492. upTo ("34", true) would return "1234".
  1493. If the substring isn't found, this will return the whole of the original string.
  1494. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1495. */
  1496. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1497. const bool includeSubStringInResult,
  1498. const bool ignoreCase) const throw();
  1499. /** Returns the start of this string, up to the last occurrence of a substring.
  1500. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1501. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1502. */
  1503. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1504. const bool includeSubStringInResult,
  1505. const bool ignoreCase) const throw();
  1506. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1507. const String trim() const throw();
  1508. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1509. const String trimStart() const throw();
  1510. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1511. const String trimEnd() const throw();
  1512. /** Returns an upper-case version of this string. */
  1513. const String toUpperCase() const throw();
  1514. /** Returns an lower-case version of this string. */
  1515. const String toLowerCase() const throw();
  1516. /** Replaces a sub-section of the string with another string.
  1517. This will return a copy of this string, with a set of characters
  1518. from startIndex to startIndex + numCharsToReplace removed, and with
  1519. a new string inserted in their place.
  1520. Note that this is a const method, and won't alter the string itself.
  1521. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1522. it will be constrained to a valid range.
  1523. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1524. characters will be taken out.
  1525. @param stringToInsert the new string to insert at startIndex after the characters have been
  1526. removed.
  1527. */
  1528. const String replaceSection (int startIndex,
  1529. int numCharactersToReplace,
  1530. const tchar* const stringToInsert) const throw();
  1531. /** Replaces all occurrences of a substring with another string.
  1532. Returns a copy of this string, with any occurrences of stringToReplace
  1533. swapped for stringToInsertInstead.
  1534. Note that this is a const method, and won't alter the string itself.
  1535. */
  1536. const String replace (const tchar* const stringToReplace,
  1537. const tchar* const stringToInsertInstead,
  1538. const bool ignoreCase = false) const throw();
  1539. /** Returns a string with all occurrences of a character replaced with a different one. */
  1540. const String replaceCharacter (const tchar characterToReplace,
  1541. const tchar characterToInsertInstead) const throw();
  1542. /** Replaces a set of characters with another set.
  1543. Returns a string in which each character from charactersToReplace has been replaced
  1544. by the character at the equivalent position in newCharacters (so the two strings
  1545. passed in must be the same length).
  1546. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1547. Note that this is a const method, and won't affect the string itself.
  1548. */
  1549. const String replaceCharacters (const String& charactersToReplace,
  1550. const tchar* const charactersToInsertInstead) const throw();
  1551. /** Returns a version of this string that only retains a fixed set of characters.
  1552. This will return a copy of this string, omitting any characters which are not
  1553. found in the string passed-in.
  1554. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1555. Note that this is a const method, and won't alter the string itself.
  1556. */
  1557. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1558. /** Returns a version of this string with a set of characters removed.
  1559. This will return a copy of this string, omitting any characters which are
  1560. found in the string passed-in.
  1561. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1562. Note that this is a const method, and won't alter the string itself.
  1563. */
  1564. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1565. /** Returns a section from the start of the string that only contains a certain set of characters.
  1566. This returns the leftmost section of the string, up to (and not including) the
  1567. first character that doesn't appear in the string passed in.
  1568. */
  1569. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1570. /** Returns a section from the start of the string that only contains a certain set of characters.
  1571. This returns the leftmost section of the string, up to (and not including) the
  1572. first character that occurs in the string passed in.
  1573. */
  1574. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1575. /** Checks whether the string might be in quotation marks.
  1576. @returns true if the string begins with a quote character (either a double or single quote).
  1577. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1578. @see unquoted, quoted
  1579. */
  1580. bool isQuotedString() const throw();
  1581. /** Removes quotation marks from around the string, (if there are any).
  1582. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1583. at the ends of the string are not affected. If there aren't any quotes, the original string
  1584. is returned.
  1585. Note that this is a const method, and won't alter the string itself.
  1586. @see isQuotedString, quoted
  1587. */
  1588. const String unquoted() const throw();
  1589. /** Adds quotation marks around a string.
  1590. This will return a copy of the string with a quote at the start and end, (but won't
  1591. add the quote if there's already one there, so it's safe to call this on strings that
  1592. may already have quotes around them).
  1593. Note that this is a const method, and won't alter the string itself.
  1594. @param quoteCharacter the character to add at the start and end
  1595. @see isQuotedString, unquoted
  1596. */
  1597. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1598. /** Writes text into this string, using printf style-arguments.
  1599. This will replace the contents of the string with the output of this
  1600. formatted printf.
  1601. Note that using the %s token with a juce string is probably a bad idea, as
  1602. this may expect differect encodings on different platforms.
  1603. @see formatted
  1604. */
  1605. void printf (const tchar* const format, ...) throw();
  1606. /** Returns a string, created using arguments in the style of printf.
  1607. This will return a string which is the result of a sprintf using the
  1608. arguments passed-in.
  1609. Note that using the %s token with a juce string is probably a bad idea, as
  1610. this may expect differect encodings on different platforms.
  1611. @see printf, vprintf
  1612. */
  1613. static const String formatted (const tchar* const format, ...) throw();
  1614. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1615. This will replace the contents of the string with the output of this
  1616. formatted printf. Used by other methods, this is public in case it's
  1617. useful for other purposes where you want to pass a va_list through directly.
  1618. Note that using the %s token with a juce string is probably a bad idea, as
  1619. this may expect differect encodings on different platforms.
  1620. @see printf, formatted
  1621. */
  1622. void vprintf (const tchar* const format, va_list& args) throw();
  1623. /** Creates a string which is a version of a string repeated and joined together.
  1624. @param stringToRepeat the string to repeat
  1625. @param numberOfTimesToRepeat how many times to repeat it
  1626. */
  1627. static const String repeatedString (const tchar* const stringToRepeat,
  1628. int numberOfTimesToRepeat) throw();
  1629. /** Creates a string from data in an unknown format.
  1630. This looks at some binary data and tries to guess whether it's Unicode
  1631. or 8-bit characters, then returns a string that represents it correctly.
  1632. Should be able to handle Unicode endianness correctly, by looking at
  1633. the first two bytes.
  1634. */
  1635. static const String createStringFromData (const void* const data,
  1636. const int size) throw();
  1637. // Numeric conversions..
  1638. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1639. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1640. */
  1641. explicit String (const int decimalInteger) throw();
  1642. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1643. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1644. */
  1645. explicit String (const unsigned int decimalInteger) throw();
  1646. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1647. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1648. */
  1649. explicit String (const short decimalInteger) throw();
  1650. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1651. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1652. */
  1653. explicit String (const unsigned short decimalInteger) throw();
  1654. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1655. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1656. */
  1657. explicit String (const int64 largeIntegerValue) throw();
  1658. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1659. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1660. */
  1661. explicit String (const uint64 largeIntegerValue) throw();
  1662. /** Creates a string representing this floating-point number.
  1663. @param floatValue the value to convert to a string
  1664. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1665. decimal places, and will not use exponent notation. If 0 or
  1666. less, it will use exponent notation if necessary.
  1667. @see getDoubleValue, getIntValue
  1668. */
  1669. explicit String (const float floatValue,
  1670. const int numberOfDecimalPlaces = 0) throw();
  1671. /** Creates a string representing this floating-point number.
  1672. @param doubleValue the value to convert to a string
  1673. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1674. decimal places, and will not use exponent notation. If 0 or
  1675. less, it will use exponent notation if necessary.
  1676. @see getFloatValue, getIntValue
  1677. */
  1678. explicit String (const double doubleValue,
  1679. const int numberOfDecimalPlaces = 0) throw();
  1680. /** Parses this string to find its numerical value (up to 32 bits in size).
  1681. @returns the value of the string as a 32 bit signed base-10 integer.
  1682. @see getTrailingIntValue, getHexValue32, getHexValue64
  1683. */
  1684. int getIntValue() const throw();
  1685. /** Parses this string to find its numerical value (up to 64 bits in size).
  1686. @returns the value of the string as a 64 bit signed base-10 integer.
  1687. */
  1688. int64 getLargeIntValue() const throw();
  1689. /** Parses a decimal number from the end of the string.
  1690. This will look for a value at the end of the string.
  1691. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1692. Negative numbers are not handled, so "xyz-5" returns 5.
  1693. @see getIntValue
  1694. */
  1695. int getTrailingIntValue() const throw();
  1696. /** Parses this string as a floating point number.
  1697. @returns the value of the string as a 32-bit floating point value.
  1698. @see getDoubleValue
  1699. */
  1700. float getFloatValue() const throw();
  1701. /** Parses this string as a floating point number.
  1702. @returns the value of the string as a 64-bit floating point value.
  1703. @see getFloatValue
  1704. */
  1705. double getDoubleValue() const throw();
  1706. /** Parses the string as a hexadecimal number.
  1707. Non-hexadecimal characters in the string are ignored.
  1708. If the string contains too many characters, then the lowest significant
  1709. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1710. @returns a 32-bit number which is the value of the string in hex.
  1711. */
  1712. int getHexValue32() const throw();
  1713. /** Parses the string as a hexadecimal number.
  1714. Non-hexadecimal characters in the string are ignored.
  1715. If the string contains too many characters, then the lowest significant
  1716. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1717. @returns a 64-bit number which is the value of the string in hex.
  1718. */
  1719. int64 getHexValue64() const throw();
  1720. /** Creates a string representing this 32-bit value in hexadecimal. */
  1721. static const String toHexString (const int number) throw();
  1722. /** Creates a string representing this 64-bit value in hexadecimal. */
  1723. static const String toHexString (const int64 number) throw();
  1724. /** Creates a string representing this 16-bit value in hexadecimal. */
  1725. static const String toHexString (const short number) throw();
  1726. /** Creates a string containing a hex dump of a block of binary data.
  1727. @param data the binary data to use as input
  1728. @param size how many bytes of data to use
  1729. @param groupSize how many bytes are grouped together before inserting a
  1730. space into the output. e.g. group size 0 has no spaces,
  1731. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1732. like "bea1 c2ff".
  1733. */
  1734. static const String toHexString (const unsigned char* data,
  1735. const int size,
  1736. const int groupSize = 1) throw();
  1737. // Casting to character arrays..
  1738. #if JUCE_STRINGS_ARE_UNICODE
  1739. /** Returns a version of this string using the default 8-bit system encoding.
  1740. Because it returns a reference to the string's internal data, the pointer
  1741. that is returned must not be stored anywhere, as it can be deleted whenever the
  1742. string changes.
  1743. */
  1744. operator const char*() const throw();
  1745. /** Returns a unicode version of this string.
  1746. Because it returns a reference to the string's internal data, the pointer
  1747. that is returned must not be stored anywhere, as it can be deleted whenever the
  1748. string changes.
  1749. */
  1750. inline operator const juce_wchar*() const throw() { return text->text; }
  1751. #else
  1752. /** Returns a version of this string using the default 8-bit system encoding.
  1753. Because it returns a reference to the string's internal data, the pointer
  1754. that is returned must not be stored anywhere, as it can be deleted whenever the
  1755. string changes.
  1756. */
  1757. inline operator const char*() const throw() { return text->text; }
  1758. /** Returns a unicode version of this string.
  1759. Because it returns a reference to the string's internal data, the pointer
  1760. that is returned must not be stored anywhere, as it can be deleted whenever the
  1761. string changes.
  1762. */
  1763. operator const juce_wchar*() const throw();
  1764. #endif
  1765. /** Copies the string to a buffer.
  1766. @param destBuffer the place to copy it to
  1767. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1768. not including the tailing zero, so this shouldn't be
  1769. larger than the size of your destination buffer - 1
  1770. */
  1771. void copyToBuffer (char* const destBuffer,
  1772. const int maxCharsToCopy) const throw();
  1773. /** Copies the string to a unicode buffer.
  1774. @param destBuffer the place to copy it to
  1775. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1776. not including the tailing zero, so this shouldn't be
  1777. larger than the size of your destination buffer - 1
  1778. */
  1779. void copyToBuffer (juce_wchar* const destBuffer,
  1780. const int maxCharsToCopy) const throw();
  1781. /** Copies the string to a buffer as UTF-8 characters.
  1782. Returns the number of bytes copied to the buffer, including the terminating null
  1783. character.
  1784. @param destBuffer the place to copy it to; if this is a null pointer,
  1785. the method just returns the number of bytes required
  1786. (including the terminating null character).
  1787. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1788. string won't fit, it'll put in as many as it can while
  1789. still allowing for a terminating null char at the end,
  1790. and will return the number of bytes that were actually
  1791. used. If this value is < 0, no limit is used.
  1792. */
  1793. int copyToUTF8 (uint8* const destBuffer, const int maxBufferSizeBytes = 0x7fffffff) const throw();
  1794. /** Returns a pointer to a UTF-8 version of this string.
  1795. Because it returns a reference to the string's internal data, the pointer
  1796. that is returned must not be stored anywhere, as it can be deleted whenever the
  1797. string changes.
  1798. */
  1799. const char* toUTF8() const throw();
  1800. /** Creates a String from a UTF-8 encoded buffer.
  1801. If the size is < 0, it'll keep reading until it hits a zero.
  1802. */
  1803. static const String fromUTF8 (const uint8* const utf8buffer,
  1804. int bufferSizeBytes = -1) throw();
  1805. /** Increases the string's internally allocated storage.
  1806. Although the string's contents won't be affected by this call, it will
  1807. increase the amount of memory allocated internally for the string to grow into.
  1808. If you're about to make a large number of calls to methods such
  1809. as += or <<, it's more efficient to preallocate enough extra space
  1810. beforehand, so that these methods won't have to keep resizing the string
  1811. to append the extra characters.
  1812. @param numCharsNeeded the number of characters to allocate storage for. If this
  1813. value is less than the currently allocated size, it will
  1814. have no effect.
  1815. */
  1816. void preallocateStorage (const int numCharsNeeded) throw();
  1817. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1818. private:
  1819. struct InternalRefCountedStringHolder
  1820. {
  1821. int refCount;
  1822. int allocatedNumChars;
  1823. #if JUCE_STRINGS_ARE_UNICODE
  1824. wchar_t text[1];
  1825. #else
  1826. char text[1];
  1827. #endif
  1828. };
  1829. InternalRefCountedStringHolder* text;
  1830. static InternalRefCountedStringHolder emptyString;
  1831. // internal constructor that preallocates a certain amount of memory
  1832. String (const int numChars, const int dummyVariable) throw();
  1833. void deleteInternal() throw();
  1834. void createInternal (const int numChars) throw();
  1835. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1836. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1837. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1838. void dupeInternalIfMultiplyReferenced() throw();
  1839. };
  1840. /** Global operator to allow a String to be appended to a string literal.
  1841. This allows the use of expressions such as "abc" + String (x)
  1842. @see String
  1843. */
  1844. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1845. const String& string2) throw();
  1846. /** Global operator to allow a String to be appended to a string literal.
  1847. This allows the use of expressions such as "abc" + String (x)
  1848. @see String
  1849. */
  1850. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1851. const String& string2) throw();
  1852. #endif // __JUCE_STRING_JUCEHEADER__
  1853. /********* End of inlined file: juce_String.h *********/
  1854. /**
  1855. Acts as an application-wide logging class.
  1856. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1857. method and this will then be used by all calls to writeToLog.
  1858. The logger class also contains methods for writing messages to the debugger's
  1859. output stream.
  1860. @see FileLogger
  1861. */
  1862. class JUCE_API Logger
  1863. {
  1864. public:
  1865. /** Destructor. */
  1866. virtual ~Logger();
  1867. /** Sets the current logging class to use.
  1868. Note that the object passed in won't be deleted when no longer needed.
  1869. A null pointer can be passed-in to disable any logging.
  1870. If deleteOldLogger is set to true, the existing logger will be
  1871. deleted (if there is one).
  1872. */
  1873. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1874. const bool deleteOldLogger = false);
  1875. /** Writes a string to the current logger.
  1876. This will pass the string to the logger's logMessage() method if a logger
  1877. has been set.
  1878. @see logMessage
  1879. */
  1880. static void JUCE_CALLTYPE writeToLog (const String& message);
  1881. /** Writes a message to the standard error stream.
  1882. This can be called directly, or by using the DBG() macro in
  1883. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1884. */
  1885. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1886. /** Writes a message to the standard error stream.
  1887. This can be called directly, or by using the DBG_PRINTF() macro in
  1888. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1889. */
  1890. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1891. protected:
  1892. Logger();
  1893. /** This is overloaded by subclasses to implement custom logging behaviour.
  1894. @see setCurrentLogger
  1895. */
  1896. virtual void logMessage (const String& message) = 0;
  1897. };
  1898. #endif // __JUCE_LOGGER_JUCEHEADER__
  1899. /********* End of inlined file: juce_Logger.h *********/
  1900. END_JUCE_NAMESPACE
  1901. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  1902. /********* End of inlined file: juce_StandardHeader.h *********/
  1903. BEGIN_JUCE_NAMESPACE
  1904. #if JUCE_MSVC
  1905. // this is set explicitly in case the app is using a different packing size.
  1906. #pragma pack (push, 8)
  1907. #pragma warning (push)
  1908. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  1909. #endif
  1910. #if JUCE_MAC
  1911. #pragma align=natural
  1912. #endif
  1913. #define JUCE_PUBLIC_INCLUDES
  1914. // this is where all the class header files get brought in..
  1915. /********* Start of inlined file: juce_core_includes.h *********/
  1916. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1917. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  1918. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1919. /********* Start of inlined file: juce_Atomic.h *********/
  1920. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  1921. #define __JUCE_ATOMIC_JUCEHEADER__
  1922. // Atomic increment/decrement operations..
  1923. #if JUCE_MAC && ! DOXYGEN
  1924. #if ! MACOS_10_3_OR_EARLIER
  1925. forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  1926. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  1927. forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  1928. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  1929. #else
  1930. forcedinline void atomicIncrement (int& variable) throw() { OTAtomicAdd32 (1, (SInt32*) &variable); }
  1931. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (1, (SInt32*) &variable); }
  1932. forcedinline void atomicDecrement (int& variable) throw() { OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1933. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OTAtomicAdd32 (-1, (SInt32*) &variable); }
  1934. #endif
  1935. #elif JUCE_GCC
  1936. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  1937. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  1938. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  1939. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  1940. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  1941. #else
  1942. /** Increments an integer in a thread-safe way. */
  1943. forcedinline void atomicIncrement (int& variable) throw()
  1944. {
  1945. __asm__ __volatile__ (
  1946. #if JUCE_64BIT
  1947. "lock incl (%%rax)"
  1948. :
  1949. : "a" (&variable)
  1950. : "cc", "memory");
  1951. #else
  1952. "lock incl %0"
  1953. : "=m" (variable)
  1954. : "m" (variable));
  1955. #endif
  1956. }
  1957. /** Increments an integer in a thread-safe way and returns the incremented value. */
  1958. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  1959. {
  1960. int result;
  1961. __asm__ __volatile__ (
  1962. #if JUCE_64BIT
  1963. "lock xaddl %%ebx, (%%rax) \n\
  1964. incl %%ebx"
  1965. : "=b" (result)
  1966. : "a" (&variable), "b" (1)
  1967. : "cc", "memory");
  1968. #else
  1969. "lock xaddl %%eax, (%%ecx) \n\
  1970. incl %%eax"
  1971. : "=a" (result)
  1972. : "c" (&variable), "a" (1)
  1973. : "memory");
  1974. #endif
  1975. return result;
  1976. }
  1977. /** Decrememts an integer in a thread-safe way. */
  1978. forcedinline void atomicDecrement (int& variable) throw()
  1979. {
  1980. __asm__ __volatile__ (
  1981. #if JUCE_64BIT
  1982. "lock decl (%%rax)"
  1983. :
  1984. : "a" (&variable)
  1985. : "cc", "memory");
  1986. #else
  1987. "lock decl %0"
  1988. : "=m" (variable)
  1989. : "m" (variable));
  1990. #endif
  1991. }
  1992. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  1993. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  1994. {
  1995. int result;
  1996. __asm__ __volatile__ (
  1997. #if JUCE_64BIT
  1998. "lock xaddl %%ebx, (%%rax) \n\
  1999. decl %%ebx"
  2000. : "=b" (result)
  2001. : "a" (&variable), "b" (-1)
  2002. : "cc", "memory");
  2003. #else
  2004. "lock xaddl %%eax, (%%ecx) \n\
  2005. decl %%eax"
  2006. : "=a" (result)
  2007. : "c" (&variable), "a" (-1)
  2008. : "memory");
  2009. #endif
  2010. return result;
  2011. }
  2012. #endif
  2013. #elif JUCE_USE_INTRINSICS
  2014. #pragma intrinsic (_InterlockedIncrement)
  2015. #pragma intrinsic (_InterlockedDecrement)
  2016. /** Increments an integer in a thread-safe way. */
  2017. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2018. {
  2019. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2020. }
  2021. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2022. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2023. {
  2024. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  2025. }
  2026. /** Decrememts an integer in a thread-safe way. */
  2027. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2028. {
  2029. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2030. }
  2031. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2032. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2033. {
  2034. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  2035. }
  2036. #else
  2037. /** Increments an integer in a thread-safe way. */
  2038. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  2039. {
  2040. __asm {
  2041. mov ecx, dword ptr [variable]
  2042. lock inc dword ptr [ecx]
  2043. }
  2044. }
  2045. /** Increments an integer in a thread-safe way and returns the incremented value. */
  2046. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  2047. {
  2048. int result;
  2049. __asm {
  2050. mov ecx, dword ptr [variable]
  2051. mov eax, 1
  2052. lock xadd dword ptr [ecx], eax
  2053. inc eax
  2054. mov result, eax
  2055. }
  2056. return result;
  2057. }
  2058. /** Decrememts an integer in a thread-safe way. */
  2059. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  2060. {
  2061. __asm {
  2062. mov ecx, dword ptr [variable]
  2063. lock dec dword ptr [ecx]
  2064. }
  2065. }
  2066. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  2067. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  2068. {
  2069. int result;
  2070. __asm {
  2071. mov ecx, dword ptr [variable]
  2072. mov eax, -1
  2073. lock xadd dword ptr [ecx], eax
  2074. dec eax
  2075. mov result, eax
  2076. }
  2077. return result;
  2078. }
  2079. #endif
  2080. #endif // __JUCE_ATOMIC_JUCEHEADER__
  2081. /********* End of inlined file: juce_Atomic.h *********/
  2082. #endif
  2083. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  2084. #endif
  2085. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2086. /********* Start of inlined file: juce_FileLogger.h *********/
  2087. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  2088. #define __JUCE_FILELOGGER_JUCEHEADER__
  2089. /********* Start of inlined file: juce_File.h *********/
  2090. #ifndef __JUCE_FILE_JUCEHEADER__
  2091. #define __JUCE_FILE_JUCEHEADER__
  2092. /********* Start of inlined file: juce_OwnedArray.h *********/
  2093. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  2094. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  2095. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2096. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2097. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2098. /** The default size of chunk in which arrays increase their storage.
  2099. Used by ArrayAllocationBase and its subclasses.
  2100. */
  2101. const int juceDefaultArrayGranularity = 8;
  2102. /**
  2103. Implements some basic array storage allocation functions.
  2104. This class isn't really for public use - it's used by the other
  2105. array classes, but might come in handy for some purposes.
  2106. @see Array, OwnedArray, ReferenceCountedArray
  2107. */
  2108. template <class ElementType>
  2109. class ArrayAllocationBase
  2110. {
  2111. protected:
  2112. /** Creates an empty array.
  2113. @param granularity_ this is the size of increment by which the internal storage
  2114. will be increased.
  2115. */
  2116. ArrayAllocationBase (const int granularity_) throw()
  2117. : elements (0),
  2118. numAllocated (0),
  2119. granularity (granularity_)
  2120. {
  2121. jassert (granularity > 0);
  2122. }
  2123. /** Destructor. */
  2124. ~ArrayAllocationBase() throw()
  2125. {
  2126. delete[] elements;
  2127. }
  2128. /** Changes the amount of storage allocated.
  2129. This will retain any data currently held in the array, and either add or
  2130. remove extra space at the end.
  2131. @param numElements the number of elements that are needed
  2132. */
  2133. void setAllocatedSize (const int numElements) throw()
  2134. {
  2135. if (numAllocated != numElements)
  2136. {
  2137. if (numElements > 0)
  2138. {
  2139. ElementType* const newElements = new ElementType [numElements];
  2140. const int itemsToRetain = jmin (numElements, numAllocated);
  2141. for (int i = 0; i < itemsToRetain; ++i)
  2142. newElements[i] = elements[i];
  2143. delete[] elements;
  2144. elements = newElements;
  2145. }
  2146. else if (elements != 0)
  2147. {
  2148. delete[] elements;
  2149. elements = 0;
  2150. }
  2151. numAllocated = numElements;
  2152. }
  2153. }
  2154. /** Increases the amount of storage allocated if it is less than a given amount.
  2155. This will retain any data currently held in the array, but will add
  2156. extra space at the end to make sure there it's at least as big as the size
  2157. passed in. If it's already bigger, no action is taken.
  2158. @param minNumElements the minimum number of elements that are needed
  2159. */
  2160. void ensureAllocatedSize (int minNumElements) throw()
  2161. {
  2162. if (minNumElements > numAllocated)
  2163. {
  2164. // for arrays with small granularity that get big, start
  2165. // increasing the size in bigger jumps
  2166. if (minNumElements > (granularity << 6))
  2167. {
  2168. minNumElements += (minNumElements / granularity);
  2169. if (minNumElements > (granularity << 8))
  2170. minNumElements += granularity << 6;
  2171. else
  2172. minNumElements += granularity << 5;
  2173. }
  2174. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2175. }
  2176. }
  2177. ElementType* elements;
  2178. int numAllocated, granularity;
  2179. private:
  2180. ArrayAllocationBase (const ArrayAllocationBase&);
  2181. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2182. };
  2183. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2184. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2185. /********* Start of inlined file: juce_ElementComparator.h *********/
  2186. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2187. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2188. /**
  2189. Sorts a range of elements in an array.
  2190. The comparator object that is passed-in must define a public method with the following
  2191. signature:
  2192. @code
  2193. int compareElements (ElementType first, ElementType second);
  2194. @endcode
  2195. ..and this method must return:
  2196. - a value of < 0 if the first comes before the second
  2197. - a value of 0 if the two objects are equivalent
  2198. - a value of > 0 if the second comes before the first
  2199. To improve performance, the compareElements() method can be declared as static or const.
  2200. @param comparator an object which defines a compareElements() method
  2201. @param array the array to sort
  2202. @param firstElement the index of the first element of the range to be sorted
  2203. @param lastElement the index of the last element in the range that needs
  2204. sorting (this is inclusive)
  2205. @param retainOrderOfEquivalentItems if true, the order of items that the
  2206. comparator deems the same will be maintained - this will be
  2207. a slower algorithm than if they are allowed to be moved around.
  2208. @see sortArrayRetainingOrder
  2209. */
  2210. template <class ElementType, class ElementComparator>
  2211. static void sortArray (ElementComparator& comparator,
  2212. ElementType* const array,
  2213. int firstElement,
  2214. int lastElement,
  2215. const bool retainOrderOfEquivalentItems)
  2216. {
  2217. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2218. // avoids getting warning messages about the parameter being unused
  2219. if (lastElement > firstElement)
  2220. {
  2221. if (retainOrderOfEquivalentItems)
  2222. {
  2223. for (int i = firstElement; i < lastElement; ++i)
  2224. {
  2225. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2226. {
  2227. const ElementType temp = array [i];
  2228. array [i] = array[i + 1];
  2229. array [i + 1] = temp;
  2230. if (i > firstElement)
  2231. i -= 2;
  2232. }
  2233. }
  2234. }
  2235. else
  2236. {
  2237. int fromStack[30], toStack[30];
  2238. int stackIndex = 0;
  2239. for (;;)
  2240. {
  2241. const int size = (lastElement - firstElement) + 1;
  2242. if (size <= 8)
  2243. {
  2244. int j = lastElement;
  2245. int maxIndex;
  2246. while (j > firstElement)
  2247. {
  2248. maxIndex = firstElement;
  2249. for (int k = firstElement + 1; k <= j; ++k)
  2250. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2251. maxIndex = k;
  2252. const ElementType temp = array [maxIndex];
  2253. array [maxIndex] = array[j];
  2254. array [j] = temp;
  2255. --j;
  2256. }
  2257. }
  2258. else
  2259. {
  2260. const int mid = firstElement + (size >> 1);
  2261. ElementType temp = array [mid];
  2262. array [mid] = array [firstElement];
  2263. array [firstElement] = temp;
  2264. int i = firstElement;
  2265. int j = lastElement + 1;
  2266. for (;;)
  2267. {
  2268. while (++i <= lastElement
  2269. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2270. {}
  2271. while (--j > firstElement
  2272. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2273. {}
  2274. if (j < i)
  2275. break;
  2276. temp = array[i];
  2277. array[i] = array[j];
  2278. array[j] = temp;
  2279. }
  2280. temp = array [firstElement];
  2281. array [firstElement] = array[j];
  2282. array [j] = temp;
  2283. if (j - 1 - firstElement >= lastElement - i)
  2284. {
  2285. if (firstElement + 1 < j)
  2286. {
  2287. fromStack [stackIndex] = firstElement;
  2288. toStack [stackIndex] = j - 1;
  2289. ++stackIndex;
  2290. }
  2291. if (i < lastElement)
  2292. {
  2293. firstElement = i;
  2294. continue;
  2295. }
  2296. }
  2297. else
  2298. {
  2299. if (i < lastElement)
  2300. {
  2301. fromStack [stackIndex] = i;
  2302. toStack [stackIndex] = lastElement;
  2303. ++stackIndex;
  2304. }
  2305. if (firstElement + 1 < j)
  2306. {
  2307. lastElement = j - 1;
  2308. continue;
  2309. }
  2310. }
  2311. }
  2312. if (--stackIndex < 0)
  2313. break;
  2314. jassert (stackIndex < numElementsInArray (fromStack));
  2315. firstElement = fromStack [stackIndex];
  2316. lastElement = toStack [stackIndex];
  2317. }
  2318. }
  2319. }
  2320. }
  2321. /**
  2322. Searches a sorted array of elements, looking for the index at which a specified value
  2323. should be inserted for it to be in the correct order.
  2324. The comparator object that is passed-in must define a public method with the following
  2325. signature:
  2326. @code
  2327. int compareElements (ElementType first, ElementType second);
  2328. @endcode
  2329. ..and this method must return:
  2330. - a value of < 0 if the first comes before the second
  2331. - a value of 0 if the two objects are equivalent
  2332. - a value of > 0 if the second comes before the first
  2333. To improve performance, the compareElements() method can be declared as static or const.
  2334. @param comparator an object which defines a compareElements() method
  2335. @param array the array to search
  2336. @param newElement the value that is going to be inserted
  2337. @param firstElement the index of the first element to search
  2338. @param lastElement the index of the last element in the range (this is non-inclusive)
  2339. */
  2340. template <class ElementType, class ElementComparator>
  2341. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2342. ElementType* const array,
  2343. const ElementType newElement,
  2344. int firstElement,
  2345. int lastElement)
  2346. {
  2347. jassert (firstElement <= lastElement);
  2348. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2349. // avoids getting warning messages about the parameter being unused
  2350. while (firstElement < lastElement)
  2351. {
  2352. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2353. {
  2354. ++firstElement;
  2355. break;
  2356. }
  2357. else
  2358. {
  2359. const int halfway = (firstElement + lastElement) >> 1;
  2360. if (halfway == firstElement)
  2361. {
  2362. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2363. ++firstElement;
  2364. break;
  2365. }
  2366. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2367. {
  2368. firstElement = halfway;
  2369. }
  2370. else
  2371. {
  2372. lastElement = halfway;
  2373. }
  2374. }
  2375. }
  2376. return firstElement;
  2377. }
  2378. /**
  2379. A simple ElementComparator class that can be used to sort an array of
  2380. integer primitive objects.
  2381. Example: @code
  2382. Array <int> myArray;
  2383. IntegerElementComparator<int> sorter;
  2384. myArray.sort (sorter);
  2385. @endcode
  2386. For floating point values, see the FloatElementComparator class instead.
  2387. @see FloatElementComparator, ElementComparator
  2388. */
  2389. template <class ElementType>
  2390. class IntegerElementComparator
  2391. {
  2392. public:
  2393. static int compareElements (const ElementType first,
  2394. const ElementType second) throw()
  2395. {
  2396. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2397. }
  2398. };
  2399. /**
  2400. A simple ElementComparator class that can be used to sort an array of numeric
  2401. double or floating point primitive objects.
  2402. Example: @code
  2403. Array <double> myArray;
  2404. FloatElementComparator<double> sorter;
  2405. myArray.sort (sorter);
  2406. @endcode
  2407. For integer values, see the IntegerElementComparator class instead.
  2408. @see IntegerElementComparator, ElementComparator
  2409. */
  2410. template <class ElementType>
  2411. class FloatElementComparator
  2412. {
  2413. public:
  2414. static int compareElements (const ElementType first,
  2415. const ElementType second) throw()
  2416. {
  2417. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2418. }
  2419. };
  2420. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2421. /********* End of inlined file: juce_ElementComparator.h *********/
  2422. /********* Start of inlined file: juce_CriticalSection.h *********/
  2423. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2424. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2425. /**
  2426. Prevents multiple threads from accessing shared objects at the same time.
  2427. @see ScopedLock, Thread, InterProcessLock
  2428. */
  2429. class JUCE_API CriticalSection
  2430. {
  2431. public:
  2432. /**
  2433. Creates a CriticalSection object
  2434. */
  2435. CriticalSection() throw();
  2436. /** Destroys a CriticalSection object.
  2437. If the critical section is deleted whilst locked, its subsequent behaviour
  2438. is unpredictable.
  2439. */
  2440. ~CriticalSection() throw();
  2441. /** Locks this critical section.
  2442. If the lock is currently held by another thread, this will wait until it
  2443. becomes free.
  2444. If the lock is already held by the caller thread, the method returns immediately.
  2445. @see exit, ScopedLock
  2446. */
  2447. void enter() const throw();
  2448. /** Attempts to lock this critical section without blocking.
  2449. This method behaves identically to CriticalSection::enter, except that the caller thread
  2450. does not wait if the lock is currently held by another thread but returns false immediately.
  2451. @returns false if the lock is currently held by another thread, true otherwise.
  2452. @see enter
  2453. */
  2454. bool tryEnter() const throw();
  2455. /** Releases the lock.
  2456. If the caller thread hasn't got the lock, this can have unpredictable results.
  2457. If the enter() method has been called multiple times by the thread, each
  2458. call must be matched by a call to exit() before other threads will be allowed
  2459. to take over the lock.
  2460. @see enter, ScopedLock
  2461. */
  2462. void exit() const throw();
  2463. juce_UseDebuggingNewOperator
  2464. private:
  2465. #if JUCE_WIN32
  2466. #if JUCE_64BIT
  2467. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2468. // block of memory here that's big enough to be used internally as a windows critical
  2469. // section object.
  2470. uint8 internal [44];
  2471. #else
  2472. uint8 internal [24];
  2473. #endif
  2474. #else
  2475. mutable pthread_mutex_t internal;
  2476. #endif
  2477. CriticalSection (const CriticalSection&);
  2478. const CriticalSection& operator= (const CriticalSection&);
  2479. };
  2480. /**
  2481. A class that can be used in place of a real CriticalSection object.
  2482. This is currently used by some templated array classes, and should get
  2483. optimised out by the compiler.
  2484. @see Array, OwnedArray, ReferenceCountedArray
  2485. */
  2486. class JUCE_API DummyCriticalSection
  2487. {
  2488. public:
  2489. forcedinline DummyCriticalSection() throw() {}
  2490. forcedinline ~DummyCriticalSection() throw() {}
  2491. forcedinline void enter() const throw() {}
  2492. forcedinline void exit() const throw() {}
  2493. };
  2494. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2495. /********* End of inlined file: juce_CriticalSection.h *********/
  2496. /** An array designed for holding objects.
  2497. This holds a list of pointers to objects, and will automatically
  2498. delete the objects when they are removed from the array, or when the
  2499. array is itself deleted.
  2500. Declare it in the form: OwnedArray<MyObjectClass>
  2501. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  2502. After adding objects, they are 'owned' by the array and will be deleted when
  2503. removed or replaced.
  2504. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2505. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2506. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  2507. */
  2508. template <class ObjectClass,
  2509. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2510. class OwnedArray : private ArrayAllocationBase <ObjectClass*>
  2511. {
  2512. public:
  2513. /** Creates an empty array.
  2514. @param granularity this is the size of increment by which the internal storage
  2515. used by the array will grow. Only change it from the default if you know the
  2516. array is going to be very big and needs to be able to grow efficiently.
  2517. @see ArrayAllocationBase
  2518. */
  2519. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  2520. : ArrayAllocationBase <ObjectClass*> (granularity),
  2521. numUsed (0)
  2522. {
  2523. }
  2524. /** Deletes the array and also deletes any objects inside it.
  2525. To get rid of the array without deleting its objects, use its
  2526. clear (false) method before deleting it.
  2527. */
  2528. ~OwnedArray()
  2529. {
  2530. clear (true);
  2531. }
  2532. /** Clears the array, optionally deleting the objects inside it first. */
  2533. void clear (const bool deleteObjects = true)
  2534. {
  2535. lock.enter();
  2536. if (deleteObjects)
  2537. {
  2538. while (numUsed > 0)
  2539. delete this->elements [--numUsed];
  2540. }
  2541. this->setAllocatedSize (0);
  2542. numUsed = 0;
  2543. lock.exit();
  2544. }
  2545. /** Returns the number of items currently in the array.
  2546. @see operator[]
  2547. */
  2548. inline int size() const throw()
  2549. {
  2550. return numUsed;
  2551. }
  2552. /** Returns a pointer to the object at this index in the array.
  2553. If the index is out-of-range, this will return a null pointer, (and
  2554. it could be null anyway, because it's ok for the array to hold null
  2555. pointers as well as objects).
  2556. @see getUnchecked
  2557. */
  2558. inline ObjectClass* operator[] (const int index) const throw()
  2559. {
  2560. lock.enter();
  2561. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  2562. ? this->elements [index]
  2563. : (ObjectClass*) 0;
  2564. lock.exit();
  2565. return result;
  2566. }
  2567. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  2568. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  2569. it can be used when you're sure the index if always going to be legal.
  2570. */
  2571. inline ObjectClass* getUnchecked (const int index) const throw()
  2572. {
  2573. lock.enter();
  2574. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2575. ObjectClass* const result = this->elements [index];
  2576. lock.exit();
  2577. return result;
  2578. }
  2579. /** Returns a pointer to the first object in the array.
  2580. This will return a null pointer if the array's empty.
  2581. @see getLast
  2582. */
  2583. inline ObjectClass* getFirst() const throw()
  2584. {
  2585. lock.enter();
  2586. ObjectClass* const result = (numUsed > 0) ? this->elements [0]
  2587. : (ObjectClass*) 0;
  2588. lock.exit();
  2589. return result;
  2590. }
  2591. /** Returns a pointer to the last object in the array.
  2592. This will return a null pointer if the array's empty.
  2593. @see getFirst
  2594. */
  2595. inline ObjectClass* getLast() const throw()
  2596. {
  2597. lock.enter();
  2598. ObjectClass* const result = (numUsed > 0) ? this->elements [numUsed - 1]
  2599. : (ObjectClass*) 0;
  2600. lock.exit();
  2601. return result;
  2602. }
  2603. /** Finds the index of an object which might be in the array.
  2604. @param objectToLookFor the object to look for
  2605. @returns the index at which the object was found, or -1 if it's not found
  2606. */
  2607. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  2608. {
  2609. int result = -1;
  2610. lock.enter();
  2611. ObjectClass* const* e = this->elements;
  2612. for (int i = numUsed; --i >= 0;)
  2613. {
  2614. if (objectToLookFor == *e)
  2615. {
  2616. result = (int) (e - this->elements);
  2617. break;
  2618. }
  2619. ++e;
  2620. }
  2621. lock.exit();
  2622. return result;
  2623. }
  2624. /** Returns true if the array contains a specified object.
  2625. @param objectToLookFor the object to look for
  2626. @returns true if the object is in the array
  2627. */
  2628. bool contains (const ObjectClass* const objectToLookFor) const throw()
  2629. {
  2630. lock.enter();
  2631. ObjectClass* const* e = this->elements;
  2632. int i = numUsed;
  2633. while (i >= 4)
  2634. {
  2635. if (objectToLookFor == *e
  2636. || objectToLookFor == *++e
  2637. || objectToLookFor == *++e
  2638. || objectToLookFor == *++e)
  2639. {
  2640. lock.exit();
  2641. return true;
  2642. }
  2643. i -= 4;
  2644. ++e;
  2645. }
  2646. while (i > 0)
  2647. {
  2648. if (objectToLookFor == *e)
  2649. {
  2650. lock.exit();
  2651. return true;
  2652. }
  2653. --i;
  2654. ++e;
  2655. }
  2656. lock.exit();
  2657. return false;
  2658. }
  2659. /** Appends a new object to the end of the array.
  2660. Note that the this object will be deleted by the OwnedArray when it
  2661. is removed, so be careful not to delete it somewhere else.
  2662. Also be careful not to add the same object to the array more than once,
  2663. as this will obviously cause deletion of dangling pointers.
  2664. @param newObject the new object to add to the array
  2665. @see set, insert, addIfNotAlreadyThere, addSorted
  2666. */
  2667. void add (const ObjectClass* const newObject) throw()
  2668. {
  2669. lock.enter();
  2670. this->ensureAllocatedSize (numUsed + 1);
  2671. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2672. lock.exit();
  2673. }
  2674. /** Inserts a new object into the array at the given index.
  2675. Note that the this object will be deleted by the OwnedArray when it
  2676. is removed, so be careful not to delete it somewhere else.
  2677. If the index is less than 0 or greater than the size of the array, the
  2678. element will be added to the end of the array.
  2679. Otherwise, it will be inserted into the array, moving all the later elements
  2680. along to make room.
  2681. Be careful not to add the same object to the array more than once,
  2682. as this will obviously cause deletion of dangling pointers.
  2683. @param indexToInsertAt the index at which the new element should be inserted
  2684. @param newObject the new object to add to the array
  2685. @see add, addSorted, addIfNotAlreadyThere, set
  2686. */
  2687. void insert (int indexToInsertAt,
  2688. const ObjectClass* const newObject) throw()
  2689. {
  2690. if (indexToInsertAt >= 0)
  2691. {
  2692. lock.enter();
  2693. if (indexToInsertAt > numUsed)
  2694. indexToInsertAt = numUsed;
  2695. this->ensureAllocatedSize (numUsed + 1);
  2696. ObjectClass** const e = this->elements + indexToInsertAt;
  2697. const int numToMove = numUsed - indexToInsertAt;
  2698. if (numToMove > 0)
  2699. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  2700. *e = const_cast <ObjectClass*> (newObject);
  2701. ++numUsed;
  2702. lock.exit();
  2703. }
  2704. else
  2705. {
  2706. add (newObject);
  2707. }
  2708. }
  2709. /** Appends a new object at the end of the array as long as the array doesn't
  2710. already contain it.
  2711. If the array already contains a matching object, nothing will be done.
  2712. @param newObject the new object to add to the array
  2713. */
  2714. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  2715. {
  2716. lock.enter();
  2717. if (! contains (newObject))
  2718. add (newObject);
  2719. lock.exit();
  2720. }
  2721. /** Replaces an object in the array with a different one.
  2722. If the index is less than zero, this method does nothing.
  2723. If the index is beyond the end of the array, the new object is added to the end of the array.
  2724. Be careful not to add the same object to the array more than once,
  2725. as this will obviously cause deletion of dangling pointers.
  2726. @param indexToChange the index whose value you want to change
  2727. @param newObject the new value to set for this index.
  2728. @param deleteOldElement whether to delete the object that's being replaced with the new one
  2729. @see add, insert, remove
  2730. */
  2731. void set (const int indexToChange,
  2732. const ObjectClass* const newObject,
  2733. const bool deleteOldElement = true)
  2734. {
  2735. if (indexToChange >= 0)
  2736. {
  2737. ObjectClass* toDelete = 0;
  2738. lock.enter();
  2739. if (indexToChange < numUsed)
  2740. {
  2741. if (deleteOldElement)
  2742. {
  2743. toDelete = this->elements [indexToChange];
  2744. if (toDelete == newObject)
  2745. toDelete = 0;
  2746. }
  2747. this->elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  2748. }
  2749. else
  2750. {
  2751. this->ensureAllocatedSize (numUsed + 1);
  2752. this->elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  2753. }
  2754. lock.exit();
  2755. delete toDelete;
  2756. }
  2757. }
  2758. /** Inserts a new object into the array assuming that the array is sorted.
  2759. This will use a comparator to find the position at which the new object
  2760. should go. If the array isn't sorted, the behaviour of this
  2761. method will be unpredictable.
  2762. @param comparator the comparator to use to compare the elements - see the sort method
  2763. for details about this object's structure
  2764. @param newObject the new object to insert to the array
  2765. @see add, sort, indexOfSorted
  2766. */
  2767. template <class ElementComparator>
  2768. void addSorted (ElementComparator& comparator,
  2769. ObjectClass* const newObject) throw()
  2770. {
  2771. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2772. // avoids getting warning messages about the parameter being unused
  2773. lock.enter();
  2774. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  2775. lock.exit();
  2776. }
  2777. /** Finds the index of an object in the array, assuming that the array is sorted.
  2778. This will use a comparator to do a binary-chop to find the index of the given
  2779. element, if it exists. If the array isn't sorted, the behaviour of this
  2780. method will be unpredictable.
  2781. @param comparator the comparator to use to compare the elements - see the sort()
  2782. method for details about the form this object should take
  2783. @param objectToLookFor the object to search for
  2784. @returns the index of the element, or -1 if it's not found
  2785. @see addSorted, sort
  2786. */
  2787. template <class ElementComparator>
  2788. int indexOfSorted (ElementComparator& comparator,
  2789. const ObjectClass* const objectToLookFor) const throw()
  2790. {
  2791. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2792. // avoids getting warning messages about the parameter being unused
  2793. lock.enter();
  2794. int start = 0;
  2795. int end = numUsed;
  2796. for (;;)
  2797. {
  2798. if (start >= end)
  2799. {
  2800. lock.exit();
  2801. return -1;
  2802. }
  2803. else if (comparator.compareElements (objectToLookFor, this->elements [start]) == 0)
  2804. {
  2805. lock.exit();
  2806. return start;
  2807. }
  2808. else
  2809. {
  2810. const int halfway = (start + end) >> 1;
  2811. if (halfway == start)
  2812. {
  2813. lock.exit();
  2814. return -1;
  2815. }
  2816. else if (comparator.compareElements (objectToLookFor, this->elements [halfway]) >= 0)
  2817. start = halfway;
  2818. else
  2819. end = halfway;
  2820. }
  2821. }
  2822. }
  2823. /** Removes an object from the array.
  2824. This will remove the object at a given index (optionally also
  2825. deleting it) and move back all the subsequent objects to close the gap.
  2826. If the index passed in is out-of-range, nothing will happen.
  2827. @param indexToRemove the index of the element to remove
  2828. @param deleteObject whether to delete the object that is removed
  2829. @see removeObject, removeRange
  2830. */
  2831. void remove (const int indexToRemove,
  2832. const bool deleteObject = true)
  2833. {
  2834. lock.enter();
  2835. ObjectClass* toDelete = 0;
  2836. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2837. {
  2838. ObjectClass** const e = this->elements + indexToRemove;
  2839. if (deleteObject)
  2840. toDelete = *e;
  2841. --numUsed;
  2842. const int numToShift = numUsed - indexToRemove;
  2843. if (numToShift > 0)
  2844. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  2845. if ((numUsed << 1) < this->numAllocated)
  2846. minimiseStorageOverheads();
  2847. }
  2848. lock.exit();
  2849. delete toDelete;
  2850. }
  2851. /** Removes a specified object from the array.
  2852. If the item isn't found, no action is taken.
  2853. @param objectToRemove the object to try to remove
  2854. @param deleteObject whether to delete the object (if it's found)
  2855. @see remove, removeRange
  2856. */
  2857. void removeObject (const ObjectClass* const objectToRemove,
  2858. const bool deleteObject = true)
  2859. {
  2860. lock.enter();
  2861. ObjectClass** e = this->elements;
  2862. for (int i = numUsed; --i >= 0;)
  2863. {
  2864. if (objectToRemove == *e)
  2865. {
  2866. remove ((int) (e - this->elements), deleteObject);
  2867. break;
  2868. }
  2869. ++e;
  2870. }
  2871. lock.exit();
  2872. }
  2873. /** Removes a range of objects from the array.
  2874. This will remove a set of objects, starting from the given index,
  2875. and move any subsequent elements down to close the gap.
  2876. If the range extends beyond the bounds of the array, it will
  2877. be safely clipped to the size of the array.
  2878. @param startIndex the index of the first object to remove
  2879. @param numberToRemove how many objects should be removed
  2880. @param deleteObjects whether to delete the objects that get removed
  2881. @see remove, removeObject
  2882. */
  2883. void removeRange (int startIndex,
  2884. const int numberToRemove,
  2885. const bool deleteObjects = true)
  2886. {
  2887. lock.enter();
  2888. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  2889. startIndex = jlimit (0, numUsed, startIndex);
  2890. if (endIndex > startIndex)
  2891. {
  2892. if (deleteObjects)
  2893. {
  2894. for (int i = startIndex; i < endIndex; ++i)
  2895. {
  2896. delete this->elements [i];
  2897. this->elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  2898. }
  2899. }
  2900. const int rangeSize = endIndex - startIndex;
  2901. ObjectClass** e = this->elements + startIndex;
  2902. int numToShift = numUsed - endIndex;
  2903. numUsed -= rangeSize;
  2904. while (--numToShift >= 0)
  2905. {
  2906. *e = e [rangeSize];
  2907. ++e;
  2908. }
  2909. if ((numUsed << 1) < this->numAllocated)
  2910. minimiseStorageOverheads();
  2911. }
  2912. lock.exit();
  2913. }
  2914. /** Removes the last n objects from the array.
  2915. @param howManyToRemove how many objects to remove from the end of the array
  2916. @param deleteObjects whether to also delete the objects that are removed
  2917. @see remove, removeObject, removeRange
  2918. */
  2919. void removeLast (int howManyToRemove = 1,
  2920. const bool deleteObjects = true)
  2921. {
  2922. lock.enter();
  2923. if (howManyToRemove >= numUsed)
  2924. {
  2925. clear (deleteObjects);
  2926. }
  2927. else
  2928. {
  2929. while (--howManyToRemove >= 0)
  2930. remove (numUsed - 1, deleteObjects);
  2931. }
  2932. lock.exit();
  2933. }
  2934. /** Swaps a pair of objects in the array.
  2935. If either of the indexes passed in is out-of-range, nothing will happen,
  2936. otherwise the two objects at these positions will be exchanged.
  2937. */
  2938. void swap (const int index1,
  2939. const int index2) throw()
  2940. {
  2941. lock.enter();
  2942. if (((unsigned int) index1) < (unsigned int) numUsed
  2943. && ((unsigned int) index2) < (unsigned int) numUsed)
  2944. {
  2945. swapVariables (this->elements [index1],
  2946. this->elements [index2]);
  2947. }
  2948. lock.exit();
  2949. }
  2950. /** Moves one of the objects to a different position.
  2951. This will move the object to a specified index, shuffling along
  2952. any intervening elements as required.
  2953. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  2954. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  2955. @param currentIndex the index of the object to be moved. If this isn't a
  2956. valid index, then nothing will be done
  2957. @param newIndex the index at which you'd like this object to end up. If this
  2958. is less than zero, it will be moved to the end of the array
  2959. */
  2960. void move (const int currentIndex,
  2961. int newIndex) throw()
  2962. {
  2963. if (currentIndex != newIndex)
  2964. {
  2965. lock.enter();
  2966. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  2967. {
  2968. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  2969. newIndex = numUsed - 1;
  2970. ObjectClass* const value = this->elements [currentIndex];
  2971. if (newIndex > currentIndex)
  2972. {
  2973. memmove (this->elements + currentIndex,
  2974. this->elements + currentIndex + 1,
  2975. (newIndex - currentIndex) * sizeof (ObjectClass*));
  2976. }
  2977. else
  2978. {
  2979. memmove (this->elements + newIndex + 1,
  2980. this->elements + newIndex,
  2981. (currentIndex - newIndex) * sizeof (ObjectClass*));
  2982. }
  2983. this->elements [newIndex] = value;
  2984. }
  2985. lock.exit();
  2986. }
  2987. }
  2988. /** This swaps the contents of this array with those of another array.
  2989. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2990. because it just swaps their internal pointers.
  2991. */
  2992. template <class OtherArrayType>
  2993. void swapWithArray (OtherArrayType& otherArray) throw()
  2994. {
  2995. lock.enter();
  2996. otherArray.lock.enter();
  2997. swapVariables <int> (this->numUsed, otherArray.numUsed);
  2998. swapVariables <ObjectClass**> (this->elements, otherArray.elements);
  2999. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3000. otherArray.lock.exit();
  3001. lock.exit();
  3002. }
  3003. /** Reduces the amount of storage being used by the array.
  3004. Arrays typically allocate slightly more storage than they need, and after
  3005. removing elements, they may have quite a lot of unused space allocated.
  3006. This method will reduce the amount of allocated storage to a minimum.
  3007. */
  3008. void minimiseStorageOverheads() throw()
  3009. {
  3010. lock.enter();
  3011. if (numUsed == 0)
  3012. {
  3013. this->setAllocatedSize (0);
  3014. }
  3015. else
  3016. {
  3017. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  3018. if (newAllocation < this->numAllocated)
  3019. this->setAllocatedSize (newAllocation);
  3020. }
  3021. lock.exit();
  3022. }
  3023. /** Increases the array's internal storage to hold a minimum number of elements.
  3024. Calling this before adding a large known number of elements means that
  3025. the array won't have to keep dynamically resizing itself as the elements
  3026. are added, and it'll therefore be more efficient.
  3027. */
  3028. void ensureStorageAllocated (const int minNumElements) throw()
  3029. {
  3030. this->ensureAllocatedSize (minNumElements);
  3031. }
  3032. /** Sorts the elements in the array.
  3033. This will use a comparator object to sort the elements into order. The object
  3034. passed must have a method of the form:
  3035. @code
  3036. int compareElements (ElementType first, ElementType second);
  3037. @endcode
  3038. ..and this method must return:
  3039. - a value of < 0 if the first comes before the second
  3040. - a value of 0 if the two objects are equivalent
  3041. - a value of > 0 if the second comes before the first
  3042. To improve performance, the compareElements() method can be declared as static or const.
  3043. @param comparator the comparator to use for comparing elements.
  3044. @param retainOrderOfEquivalentItems if this is true, then items
  3045. which the comparator says are equivalent will be
  3046. kept in the order in which they currently appear
  3047. in the array. This is slower to perform, but may
  3048. be important in some cases. If it's false, a faster
  3049. algorithm is used, but equivalent elements may be
  3050. rearranged.
  3051. @see sortArray, indexOfSorted
  3052. */
  3053. template <class ElementComparator>
  3054. void sort (ElementComparator& comparator,
  3055. const bool retainOrderOfEquivalentItems = false) const throw()
  3056. {
  3057. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3058. // avoids getting warning messages about the parameter being unused
  3059. lock.enter();
  3060. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3061. lock.exit();
  3062. }
  3063. /** Locks the array's CriticalSection.
  3064. Of course if the type of section used is a DummyCriticalSection, this won't
  3065. have any effect.
  3066. @see unlockArray
  3067. */
  3068. void lockArray() const throw()
  3069. {
  3070. lock.enter();
  3071. }
  3072. /** Unlocks the array's CriticalSection.
  3073. Of course if the type of section used is a DummyCriticalSection, this won't
  3074. have any effect.
  3075. @see lockArray
  3076. */
  3077. void unlockArray() const throw()
  3078. {
  3079. lock.exit();
  3080. }
  3081. juce_UseDebuggingNewOperator
  3082. private:
  3083. int numUsed;
  3084. TypeOfCriticalSectionToUse lock;
  3085. // disallow copy constructor and assignment
  3086. OwnedArray (const OwnedArray&);
  3087. const OwnedArray& operator= (const OwnedArray&);
  3088. };
  3089. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  3090. /********* End of inlined file: juce_OwnedArray.h *********/
  3091. /********* Start of inlined file: juce_Time.h *********/
  3092. #ifndef __JUCE_TIME_JUCEHEADER__
  3093. #define __JUCE_TIME_JUCEHEADER__
  3094. /********* Start of inlined file: juce_RelativeTime.h *********/
  3095. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  3096. #define __JUCE_RELATIVETIME_JUCEHEADER__
  3097. /** A relative measure of time.
  3098. The time is stored as a number of seconds, at double-precision floating
  3099. point accuracy, and may be positive or negative.
  3100. If you need an absolute time, (i.e. a date + time), see the Time class.
  3101. */
  3102. class JUCE_API RelativeTime
  3103. {
  3104. public:
  3105. /** Creates a RelativeTime.
  3106. @param seconds the number of seconds, which may be +ve or -ve.
  3107. @see milliseconds, minutes, hours, days, weeks
  3108. */
  3109. explicit RelativeTime (const double seconds = 0.0) throw();
  3110. /** Copies another relative time. */
  3111. RelativeTime (const RelativeTime& other) throw();
  3112. /** Copies another relative time. */
  3113. const RelativeTime& operator= (const RelativeTime& other) throw();
  3114. /** Destructor. */
  3115. ~RelativeTime() throw();
  3116. /** Creates a new RelativeTime object representing a number of milliseconds.
  3117. @see minutes, hours, days, weeks
  3118. */
  3119. static const RelativeTime milliseconds (const int milliseconds) throw();
  3120. /** Creates a new RelativeTime object representing a number of milliseconds.
  3121. @see minutes, hours, days, weeks
  3122. */
  3123. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  3124. /** Creates a new RelativeTime object representing a number of minutes.
  3125. @see milliseconds, hours, days, weeks
  3126. */
  3127. static const RelativeTime minutes (const double numberOfMinutes) throw();
  3128. /** Creates a new RelativeTime object representing a number of hours.
  3129. @see milliseconds, minutes, days, weeks
  3130. */
  3131. static const RelativeTime hours (const double numberOfHours) throw();
  3132. /** Creates a new RelativeTime object representing a number of days.
  3133. @see milliseconds, minutes, hours, weeks
  3134. */
  3135. static const RelativeTime days (const double numberOfDays) throw();
  3136. /** Creates a new RelativeTime object representing a number of weeks.
  3137. @see milliseconds, minutes, hours, days
  3138. */
  3139. static const RelativeTime weeks (const double numberOfWeeks) throw();
  3140. /** Returns the number of milliseconds this time represents.
  3141. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3142. */
  3143. int64 inMilliseconds() const throw();
  3144. /** Returns the number of seconds this time represents.
  3145. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  3146. */
  3147. double inSeconds() const throw() { return seconds; }
  3148. /** Returns the number of minutes this time represents.
  3149. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  3150. */
  3151. double inMinutes() const throw();
  3152. /** Returns the number of hours this time represents.
  3153. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  3154. */
  3155. double inHours() const throw();
  3156. /** Returns the number of days this time represents.
  3157. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  3158. */
  3159. double inDays() const throw();
  3160. /** Returns the number of weeks this time represents.
  3161. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  3162. */
  3163. double inWeeks() const throw();
  3164. /** Returns a readable textual description of the time.
  3165. The exact format of the string returned will depend on
  3166. the magnitude of the time - e.g.
  3167. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  3168. so that only the two most significant units are printed.
  3169. The returnValueForZeroTime value is the result that is returned if the
  3170. length is zero. Depending on your application you might want to use this
  3171. to return something more relevant like "empty" or "0 secs", etc.
  3172. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  3173. */
  3174. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) 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. /** Compares two RelativeTimes. */
  3182. bool operator< (const RelativeTime& other) const throw();
  3183. /** Compares two RelativeTimes. */
  3184. bool operator>= (const RelativeTime& other) const throw();
  3185. /** Compares two RelativeTimes. */
  3186. bool operator<= (const RelativeTime& other) const throw();
  3187. /** Adds another RelativeTime to this one and returns the result. */
  3188. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  3189. /** Subtracts another RelativeTime from this one and returns the result. */
  3190. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  3191. /** Adds a number of seconds to this RelativeTime and returns the result. */
  3192. const RelativeTime operator+ (const double secondsToAdd) const throw();
  3193. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  3194. const RelativeTime operator- (const double secondsToSubtract) const throw();
  3195. /** Adds another RelativeTime to this one. */
  3196. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  3197. /** Subtracts another RelativeTime from this one. */
  3198. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  3199. /** Adds a number of seconds to this time. */
  3200. const RelativeTime& operator+= (const double secondsToAdd) throw();
  3201. /** Subtracts a number of seconds from this time. */
  3202. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  3203. juce_UseDebuggingNewOperator
  3204. private:
  3205. double seconds;
  3206. };
  3207. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  3208. /********* End of inlined file: juce_RelativeTime.h *********/
  3209. /**
  3210. Holds an absolute date and time.
  3211. Internally, the time is stored at millisecond precision.
  3212. @see RelativeTime
  3213. */
  3214. class JUCE_API Time
  3215. {
  3216. public:
  3217. /** Creates a Time object.
  3218. This default constructor creates a time of 1st January 1970, (which is
  3219. represented internally as 0ms).
  3220. To create a time object representing the current time, use getCurrentTime().
  3221. @see getCurrentTime
  3222. */
  3223. Time() throw();
  3224. /** Creates a copy of another Time object. */
  3225. Time (const Time& other) throw();
  3226. /** Creates a time based on a number of milliseconds.
  3227. The internal millisecond count is set to 0 (1st January 1970). To create a
  3228. time object set to the current time, use getCurrentTime().
  3229. @param millisecondsSinceEpoch the number of milliseconds since the unix
  3230. 'epoch' (midnight Jan 1st 1970).
  3231. @see getCurrentTime, currentTimeMillis
  3232. */
  3233. Time (const int64 millisecondsSinceEpoch) throw();
  3234. /** Creates a time from a set of date components.
  3235. The timezone is assumed to be whatever the system is using as its locale.
  3236. @param year the year, in 4-digit format, e.g. 2004
  3237. @param month the month, in the range 0 to 11
  3238. @param day the day of the month, in the range 1 to 31
  3239. @param hours hours in 24-hour clock format, 0 to 23
  3240. @param minutes minutes 0 to 59
  3241. @param seconds seconds 0 to 59
  3242. @param milliseconds milliseconds 0 to 999
  3243. @param useLocalTime if true, encode using the current machine's local time; if
  3244. false, it will always work in GMT.
  3245. */
  3246. Time (const int year,
  3247. const int month,
  3248. const int day,
  3249. const int hours,
  3250. const int minutes,
  3251. const int seconds = 0,
  3252. const int milliseconds = 0,
  3253. const bool useLocalTime = true) throw();
  3254. /** Destructor. */
  3255. ~Time() throw();
  3256. /** Copies this time from another one. */
  3257. const Time& operator= (const Time& other) throw();
  3258. /** Returns a Time object that is set to the current system time.
  3259. @see currentTimeMillis
  3260. */
  3261. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  3262. /** Returns the time as a number of milliseconds.
  3263. @returns the number of milliseconds this Time object represents, since
  3264. midnight jan 1st 1970.
  3265. @see getMilliseconds
  3266. */
  3267. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  3268. /** Returns the year.
  3269. A 4-digit format is used, e.g. 2004.
  3270. */
  3271. int getYear() const throw();
  3272. /** Returns the number of the month.
  3273. The value returned is in the range 0 to 11.
  3274. @see getMonthName
  3275. */
  3276. int getMonth() const throw();
  3277. /** Returns the name of the month.
  3278. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3279. it'll return the long form, e.g. "January"
  3280. @see getMonth
  3281. */
  3282. const String getMonthName (const bool threeLetterVersion) const throw();
  3283. /** Returns the day of the month.
  3284. The value returned is in the range 1 to 31.
  3285. */
  3286. int getDayOfMonth() const throw();
  3287. /** Returns the number of the day of the week.
  3288. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  3289. */
  3290. int getDayOfWeek() const throw();
  3291. /** Returns the name of the weekday.
  3292. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3293. false, it'll return the full version, e.g. "Tuesday".
  3294. */
  3295. const String getWeekdayName (const bool threeLetterVersion) const throw();
  3296. /** Returns the number of hours since midnight.
  3297. This is in 24-hour clock format, in the range 0 to 23.
  3298. @see getHoursInAmPmFormat, isAfternoon
  3299. */
  3300. int getHours() const throw();
  3301. /** Returns true if the time is in the afternoon.
  3302. So it returns true for "PM", false for "AM".
  3303. @see getHoursInAmPmFormat, getHours
  3304. */
  3305. bool isAfternoon() const throw();
  3306. /** Returns the hours in 12-hour clock format.
  3307. This will return a value 1 to 12 - use isAfternoon() to find out
  3308. whether this is in the afternoon or morning.
  3309. @see getHours, isAfternoon
  3310. */
  3311. int getHoursInAmPmFormat() const throw();
  3312. /** Returns the number of minutes, 0 to 59. */
  3313. int getMinutes() const throw();
  3314. /** Returns the number of seconds, 0 to 59. */
  3315. int getSeconds() const throw();
  3316. /** Returns the number of milliseconds, 0 to 999.
  3317. Unlike toMilliseconds(), this just returns the position within the
  3318. current second rather than the total number since the epoch.
  3319. @see toMilliseconds
  3320. */
  3321. int getMilliseconds() const throw();
  3322. /** Returns true if the local timezone uses a daylight saving correction. */
  3323. bool isDaylightSavingTime() const throw();
  3324. /** Returns a 3-character string to indicate the local timezone. */
  3325. const String getTimeZone() const throw();
  3326. /** Quick way of getting a string version of a date and time.
  3327. For a more powerful way of formatting the date and time, see the formatted() method.
  3328. @param includeDate whether to include the date in the string
  3329. @param includeTime whether to include the time in the string
  3330. @param includeSeconds if the time is being included, this provides an option not to include
  3331. the seconds in it
  3332. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  3333. hour notation.
  3334. @see formatted
  3335. */
  3336. const String toString (const bool includeDate,
  3337. const bool includeTime,
  3338. const bool includeSeconds = true,
  3339. const bool use24HourClock = false) const throw();
  3340. /** Converts this date/time to a string with a user-defined format.
  3341. This uses the C strftime() function to format this time as a string. To save you
  3342. looking it up, these are the escape codes that strftime uses (other codes might
  3343. work on some platforms and not others, but these are the common ones):
  3344. %a is replaced by the locale's abbreviated weekday name.
  3345. %A is replaced by the locale's full weekday name.
  3346. %b is replaced by the locale's abbreviated month name.
  3347. %B is replaced by the locale's full month name.
  3348. %c is replaced by the locale's appropriate date and time representation.
  3349. %d is replaced by the day of the month as a decimal number [01,31].
  3350. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  3351. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  3352. %j is replaced by the day of the year as a decimal number [001,366].
  3353. %m is replaced by the month as a decimal number [01,12].
  3354. %M is replaced by the minute as a decimal number [00,59].
  3355. %p is replaced by the locale's equivalent of either a.m. or p.m.
  3356. %S is replaced by the second as a decimal number [00,61].
  3357. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  3358. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  3359. %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.
  3360. %x is replaced by the locale's appropriate date representation.
  3361. %X is replaced by the locale's appropriate time representation.
  3362. %y is replaced by the year without century as a decimal number [00,99].
  3363. %Y is replaced by the year with century as a decimal number.
  3364. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  3365. %% is replaced by %.
  3366. @see toString
  3367. */
  3368. const String formatted (const tchar* const format) const throw();
  3369. /** Adds a RelativeTime to this time and returns the result. */
  3370. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  3371. /** Subtracts a RelativeTime from this time and returns the result. */
  3372. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  3373. /** Returns the relative time difference between this time and another one. */
  3374. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (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. /** Compares two Time objects. */
  3382. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  3383. /** Compares two Time objects. */
  3384. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  3385. /** Compares two Time objects. */
  3386. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  3387. /** Tries to set the computer's clock.
  3388. @returns true if this succeeds, although depending on the system, the
  3389. application might not have sufficient privileges to do this.
  3390. */
  3391. bool setSystemTimeToThisTime() const throw();
  3392. /** Returns the name of a day of the week.
  3393. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  3394. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  3395. false, it'll return the full version, e.g. "Tuesday".
  3396. */
  3397. static const String getWeekdayName (int dayNumber,
  3398. const bool threeLetterVersion) throw();
  3399. /** Returns the name of one of the months.
  3400. @param monthNumber the month, 0 to 11
  3401. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  3402. it'll return the long form, e.g. "January"
  3403. */
  3404. static const String getMonthName (int monthNumber,
  3405. const bool threeLetterVersion) throw();
  3406. // Static methods for getting system timers directly..
  3407. /** Returns the current system time.
  3408. Returns the number of milliseconds since midnight jan 1st 1970.
  3409. Should be accurate to within a few millisecs, depending on platform,
  3410. hardware, etc.
  3411. */
  3412. static int64 currentTimeMillis() throw();
  3413. /** Returns the number of millisecs since system startup.
  3414. Should be accurate to within a few millisecs, depending on platform,
  3415. hardware, etc.
  3416. @see getApproximateMillisecondCounter
  3417. */
  3418. static uint32 getMillisecondCounter() throw();
  3419. /** Returns the number of millisecs since system startup.
  3420. Same as getMillisecondCounter(), but returns a more accurate value, using
  3421. the high-res timer.
  3422. @see getMillisecondCounter
  3423. */
  3424. static double getMillisecondCounterHiRes() throw();
  3425. /** Waits until the getMillisecondCounter() reaches a given value.
  3426. This will make the thread sleep as efficiently as it can while it's waiting.
  3427. */
  3428. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  3429. /** Less-accurate but faster version of getMillisecondCounter().
  3430. This will return the last value that getMillisecondCounter() returned, so doesn't
  3431. need to make a system call, but is less accurate - it shouldn't be more than
  3432. 100ms away from the correct time, though, so is still accurate enough for a
  3433. lot of purposes.
  3434. @see getMillisecondCounter
  3435. */
  3436. static uint32 getApproximateMillisecondCounter() throw();
  3437. // High-resolution timers..
  3438. /** Returns the current high-resolution counter's tick-count.
  3439. This is a similar idea to getMillisecondCounter(), but with a higher
  3440. resolution.
  3441. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  3442. secondsToHighResolutionTicks
  3443. */
  3444. static int64 getHighResolutionTicks() throw();
  3445. /** Returns the resolution of the high-resolution counter in ticks per second.
  3446. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  3447. secondsToHighResolutionTicks
  3448. */
  3449. static int64 getHighResolutionTicksPerSecond() throw();
  3450. /** Converts a number of high-resolution ticks into seconds.
  3451. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3452. secondsToHighResolutionTicks
  3453. */
  3454. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  3455. /** Converts a number seconds into high-resolution ticks.
  3456. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  3457. highResolutionTicksToSeconds
  3458. */
  3459. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  3460. private:
  3461. int64 millisSinceEpoch;
  3462. };
  3463. #endif // __JUCE_TIME_JUCEHEADER__
  3464. /********* End of inlined file: juce_Time.h *********/
  3465. /********* Start of inlined file: juce_StringArray.h *********/
  3466. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  3467. #define __JUCE_STRINGARRAY_JUCEHEADER__
  3468. /********* Start of inlined file: juce_VoidArray.h *********/
  3469. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  3470. #define __JUCE_VOIDARRAY_JUCEHEADER__
  3471. /********* Start of inlined file: juce_Array.h *********/
  3472. #ifndef __JUCE_ARRAY_JUCEHEADER__
  3473. #define __JUCE_ARRAY_JUCEHEADER__
  3474. /**
  3475. Holds a list of primitive objects, such as ints, doubles, or pointers.
  3476. Examples of arrays are: Array<int> or Array<MyClass*>
  3477. Note that when holding pointers to objects, the array doesn't take any ownership
  3478. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  3479. If you're using a class or struct as the element type, it must be
  3480. capable of being copied or moved with a straightforward memcpy, rather than
  3481. needing construction and destruction code.
  3482. For holding lists of strings, use the specialised class StringArray.
  3483. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3484. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3485. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  3486. */
  3487. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3488. class Array : private ArrayAllocationBase <ElementType>
  3489. {
  3490. public:
  3491. /** Creates an empty array.
  3492. @param granularity this is the size of increment by which the internal storage
  3493. used by the array will grow. Only change it from the default if you know the
  3494. array is going to be very big and needs to be able to grow efficiently.
  3495. @see ArrayAllocationBase
  3496. */
  3497. Array (const int granularity = juceDefaultArrayGranularity) throw()
  3498. : ArrayAllocationBase <ElementType> (granularity),
  3499. numUsed (0)
  3500. {
  3501. }
  3502. /** Creates a copy of another array.
  3503. @param other the array to copy
  3504. */
  3505. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3506. : ArrayAllocationBase <ElementType> (other.granularity)
  3507. {
  3508. other.lockArray();
  3509. numUsed = other.numUsed;
  3510. this->setAllocatedSize (other.numUsed);
  3511. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  3512. other.unlockArray();
  3513. }
  3514. /** Initalises from a null-terminated C array of values.
  3515. @param values the array to copy from
  3516. */
  3517. Array (const ElementType* values) throw()
  3518. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3519. numUsed (0)
  3520. {
  3521. while (*values != 0)
  3522. add (*values++);
  3523. }
  3524. /** Initalises from a C array of values.
  3525. @param values the array to copy from
  3526. @param numValues the number of values in the array
  3527. */
  3528. Array (const ElementType* values, int numValues) throw()
  3529. : ArrayAllocationBase <ElementType> (juceDefaultArrayGranularity),
  3530. numUsed (numValues)
  3531. {
  3532. this->setAllocatedSize (numValues);
  3533. memcpy (this->elements, values, numValues * sizeof (ElementType));
  3534. }
  3535. /** Destructor. */
  3536. ~Array() throw()
  3537. {
  3538. }
  3539. /** Copies another array.
  3540. @param other the array to copy
  3541. */
  3542. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  3543. {
  3544. if (this != &other)
  3545. {
  3546. other.lockArray();
  3547. lock.enter();
  3548. this->granularity = other.granularity;
  3549. this->ensureAllocatedSize (other.size());
  3550. numUsed = other.numUsed;
  3551. memcpy (this->elements, other.elements, this->numUsed * sizeof (ElementType));
  3552. minimiseStorageOverheads();
  3553. lock.exit();
  3554. other.unlockArray();
  3555. }
  3556. return *this;
  3557. }
  3558. /** Compares this array to another one.
  3559. Two arrays are considered equal if they both contain the same set of
  3560. elements, in the same order.
  3561. @param other the other array to compare with
  3562. */
  3563. template <class OtherArrayType>
  3564. bool operator== (const OtherArrayType& other) const throw()
  3565. {
  3566. lock.enter();
  3567. if (this->numUsed != other.numUsed)
  3568. {
  3569. lock.exit();
  3570. return false;
  3571. }
  3572. for (int i = numUsed; --i >= 0;)
  3573. {
  3574. if (this->elements [i] != other.elements [i])
  3575. {
  3576. lock.exit();
  3577. return false;
  3578. }
  3579. }
  3580. lock.exit();
  3581. return true;
  3582. }
  3583. /** Compares this array to another one.
  3584. Two arrays are considered equal if they both contain the same set of
  3585. elements, in the same order.
  3586. @param other the other array to compare with
  3587. */
  3588. template <class OtherArrayType>
  3589. bool operator!= (const OtherArrayType& other) const throw()
  3590. {
  3591. return ! operator== (other);
  3592. }
  3593. /** Removes all elements from the array.
  3594. This will remove all the elements, and free any storage that the array is
  3595. using. To clear the array without freeing the storage, use the clearQuick()
  3596. method instead.
  3597. @see clearQuick
  3598. */
  3599. void clear() throw()
  3600. {
  3601. lock.enter();
  3602. this->setAllocatedSize (0);
  3603. numUsed = 0;
  3604. lock.exit();
  3605. }
  3606. /** Removes all elements from the array without freeing the array's allocated storage.
  3607. @see clear
  3608. */
  3609. void clearQuick() throw()
  3610. {
  3611. lock.enter();
  3612. numUsed = 0;
  3613. lock.exit();
  3614. }
  3615. /** Returns the current number of elements in the array.
  3616. */
  3617. inline int size() const throw()
  3618. {
  3619. return numUsed;
  3620. }
  3621. /** Returns one of the elements in the array.
  3622. If the index passed in is beyond the range of valid elements, this
  3623. will return zero.
  3624. If you're certain that the index will always be a valid element, you
  3625. can call getUnchecked() instead, which is faster.
  3626. @param index the index of the element being requested (0 is the first element in the array)
  3627. @see getUnchecked, getFirst, getLast
  3628. */
  3629. inline ElementType operator[] (const int index) const throw()
  3630. {
  3631. lock.enter();
  3632. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  3633. ? this->elements [index]
  3634. : ElementType();
  3635. lock.exit();
  3636. return result;
  3637. }
  3638. /** Returns one of the elements in the array, without checking the index passed in.
  3639. Unlike the operator[] method, this will try to return an element without
  3640. checking that the index is within the bounds of the array, so should only
  3641. be used when you're confident that it will always be a valid index.
  3642. @param index the index of the element being requested (0 is the first element in the array)
  3643. @see operator[], getFirst, getLast
  3644. */
  3645. inline ElementType getUnchecked (const int index) const throw()
  3646. {
  3647. lock.enter();
  3648. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3649. const ElementType result = this->elements [index];
  3650. lock.exit();
  3651. return result;
  3652. }
  3653. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  3654. This is like getUnchecked, but returns a direct reference to the element, so that
  3655. you can alter it directly. Obviously this can be dangerous, so only use it when
  3656. absolutely necessary.
  3657. @param index the index of the element being requested (0 is the first element in the array)
  3658. @see operator[], getFirst, getLast
  3659. */
  3660. inline ElementType& getReference (const int index) const throw()
  3661. {
  3662. lock.enter();
  3663. jassert (((unsigned int) index) < (unsigned int) numUsed);
  3664. ElementType& result = this->elements [index];
  3665. lock.exit();
  3666. return result;
  3667. }
  3668. /** Returns the first element in the array, or 0 if the array is empty.
  3669. @see operator[], getUnchecked, getLast
  3670. */
  3671. inline ElementType getFirst() const throw()
  3672. {
  3673. lock.enter();
  3674. const ElementType result = (numUsed > 0) ? this->elements [0]
  3675. : ElementType();
  3676. lock.exit();
  3677. return result;
  3678. }
  3679. /** Returns the last element in the array, or 0 if the array is empty.
  3680. @see operator[], getUnchecked, getFirst
  3681. */
  3682. inline ElementType getLast() const throw()
  3683. {
  3684. lock.enter();
  3685. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  3686. : ElementType();
  3687. lock.exit();
  3688. return result;
  3689. }
  3690. /** Finds the index of the first element which matches the value passed in.
  3691. This will search the array for the given object, and return the index
  3692. of its first occurrence. If the object isn't found, the method will return -1.
  3693. @param elementToLookFor the value or object to look for
  3694. @returns the index of the object, or -1 if it's not found
  3695. */
  3696. int indexOf (const ElementType elementToLookFor) const throw()
  3697. {
  3698. int result = -1;
  3699. lock.enter();
  3700. const ElementType* e = this->elements;
  3701. for (int i = numUsed; --i >= 0;)
  3702. {
  3703. if (elementToLookFor == *e)
  3704. {
  3705. result = (int) (e - this->elements);
  3706. break;
  3707. }
  3708. ++e;
  3709. }
  3710. lock.exit();
  3711. return result;
  3712. }
  3713. /** Returns true if the array contains at least one occurrence of an object.
  3714. @param elementToLookFor the value or object to look for
  3715. @returns true if the item is found
  3716. */
  3717. bool contains (const ElementType elementToLookFor) const throw()
  3718. {
  3719. lock.enter();
  3720. const ElementType* e = this->elements;
  3721. int num = numUsed;
  3722. while (num >= 4)
  3723. {
  3724. if (*e == elementToLookFor
  3725. || *++e == elementToLookFor
  3726. || *++e == elementToLookFor
  3727. || *++e == elementToLookFor)
  3728. {
  3729. lock.exit();
  3730. return true;
  3731. }
  3732. num -= 4;
  3733. ++e;
  3734. }
  3735. while (num > 0)
  3736. {
  3737. if (elementToLookFor == *e)
  3738. {
  3739. lock.exit();
  3740. return true;
  3741. }
  3742. --num;
  3743. ++e;
  3744. }
  3745. lock.exit();
  3746. return false;
  3747. }
  3748. /** Appends a new element at the end of the array.
  3749. @param newElement the new object to add to the array
  3750. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  3751. */
  3752. void add (const ElementType newElement) throw()
  3753. {
  3754. lock.enter();
  3755. this->ensureAllocatedSize (numUsed + 1);
  3756. this->elements [numUsed++] = newElement;
  3757. lock.exit();
  3758. }
  3759. /** Inserts a new element into the array at a given position.
  3760. If the index is less than 0 or greater than the size of the array, the
  3761. element will be added to the end of the array.
  3762. Otherwise, it will be inserted into the array, moving all the later elements
  3763. along to make room.
  3764. @param indexToInsertAt the index at which the new element should be
  3765. inserted (pass in -1 to add it to the end)
  3766. @param newElement the new object to add to the array
  3767. @see add, addSorted, set
  3768. */
  3769. void insert (int indexToInsertAt, const ElementType newElement) throw()
  3770. {
  3771. lock.enter();
  3772. this->ensureAllocatedSize (numUsed + 1);
  3773. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3774. {
  3775. ElementType* const insertPos = this->elements + indexToInsertAt;
  3776. const int numberToMove = numUsed - indexToInsertAt;
  3777. if (numberToMove > 0)
  3778. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  3779. *insertPos = newElement;
  3780. ++numUsed;
  3781. }
  3782. else
  3783. {
  3784. this->elements [numUsed++] = newElement;
  3785. }
  3786. lock.exit();
  3787. }
  3788. /** Inserts multiple copies of an element into the array at a given position.
  3789. If the index is less than 0 or greater than the size of the array, the
  3790. element will be added to the end of the array.
  3791. Otherwise, it will be inserted into the array, moving all the later elements
  3792. along to make room.
  3793. @param indexToInsertAt the index at which the new element should be inserted
  3794. @param newElement the new object to add to the array
  3795. @param numberOfTimesToInsertIt how many copies of the value to insert
  3796. @see insert, add, addSorted, set
  3797. */
  3798. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  3799. int numberOfTimesToInsertIt) throw()
  3800. {
  3801. if (numberOfTimesToInsertIt > 0)
  3802. {
  3803. lock.enter();
  3804. this->ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  3805. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3806. {
  3807. ElementType* insertPos = this->elements + indexToInsertAt;
  3808. const int numberToMove = numUsed - indexToInsertAt;
  3809. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  3810. numUsed += numberOfTimesToInsertIt;
  3811. while (--numberOfTimesToInsertIt >= 0)
  3812. *insertPos++ = newElement;
  3813. }
  3814. else
  3815. {
  3816. while (--numberOfTimesToInsertIt >= 0)
  3817. this->elements [numUsed++] = newElement;
  3818. }
  3819. lock.exit();
  3820. }
  3821. }
  3822. /** Inserts an array of values into this array at a given position.
  3823. If the index is less than 0 or greater than the size of the array, the
  3824. new elements will be added to the end of the array.
  3825. Otherwise, they will be inserted into the array, moving all the later elements
  3826. along to make room.
  3827. @param indexToInsertAt the index at which the first new element should be inserted
  3828. @param newElements the new values to add to the array
  3829. @param numberOfElements how many items are in the array
  3830. @see insert, add, addSorted, set
  3831. */
  3832. void insertArray (int indexToInsertAt,
  3833. const ElementType* newElements,
  3834. int numberOfElements) throw()
  3835. {
  3836. if (numberOfElements > 0)
  3837. {
  3838. lock.enter();
  3839. this->ensureAllocatedSize (numUsed + numberOfElements);
  3840. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  3841. {
  3842. ElementType* insertPos = this->elements + indexToInsertAt;
  3843. const int numberToMove = numUsed - indexToInsertAt;
  3844. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  3845. numUsed += numberOfElements;
  3846. while (--numberOfElements >= 0)
  3847. *insertPos++ = *newElements++;
  3848. }
  3849. else
  3850. {
  3851. while (--numberOfElements >= 0)
  3852. this->elements [numUsed++] = *newElements++;
  3853. }
  3854. lock.exit();
  3855. }
  3856. }
  3857. /** Appends a new element at the end of the array as long as the array doesn't
  3858. already contain it.
  3859. If the array already contains an element that matches the one passed in, nothing
  3860. will be done.
  3861. @param newElement the new object to add to the array
  3862. */
  3863. void addIfNotAlreadyThere (const ElementType newElement) throw()
  3864. {
  3865. lock.enter();
  3866. if (! contains (newElement))
  3867. add (newElement);
  3868. lock.exit();
  3869. }
  3870. /** Replaces an element with a new value.
  3871. If the index is less than zero, this method does nothing.
  3872. If the index is beyond the end of the array, the item is added to the end of the array.
  3873. @param indexToChange the index whose value you want to change
  3874. @param newValue the new value to set for this index.
  3875. @see add, insert
  3876. */
  3877. void set (const int indexToChange,
  3878. const ElementType newValue) throw()
  3879. {
  3880. jassert (indexToChange >= 0);
  3881. if (indexToChange >= 0)
  3882. {
  3883. lock.enter();
  3884. if (indexToChange < numUsed)
  3885. {
  3886. this->elements [indexToChange] = newValue;
  3887. }
  3888. else
  3889. {
  3890. this->ensureAllocatedSize (numUsed + 1);
  3891. this->elements [numUsed++] = newValue;
  3892. }
  3893. lock.exit();
  3894. }
  3895. }
  3896. /** Replaces an element with a new value without doing any bounds-checking.
  3897. This just sets a value directly in the array's internal storage, so you'd
  3898. better make sure it's in range!
  3899. @param indexToChange the index whose value you want to change
  3900. @param newValue the new value to set for this index.
  3901. @see set, getUnchecked
  3902. */
  3903. void setUnchecked (const int indexToChange,
  3904. const ElementType newValue) throw()
  3905. {
  3906. lock.enter();
  3907. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3908. this->elements [indexToChange] = newValue;
  3909. lock.exit();
  3910. }
  3911. /** Adds elements from an array to the end of this array.
  3912. @param elementsToAdd the array of elements to add
  3913. @param numElementsToAdd how many elements are in this other array
  3914. @see add
  3915. */
  3916. void addArray (const ElementType* elementsToAdd,
  3917. int numElementsToAdd) throw()
  3918. {
  3919. lock.enter();
  3920. if (numElementsToAdd > 0)
  3921. {
  3922. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  3923. while (--numElementsToAdd >= 0)
  3924. this->elements [numUsed++] = *elementsToAdd++;
  3925. }
  3926. lock.exit();
  3927. }
  3928. /** This swaps the contents of this array with those of another array.
  3929. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3930. because it just swaps their internal pointers.
  3931. */
  3932. template <class OtherArrayType>
  3933. void swapWithArray (OtherArrayType& otherArray) throw()
  3934. {
  3935. lock.enter();
  3936. otherArray.lock.enter();
  3937. swapVariables <int> (this->numUsed, otherArray.numUsed);
  3938. swapVariables <ElementType*> (this->elements, otherArray.elements);
  3939. swapVariables <int> (this->numAllocated, otherArray.numAllocated);
  3940. otherArray.lock.exit();
  3941. lock.exit();
  3942. }
  3943. /** Adds elements from another array to the end of this array.
  3944. @param arrayToAddFrom the array from which to copy the elements
  3945. @param startIndex the first element of the other array to start copying from
  3946. @param numElementsToAdd how many elements to add from the other array. If this
  3947. value is negative or greater than the number of available elements,
  3948. all available elements will be copied.
  3949. @see add
  3950. */
  3951. template <class OtherArrayType>
  3952. void addArray (const OtherArrayType& arrayToAddFrom,
  3953. int startIndex = 0,
  3954. int numElementsToAdd = -1) throw()
  3955. {
  3956. arrayToAddFrom.lockArray();
  3957. lock.enter();
  3958. jassert (this != &arrayToAddFrom);
  3959. if (startIndex < 0)
  3960. {
  3961. jassertfalse
  3962. startIndex = 0;
  3963. }
  3964. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3965. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3966. this->addArray ((const ElementType*) (arrayToAddFrom.elements + startIndex), numElementsToAdd);
  3967. lock.exit();
  3968. arrayToAddFrom.unlockArray();
  3969. }
  3970. /** Inserts a new element into the array, assuming that the array is sorted.
  3971. This will use a comparator to find the position at which the new element
  3972. should go. If the array isn't sorted, the behaviour of this
  3973. method will be unpredictable.
  3974. @param comparator the comparator to use to compare the elements - see the sort()
  3975. method for details about the form this object should take
  3976. @param newElement the new element to insert to the array
  3977. @see add, sort
  3978. */
  3979. template <class ElementComparator>
  3980. void addSorted (ElementComparator& comparator,
  3981. const ElementType newElement) throw()
  3982. {
  3983. lock.enter();
  3984. insert (findInsertIndexInSortedArray (comparator, this->elements, newElement, 0, numUsed), newElement);
  3985. lock.exit();
  3986. }
  3987. /** Finds the index of an element in the array, assuming that the array is sorted.
  3988. This will use a comparator to do a binary-chop to find the index of the given
  3989. element, if it exists. If the array isn't sorted, the behaviour of this
  3990. method will be unpredictable.
  3991. @param comparator the comparator to use to compare the elements - see the sort()
  3992. method for details about the form this object should take
  3993. @param elementToLookFor the element to search for
  3994. @returns the index of the element, or -1 if it's not found
  3995. @see addSorted, sort
  3996. */
  3997. template <class ElementComparator>
  3998. int indexOfSorted (ElementComparator& comparator,
  3999. const ElementType elementToLookFor) const throw()
  4000. {
  4001. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4002. // avoids getting warning messages about the parameter being unused
  4003. lock.enter();
  4004. int start = 0;
  4005. int end = numUsed;
  4006. for (;;)
  4007. {
  4008. if (start >= end)
  4009. {
  4010. lock.exit();
  4011. return -1;
  4012. }
  4013. else if (comparator.compareElements (elementToLookFor, this->elements [start]) == 0)
  4014. {
  4015. lock.exit();
  4016. return start;
  4017. }
  4018. else
  4019. {
  4020. const int halfway = (start + end) >> 1;
  4021. if (halfway == start)
  4022. {
  4023. lock.exit();
  4024. return -1;
  4025. }
  4026. else if (comparator.compareElements (elementToLookFor, this->elements [halfway]) >= 0)
  4027. start = halfway;
  4028. else
  4029. end = halfway;
  4030. }
  4031. }
  4032. }
  4033. /** Removes an element from the array.
  4034. This will remove the element at a given index, and move back
  4035. all the subsequent elements to close the gap.
  4036. If the index passed in is out-of-range, nothing will happen.
  4037. @param indexToRemove the index of the element to remove
  4038. @returns the element that has been removed
  4039. @see removeValue, removeRange
  4040. */
  4041. ElementType remove (const int indexToRemove) throw()
  4042. {
  4043. lock.enter();
  4044. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4045. {
  4046. --numUsed;
  4047. ElementType* const e = this->elements + indexToRemove;
  4048. ElementType const removed = *e;
  4049. const int numberToShift = numUsed - indexToRemove;
  4050. if (numberToShift > 0)
  4051. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  4052. if ((numUsed << 1) < this->numAllocated)
  4053. minimiseStorageOverheads();
  4054. lock.exit();
  4055. return removed;
  4056. }
  4057. else
  4058. {
  4059. lock.exit();
  4060. return ElementType();
  4061. }
  4062. }
  4063. /** Removes an item from the array.
  4064. This will remove the first occurrence of the given element from the array.
  4065. If the item isn't found, no action is taken.
  4066. @param valueToRemove the object to try to remove
  4067. @see remove, removeRange
  4068. */
  4069. void removeValue (const ElementType valueToRemove) throw()
  4070. {
  4071. lock.enter();
  4072. ElementType* e = this->elements;
  4073. for (int i = numUsed; --i >= 0;)
  4074. {
  4075. if (valueToRemove == *e)
  4076. {
  4077. remove ((int) (e - this->elements));
  4078. break;
  4079. }
  4080. ++e;
  4081. }
  4082. lock.exit();
  4083. }
  4084. /** Removes a range of elements from the array.
  4085. This will remove a set of elements, starting from the given index,
  4086. and move subsequent elements down to close the gap.
  4087. If the range extends beyond the bounds of the array, it will
  4088. be safely clipped to the size of the array.
  4089. @param startIndex the index of the first element to remove
  4090. @param numberToRemove how many elements should be removed
  4091. @see remove, removeValue
  4092. */
  4093. void removeRange (int startIndex,
  4094. const int numberToRemove) throw()
  4095. {
  4096. lock.enter();
  4097. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4098. startIndex = jlimit (0, numUsed, startIndex);
  4099. if (endIndex > startIndex)
  4100. {
  4101. const int rangeSize = endIndex - startIndex;
  4102. ElementType* e = this->elements + startIndex;
  4103. int numToShift = numUsed - endIndex;
  4104. numUsed -= rangeSize;
  4105. while (--numToShift >= 0)
  4106. {
  4107. *e = e [rangeSize];
  4108. ++e;
  4109. }
  4110. if ((numUsed << 1) < this->numAllocated)
  4111. minimiseStorageOverheads();
  4112. }
  4113. lock.exit();
  4114. }
  4115. /** Removes the last n elements from the array.
  4116. @param howManyToRemove how many elements to remove from the end of the array
  4117. @see remove, removeValue, removeRange
  4118. */
  4119. void removeLast (const int howManyToRemove = 1) throw()
  4120. {
  4121. lock.enter();
  4122. numUsed = jmax (0, numUsed - howManyToRemove);
  4123. if ((numUsed << 1) < this->numAllocated)
  4124. minimiseStorageOverheads();
  4125. lock.exit();
  4126. }
  4127. /** Removes any elements which are also in another array.
  4128. @param otherArray the other array in which to look for elements to remove
  4129. @see removeValuesNotIn, remove, removeValue, removeRange
  4130. */
  4131. template <class OtherArrayType>
  4132. void removeValuesIn (const OtherArrayType& otherArray) throw()
  4133. {
  4134. otherArray.lockArray();
  4135. lock.enter();
  4136. if (this == &otherArray)
  4137. {
  4138. clear();
  4139. }
  4140. else
  4141. {
  4142. if (otherArray.size() > 0)
  4143. {
  4144. for (int i = numUsed; --i >= 0;)
  4145. if (otherArray.contains (this->elements [i]))
  4146. remove (i);
  4147. }
  4148. }
  4149. lock.exit();
  4150. otherArray.unlockArray();
  4151. }
  4152. /** Removes any elements which are not found in another array.
  4153. Only elements which occur in this other array will be retained.
  4154. @param otherArray the array in which to look for elements NOT to remove
  4155. @see removeValuesIn, remove, removeValue, removeRange
  4156. */
  4157. template <class OtherArrayType>
  4158. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  4159. {
  4160. otherArray.lockArray();
  4161. lock.enter();
  4162. if (this != &otherArray)
  4163. {
  4164. if (otherArray.size() <= 0)
  4165. {
  4166. clear();
  4167. }
  4168. else
  4169. {
  4170. for (int i = numUsed; --i >= 0;)
  4171. if (! otherArray.contains (this->elements [i]))
  4172. remove (i);
  4173. }
  4174. }
  4175. lock.exit();
  4176. otherArray.unlockArray();
  4177. }
  4178. /** Swaps over two elements in the array.
  4179. This swaps over the elements found at the two indexes passed in.
  4180. If either index is out-of-range, this method will do nothing.
  4181. @param index1 index of one of the elements to swap
  4182. @param index2 index of the other element to swap
  4183. */
  4184. void swap (const int index1,
  4185. const int index2) throw()
  4186. {
  4187. lock.enter();
  4188. if (((unsigned int) index1) < (unsigned int) numUsed
  4189. && ((unsigned int) index2) < (unsigned int) numUsed)
  4190. {
  4191. swapVariables (this->elements [index1],
  4192. this->elements [index2]);
  4193. }
  4194. lock.exit();
  4195. }
  4196. /** Moves one of the values to a different position.
  4197. This will move the value to a specified index, shuffling along
  4198. any intervening elements as required.
  4199. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4200. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4201. @param currentIndex the index of the value to be moved. If this isn't a
  4202. valid index, then nothing will be done
  4203. @param newIndex the index at which you'd like this value to end up. If this
  4204. is less than zero, the value will be moved to the end
  4205. of the array
  4206. */
  4207. void move (const int currentIndex,
  4208. int newIndex) throw()
  4209. {
  4210. if (currentIndex != newIndex)
  4211. {
  4212. lock.enter();
  4213. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4214. {
  4215. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4216. newIndex = numUsed - 1;
  4217. const ElementType value = this->elements [currentIndex];
  4218. if (newIndex > currentIndex)
  4219. {
  4220. memmove (this->elements + currentIndex,
  4221. this->elements + currentIndex + 1,
  4222. (newIndex - currentIndex) * sizeof (ElementType));
  4223. }
  4224. else
  4225. {
  4226. memmove (this->elements + newIndex + 1,
  4227. this->elements + newIndex,
  4228. (currentIndex - newIndex) * sizeof (ElementType));
  4229. }
  4230. this->elements [newIndex] = value;
  4231. }
  4232. lock.exit();
  4233. }
  4234. }
  4235. /** Reduces the amount of storage being used by the array.
  4236. Arrays typically allocate slightly more storage than they need, and after
  4237. removing elements, they may have quite a lot of unused space allocated.
  4238. This method will reduce the amount of allocated storage to a minimum.
  4239. */
  4240. void minimiseStorageOverheads() throw()
  4241. {
  4242. lock.enter();
  4243. if (numUsed == 0)
  4244. {
  4245. this->setAllocatedSize (0);
  4246. }
  4247. else
  4248. {
  4249. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  4250. if (newAllocation < this->numAllocated)
  4251. this->setAllocatedSize (newAllocation);
  4252. }
  4253. lock.exit();
  4254. }
  4255. /** Increases the array's internal storage to hold a minimum number of elements.
  4256. Calling this before adding a large known number of elements means that
  4257. the array won't have to keep dynamically resizing itself as the elements
  4258. are added, and it'll therefore be more efficient.
  4259. */
  4260. void ensureStorageAllocated (const int minNumElements) throw()
  4261. {
  4262. this->ensureAllocatedSize (minNumElements);
  4263. }
  4264. /** Sorts the elements in the array.
  4265. This will use a comparator object to sort the elements into order. The object
  4266. passed must have a method of the form:
  4267. @code
  4268. int compareElements (ElementType first, ElementType second);
  4269. @endcode
  4270. ..and this method must return:
  4271. - a value of < 0 if the first comes before the second
  4272. - a value of 0 if the two objects are equivalent
  4273. - a value of > 0 if the second comes before the first
  4274. To improve performance, the compareElements() method can be declared as static or const.
  4275. @param comparator the comparator to use for comparing elements.
  4276. @param retainOrderOfEquivalentItems if this is true, then items
  4277. which the comparator says are equivalent will be
  4278. kept in the order in which they currently appear
  4279. in the array. This is slower to perform, but may
  4280. be important in some cases. If it's false, a faster
  4281. algorithm is used, but equivalent elements may be
  4282. rearranged.
  4283. @see addSorted, indexOfSorted, sortArray
  4284. */
  4285. template <class ElementComparator>
  4286. void sort (ElementComparator& comparator,
  4287. const bool retainOrderOfEquivalentItems = false) const throw()
  4288. {
  4289. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4290. // avoids getting warning messages about the parameter being unused
  4291. lock.enter();
  4292. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4293. lock.exit();
  4294. }
  4295. /** Locks the array's CriticalSection.
  4296. Of course if the type of section used is a DummyCriticalSection, this won't
  4297. have any effect.
  4298. @see unlockArray
  4299. */
  4300. void lockArray() const throw()
  4301. {
  4302. lock.enter();
  4303. }
  4304. /** Unlocks the array's CriticalSection.
  4305. Of course if the type of section used is a DummyCriticalSection, this won't
  4306. have any effect.
  4307. @see lockArray
  4308. */
  4309. void unlockArray() const throw()
  4310. {
  4311. lock.exit();
  4312. }
  4313. juce_UseDebuggingNewOperator
  4314. private:
  4315. int numUsed;
  4316. TypeOfCriticalSectionToUse lock;
  4317. };
  4318. #endif // __JUCE_ARRAY_JUCEHEADER__
  4319. /********* End of inlined file: juce_Array.h *********/
  4320. /**
  4321. A typedef for an Array of void*'s.
  4322. VoidArrays are used in various places throughout the library instead of
  4323. more strongly-typed arrays, to keep code-size low.
  4324. */
  4325. typedef Array <void*> VoidArray;
  4326. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  4327. /********* End of inlined file: juce_VoidArray.h *********/
  4328. #ifndef DOXYGEN
  4329. // (used in StringArray::appendNumbersToDuplicates)
  4330. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4331. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4332. #endif
  4333. /**
  4334. A special array for holding a list of strings.
  4335. @see String, StringPairArray
  4336. */
  4337. class JUCE_API StringArray
  4338. {
  4339. public:
  4340. /** Creates an empty string array */
  4341. StringArray() throw();
  4342. /** Creates a copy of another string array */
  4343. StringArray (const StringArray& other) throw();
  4344. /** Creates a copy of an array of string literals.
  4345. @param strings an array of strings to add. Null pointers in the array will be
  4346. treated as empty strings
  4347. @param numberOfStrings how many items there are in the array
  4348. */
  4349. StringArray (const juce_wchar** const strings,
  4350. const int numberOfStrings) throw();
  4351. /** Creates a copy of an array of string literals.
  4352. @param strings an array of strings to add. Null pointers in the array will be
  4353. treated as empty strings
  4354. @param numberOfStrings how many items there are in the array
  4355. */
  4356. StringArray (const char** const strings,
  4357. const int numberOfStrings) throw();
  4358. /** Creates a copy of a null-terminated array of string literals.
  4359. Each item from the array passed-in is added, until it encounters a null pointer,
  4360. at which point it stops.
  4361. */
  4362. StringArray (const juce_wchar** const strings) throw();
  4363. /** Creates a copy of a null-terminated array of string literals.
  4364. Each item from the array passed-in is added, until it encounters a null pointer,
  4365. at which point it stops.
  4366. */
  4367. StringArray (const char** const strings) throw();
  4368. /** Destructor. */
  4369. virtual ~StringArray() throw();
  4370. /** Copies the contents of another string array into this one */
  4371. const StringArray& operator= (const StringArray& other) throw();
  4372. /** Compares two arrays.
  4373. Comparisons are case-sensitive.
  4374. @returns true only if the other array contains exactly the same strings in the same order
  4375. */
  4376. bool operator== (const StringArray& other) const throw();
  4377. /** Compares two arrays.
  4378. Comparisons are case-sensitive.
  4379. @returns false if the other array contains exactly the same strings in the same order
  4380. */
  4381. bool operator!= (const StringArray& other) const throw();
  4382. /** Returns the number of strings in the array */
  4383. inline int size() const throw() { return strings.size(); };
  4384. /** Returns one of the strings from the array.
  4385. If the index is out-of-range, an empty string is returned.
  4386. Obviously the reference returned shouldn't be stored for later use, as the
  4387. string it refers to may disappear when the array changes.
  4388. */
  4389. const String& operator[] (const int index) const throw();
  4390. /** Searches for a string in the array.
  4391. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4392. @returns true if the string is found inside the array
  4393. */
  4394. bool contains (const String& stringToLookFor,
  4395. const bool ignoreCase = false) const throw();
  4396. /** Searches for a string in the array.
  4397. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4398. @param stringToLookFor the string to try to find
  4399. @param ignoreCase whether the comparison should be case-insensitive
  4400. @param startIndex the first index to start searching from
  4401. @returns the index of the first occurrence of the string in this array,
  4402. or -1 if it isn't found.
  4403. */
  4404. int indexOf (const String& stringToLookFor,
  4405. const bool ignoreCase = false,
  4406. int startIndex = 0) const throw();
  4407. /** Appends a string at the end of the array. */
  4408. void add (const String& stringToAdd) throw();
  4409. /** Inserts a string into the array.
  4410. This will insert a string into the array at the given index, moving
  4411. up the other elements to make room for it.
  4412. If the index is less than zero or greater than the size of the array,
  4413. the new string will be added to the end of the array.
  4414. */
  4415. void insert (const int index,
  4416. const String& stringToAdd) throw();
  4417. /** Adds a string to the array as long as it's not already in there.
  4418. The search can optionally be case-insensitive.
  4419. */
  4420. void addIfNotAlreadyThere (const String& stringToAdd,
  4421. const bool ignoreCase = false) throw();
  4422. /** Replaces one of the strings in the array with another one.
  4423. If the index is higher than the array's size, the new string will be
  4424. added to the end of the array; if it's less than zero nothing happens.
  4425. */
  4426. void set (const int index,
  4427. const String& newString) throw();
  4428. /** Appends some strings from another array to the end of this one.
  4429. @param other the array to add
  4430. @param startIndex the first element of the other array to add
  4431. @param numElementsToAdd the maximum number of elements to add (if this is
  4432. less than zero, they are all added)
  4433. */
  4434. void addArray (const StringArray& other,
  4435. int startIndex = 0,
  4436. int numElementsToAdd = -1) throw();
  4437. /** Breaks up a string into tokens and adds them to this array.
  4438. This will tokenise the given string using whitespace characters as the
  4439. token delimiters, and will add these tokens to the end of the array.
  4440. @returns the number of tokens added
  4441. */
  4442. int addTokens (const tchar* const stringToTokenise,
  4443. const bool preserveQuotedStrings) throw();
  4444. /** Breaks up a string into tokens and adds them to this array.
  4445. This will tokenise the given string (using the string passed in to define the
  4446. token delimiters), and will add these tokens to the end of the array.
  4447. @param stringToTokenise the string to tokenise
  4448. @param breakCharacters a string of characters, any of which will be considered
  4449. to be a token delimiter.
  4450. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4451. which are treated as quotes. Any text occurring
  4452. between quotes is not broken up into tokens.
  4453. @returns the number of tokens added
  4454. */
  4455. int addTokens (const tchar* const stringToTokenise,
  4456. const tchar* breakCharacters,
  4457. const tchar* quoteCharacters) throw();
  4458. /** Breaks up a string into lines and adds them to this array.
  4459. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4460. to the array. Line-break characters are omitted from the strings that are added to
  4461. the array.
  4462. */
  4463. int addLines (const tchar* stringToBreakUp) throw();
  4464. /** Removes all elements from the array. */
  4465. void clear() throw();
  4466. /** Removes a string from the array.
  4467. If the index is out-of-range, no action will be taken.
  4468. */
  4469. void remove (const int index) throw();
  4470. /** Finds a string in the array and removes it.
  4471. This will remove the first occurrence of the given string from the array. The
  4472. comparison may be case-insensitive depending on the ignoreCase parameter.
  4473. */
  4474. void removeString (const String& stringToRemove,
  4475. const bool ignoreCase = false) throw();
  4476. /** Removes any duplicated elements from the array.
  4477. If any string appears in the array more than once, only the first occurrence of
  4478. it will be retained.
  4479. @param ignoreCase whether to use a case-insensitive comparison
  4480. */
  4481. void removeDuplicates (const bool ignoreCase) throw();
  4482. /** Removes empty strings from the array.
  4483. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4484. characters will also be removed
  4485. */
  4486. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4487. /** Moves one of the strings to a different position.
  4488. This will move the string to a specified index, shuffling along
  4489. any intervening elements as required.
  4490. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4491. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4492. @param currentIndex the index of the value to be moved. If this isn't a
  4493. valid index, then nothing will be done
  4494. @param newIndex the index at which you'd like this value to end up. If this
  4495. is less than zero, the value will be moved to the end
  4496. of the array
  4497. */
  4498. void move (const int currentIndex, int newIndex) throw();
  4499. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4500. void trim() throw();
  4501. /** Adds numbers to the strings in the array, to make each string unique.
  4502. This will add numbers to the ends of groups of similar strings.
  4503. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4504. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4505. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4506. also has a number appended to it.
  4507. @param preNumberString when adding a number, this string is added before the number
  4508. @param postNumberString this string is appended after any numbers that are added
  4509. */
  4510. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4511. const bool appendNumberToFirstInstance,
  4512. const tchar* const preNumberString = defaultPreNumberString,
  4513. const tchar* const postNumberString = defaultPostNumberString) throw();
  4514. /** Joins the strings in the array together into one string.
  4515. This will join a range of elements from the array into a string, separating
  4516. them with a given string.
  4517. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4518. @param separatorString the string to insert between all the strings
  4519. @param startIndex the first element to join
  4520. @param numberOfElements how many elements to join together. If this is less
  4521. than zero, all available elements will be used.
  4522. */
  4523. const String joinIntoString (const String& separatorString,
  4524. int startIndex = 0,
  4525. int numberOfElements = -1) const throw();
  4526. /** Sorts the array into alphabetical order.
  4527. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4528. */
  4529. void sort (const bool ignoreCase) throw();
  4530. /** Reduces the amount of storage being used by the array.
  4531. Arrays typically allocate slightly more storage than they need, and after
  4532. removing elements, they may have quite a lot of unused space allocated.
  4533. This method will reduce the amount of allocated storage to a minimum.
  4534. */
  4535. void minimiseStorageOverheads() throw();
  4536. juce_UseDebuggingNewOperator
  4537. private:
  4538. VoidArray strings;
  4539. };
  4540. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4541. /********* End of inlined file: juce_StringArray.h *********/
  4542. /********* Start of inlined file: juce_MemoryBlock.h *********/
  4543. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4544. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  4545. /**
  4546. A class to hold a resizable block of raw data.
  4547. */
  4548. class JUCE_API MemoryBlock
  4549. {
  4550. public:
  4551. /** Create an uninitialised block with 0 size. */
  4552. MemoryBlock() throw();
  4553. /** Creates a memory block with a given initial size.
  4554. @param initialSize the size of block to create
  4555. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  4556. */
  4557. MemoryBlock (const int initialSize,
  4558. const bool initialiseToZero = false) throw();
  4559. /** Creates a copy of another memory block. */
  4560. MemoryBlock (const MemoryBlock& other) throw();
  4561. /** Creates a memory block using a copy of a block of data.
  4562. @param dataToInitialiseFrom some data to copy into this block
  4563. @param sizeInBytes how much space to use
  4564. */
  4565. MemoryBlock (const void* const dataToInitialiseFrom,
  4566. const int sizeInBytes) throw();
  4567. /** Destructor. */
  4568. ~MemoryBlock() throw();
  4569. /** Copies another memory block onto this one.
  4570. This block will be resized and copied to exactly match the other one.
  4571. */
  4572. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  4573. /** Compares two memory blocks.
  4574. @returns true only if the two blocks are the same size and have identical contents.
  4575. */
  4576. bool operator== (const MemoryBlock& other) const throw();
  4577. /** Compares two memory blocks.
  4578. @returns true if the two blocks are different sizes or have different contents.
  4579. */
  4580. bool operator!= (const MemoryBlock& other) const throw();
  4581. /** Returns a pointer to the data, casting it to any type of primitive data required.
  4582. Note that the pointer returned will probably become invalid when the
  4583. block is resized.
  4584. */
  4585. template <class DataType>
  4586. operator DataType*() const throw() { return (DataType*) data; }
  4587. /** Returns a void pointer to the data.
  4588. Note that the pointer returned will probably become invalid when the
  4589. block is resized.
  4590. */
  4591. void* getData() const throw() { return data; }
  4592. /** Returns a byte from the memory block.
  4593. This returns a reference, so you can also use it to set a byte.
  4594. */
  4595. char& operator[] (const int offset) const throw() { return data [offset]; }
  4596. /** Returns the block's current allocated size, in bytes. */
  4597. int getSize() const throw() { return size; }
  4598. /** Resizes the memory block.
  4599. This will try to keep as much of the block's current content as it can,
  4600. and can optionally be made to clear any new space that gets allocated at
  4601. the end of the block.
  4602. @param newSize the new desired size for the block
  4603. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4604. whether to clear the new section or just leave it
  4605. uninitialised
  4606. @see ensureSize
  4607. */
  4608. void setSize (const int newSize,
  4609. const bool initialiseNewSpaceToZero = false) throw();
  4610. /** Increases the block's size only if it's smaller than a given size.
  4611. @param minimumSize if the block is already bigger than this size, no action
  4612. will be taken; otherwise it will be increased to this size
  4613. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  4614. whether to clear the new section or just leave it
  4615. uninitialised
  4616. @see setSize
  4617. */
  4618. void ensureSize (const int minimumSize,
  4619. const bool initialiseNewSpaceToZero = false) throw();
  4620. /** Fills the entire memory block with a repeated byte value.
  4621. This is handy for clearing a block of memory to zero.
  4622. */
  4623. void fillWith (const uint8 valueToUse) throw();
  4624. /** Adds another block of data to the end of this one.
  4625. This block's size will be increased accordingly.
  4626. */
  4627. void append (const void* const data,
  4628. const int numBytes) throw();
  4629. /** Copies data into this MemoryBlock from a memory address.
  4630. @param srcData the memory location of the data to copy into this block
  4631. @param destinationOffset the offset in this block at which the data being copied should begin
  4632. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  4633. it will be clipped so not to do anything nasty)
  4634. */
  4635. void copyFrom (const void* srcData,
  4636. int destinationOffset,
  4637. int numBytes) throw();
  4638. /** Copies data from this MemoryBlock to a memory address.
  4639. @param destData the memory location to write to
  4640. @param sourceOffset the offset within this block from which the copied data will be read
  4641. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  4642. zeros will be used for that portion of the data)
  4643. */
  4644. void copyTo (void* destData,
  4645. int sourceOffset,
  4646. int numBytes) const throw();
  4647. /** Chops out a section of the block.
  4648. This will remove a section of the memory block and close the gap around it,
  4649. shifting any subsequent data downwards and reducing the size of the block.
  4650. If the range specified goes beyond the size of the block, it will be clipped.
  4651. */
  4652. void removeSection (int startByte, int numBytesToRemove) throw();
  4653. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  4654. characters in the system's default encoding. */
  4655. const String toString() const throw();
  4656. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  4657. The block will be resized to the number of valid bytes read from the string.
  4658. Non-hex characters in the string will be ignored.
  4659. @see String::toHexString()
  4660. */
  4661. void loadFromHexString (const String& sourceHexString) throw();
  4662. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  4663. void setBitRange (int bitRangeStart,
  4664. int numBits,
  4665. int binaryNumberToApply) throw();
  4666. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  4667. int getBitRange (int bitRangeStart,
  4668. int numBitsToRead) const throw();
  4669. /** Returns a string of characters that represent the binary contents of this block.
  4670. Uses a 64-bit encoding system to allow binary data to be turned into a string
  4671. of simple non-extended characters, e.g. for storage in XML.
  4672. @see fromBase64Encoding
  4673. */
  4674. const String toBase64Encoding() const throw();
  4675. /** Takes a string of encoded characters and turns it into binary data.
  4676. The string passed in must have been created by to64BitEncoding(), and this
  4677. block will be resized to recreate the original data block.
  4678. @see toBase64Encoding
  4679. */
  4680. bool fromBase64Encoding (const String& encodedString) throw();
  4681. juce_UseDebuggingNewOperator
  4682. private:
  4683. char* data;
  4684. int size;
  4685. };
  4686. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  4687. /********* End of inlined file: juce_MemoryBlock.h *********/
  4688. class FileInputStream;
  4689. class FileOutputStream;
  4690. /**
  4691. Represents a local file or directory.
  4692. This class encapsulates the absolute pathname of a file or directory, and
  4693. has methods for finding out about the file and changing its properties.
  4694. To read or write to the file, there are methods for returning an input or
  4695. output stream.
  4696. @see FileInputStream, FileOutputStream
  4697. */
  4698. class JUCE_API File
  4699. {
  4700. public:
  4701. /** Creates an (invalid) file object.
  4702. The file is initially set to an empty path, so getFullPath() will return
  4703. an empty string, and comparing the file to File::nonexistent will return
  4704. true.
  4705. You can use its operator= method to point it at a proper file.
  4706. */
  4707. File() throw() {}
  4708. /** Creates a file from an absolute path.
  4709. If the path supplied is a relative path, it is taken to be relative
  4710. to the current working directory (see File::getCurrentWorkingDirectory()),
  4711. but this isn't a recommended way of creating a file, because you
  4712. never know what the CWD is going to be.
  4713. On the Mac/Linux, the path can include "~" notation for referring to
  4714. user home directories.
  4715. */
  4716. File (const String& path) throw();
  4717. /** Creates a copy of another file object. */
  4718. File (const File& other) throw();
  4719. /** Destructor. */
  4720. ~File() throw() {}
  4721. /** Sets the file based on an absolute pathname.
  4722. If the path supplied is a relative path, it is taken to be relative
  4723. to the current working directory (see File::getCurrentWorkingDirectory()),
  4724. but this isn't a recommended way of creating a file, because you
  4725. never know what the CWD is going to be.
  4726. On the Mac/Linux, the path can include "~" notation for referring to
  4727. user home directories.
  4728. */
  4729. const File& operator= (const String& newFilePath) throw();
  4730. /** Copies from another file object. */
  4731. const File& operator= (const File& otherFile) throw();
  4732. /** This static constant is used for referring to an 'invalid' file. */
  4733. static const File nonexistent;
  4734. /** Checks whether the file actually exists.
  4735. @returns true if the file exists, either as a file or a directory.
  4736. @see existsAsFile, isDirectory
  4737. */
  4738. bool exists() const throw();
  4739. /** Checks whether the file exists and is a file rather than a directory.
  4740. @returns true only if this is a real file, false if it's a directory
  4741. or doesn't exist
  4742. @see exists, isDirectory
  4743. */
  4744. bool existsAsFile() const throw();
  4745. /** Checks whether the file is a directory that exists.
  4746. @returns true only if the file is a directory which actually exists, so
  4747. false if it's a file or doesn't exist at all
  4748. @see exists, existsAsFile
  4749. */
  4750. bool isDirectory() const throw();
  4751. /** Returns the size of the file in bytes.
  4752. @returns the number of bytes in the file, or 0 if it doesn't exist.
  4753. */
  4754. int64 getSize() const throw();
  4755. /** Utility function to convert a file size in bytes to a neat string description.
  4756. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  4757. 2000000 would produce "2 MB", etc.
  4758. */
  4759. static const String descriptionOfSizeInBytes (const int64 bytes);
  4760. /** Returns the complete, absolute path of this file.
  4761. This includes the filename and all its parent folders. On Windows it'll
  4762. also include the drive letter prefix; on Mac or Linux it'll be a complete
  4763. path starting from the root folder.
  4764. If you just want the file's name, you should use getFileName() or
  4765. getFileNameWithoutExtension().
  4766. @see getFileName, getRelativePathFrom
  4767. */
  4768. const String& getFullPathName() const throw() { return fullPath; }
  4769. /** Returns the last section of the pathname.
  4770. Returns just the final part of the path - e.g. if the whole path
  4771. is "/moose/fish/foo.txt" this will return "foo.txt".
  4772. For a directory, it returns the final part of the path - e.g. for the
  4773. directory "/moose/fish" it'll return "fish".
  4774. If the filename begins with a dot, it'll return the whole filename, e.g. for
  4775. "/moose/.fish", it'll return ".fish"
  4776. @see getFullPathName, getFileNameWithoutExtension
  4777. */
  4778. const String getFileName() const throw();
  4779. /** Creates a relative path that refers to a file relatively to a given directory.
  4780. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  4781. would return "../../foo.txt".
  4782. If it's not possible to navigate from one file to the other, an absolute
  4783. path is returned. If the paths are invalid, an empty string may also be
  4784. returned.
  4785. @param directoryToBeRelativeTo the directory which the resultant string will
  4786. be relative to. If this is actually a file rather than
  4787. a directory, its parent directory will be used instead.
  4788. If it doesn't exist, it's assumed to be a directory.
  4789. @see getChildFile, isAbsolutePath
  4790. */
  4791. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  4792. /** Returns the file's extension.
  4793. Returns the file extension of this file, also including the dot.
  4794. e.g. "/moose/fish/foo.txt" would return ".txt"
  4795. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  4796. */
  4797. const String getFileExtension() const throw();
  4798. /** Checks whether the file has a given extension.
  4799. @param extensionToTest the extension to look for - it doesn't matter whether or
  4800. not this string has a dot at the start, so ".wav" and "wav"
  4801. will have the same effect. The comparison used is
  4802. case-insensitve.
  4803. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  4804. */
  4805. bool hasFileExtension (const String& extensionToTest) const throw();
  4806. /** Returns a version of this file with a different file extension.
  4807. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  4808. @param newExtension the new extension, either with or without a dot at the start (this
  4809. doesn't make any difference). To get remove a file's extension altogether,
  4810. pass an empty string into this function.
  4811. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  4812. */
  4813. const File withFileExtension (const String& newExtension) const throw();
  4814. /** Returns the last part of the filename, without its file extension.
  4815. e.g. for "/moose/fish/foo.txt" this will return "foo".
  4816. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  4817. */
  4818. const String getFileNameWithoutExtension() const throw();
  4819. /** Returns a 32-bit hash-code that identifies this file.
  4820. This is based on the filename. Obviously it's possible, although unlikely, that
  4821. two files will have the same hash-code.
  4822. */
  4823. int hashCode() const throw();
  4824. /** Returns a 64-bit hash-code that identifies this file.
  4825. This is based on the filename. Obviously it's possible, although unlikely, that
  4826. two files will have the same hash-code.
  4827. */
  4828. int64 hashCode64() const throw();
  4829. /** Returns a file based on a relative path.
  4830. This will find a child file or directory of the current object.
  4831. e.g.
  4832. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  4833. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  4834. If the string is actually an absolute path, it will be treated as such, e.g.
  4835. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  4836. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  4837. */
  4838. const File getChildFile (String relativePath) const throw();
  4839. /** Returns a file which is in the same directory as this one.
  4840. This is equivalent to getParentDirectory().getChildFile (name).
  4841. @see getChildFile, getParentDirectory
  4842. */
  4843. const File getSiblingFile (const String& siblingFileName) const throw();
  4844. /** Returns the directory that contains this file or directory.
  4845. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  4846. */
  4847. const File getParentDirectory() const throw();
  4848. /** Checks whether a file is somewhere inside a directory.
  4849. Returns true if this file is somewhere inside a subdirectory of the directory
  4850. that is passed in. Neither file actually has to exist, because the function
  4851. just checks the paths for similarities.
  4852. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  4853. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  4854. */
  4855. bool isAChildOf (const File& potentialParentDirectory) const throw();
  4856. /** Chooses a filename relative to this one that doesn't already exist.
  4857. If this file is a directory, this will return a child file of this
  4858. directory that doesn't exist, by adding numbers to a prefix and suffix until
  4859. it finds one that isn't already there.
  4860. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  4861. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  4862. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  4863. @param prefix the string to use for the filename before the number
  4864. @param suffix the string to add to the filename after the number
  4865. @param putNumbersInBrackets if true, this will create filenames in the
  4866. format "prefix(number)suffix", if false, it will leave the
  4867. brackets out.
  4868. */
  4869. const File getNonexistentChildFile (const String& prefix,
  4870. const String& suffix,
  4871. bool putNumbersInBrackets = true) const throw();
  4872. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  4873. If this file doesn't exist, this will just return itself, otherwise it
  4874. will return an appropriate sibling that doesn't exist, e.g. if a file
  4875. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  4876. @param putNumbersInBrackets whether to add brackets around the numbers that
  4877. get appended to the new filename.
  4878. */
  4879. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  4880. /** Compares the pathnames for two files. */
  4881. bool operator== (const File& otherFile) const throw();
  4882. /** Compares the pathnames for two files. */
  4883. bool operator!= (const File& otherFile) const throw();
  4884. /** Checks whether a file can be created or written to.
  4885. @returns true if it's possible to create and write to this file. If the file
  4886. doesn't already exist, this will check its parent directory to
  4887. see if writing is allowed.
  4888. @see setReadOnly
  4889. */
  4890. bool hasWriteAccess() const throw();
  4891. /** Changes the write-permission of a file or directory.
  4892. @param shouldBeReadOnly whether to add or remove write-permission
  4893. @param applyRecursively if the file is a directory and this is true, it will
  4894. recurse through all the subfolders changing the permissions
  4895. of all files
  4896. @returns true if it manages to change the file's permissions.
  4897. @see hasWriteAccess
  4898. */
  4899. bool setReadOnly (const bool shouldBeReadOnly,
  4900. const bool applyRecursively = false) const throw();
  4901. /** Returns true if this file is a hidden or system file.
  4902. The criteria for deciding whether a file is hidden are platform-dependent.
  4903. */
  4904. bool isHidden() const throw();
  4905. /** If this file is a link, this returns the file that it points to.
  4906. If this file isn't actually link, it'll just return itself.
  4907. */
  4908. const File getLinkedTarget() const throw();
  4909. /** Returns the last modification time of this file.
  4910. @returns the time, or an invalid time if the file doesn't exist.
  4911. @see setLastModificationTime, getLastAccessTime, getCreationTime
  4912. */
  4913. const Time getLastModificationTime() const throw();
  4914. /** Returns the last time this file was accessed.
  4915. @returns the time, or an invalid time if the file doesn't exist.
  4916. @see setLastAccessTime, getLastModificationTime, getCreationTime
  4917. */
  4918. const Time getLastAccessTime() const throw();
  4919. /** Returns the time that this file was created.
  4920. @returns the time, or an invalid time if the file doesn't exist.
  4921. @see getLastModificationTime, getLastAccessTime
  4922. */
  4923. const Time getCreationTime() const throw();
  4924. /** Changes the modification 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 getLastModificationTime, setLastAccessTime, setCreationTime
  4928. */
  4929. bool setLastModificationTime (const Time& newTime) const throw();
  4930. /** Changes the last-access time 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 getLastAccessTime, setLastModificationTime, setCreationTime
  4934. */
  4935. bool setLastAccessTime (const Time& newTime) const throw();
  4936. /** Changes the creation date for this file.
  4937. @param newTime the time to apply to the file
  4938. @returns true if it manages to change the file's time.
  4939. @see getCreationTime, setLastModificationTime, setLastAccessTime
  4940. */
  4941. bool setCreationTime (const Time& newTime) const throw();
  4942. /** If possible, this will try to create a version string for the given file.
  4943. The OS may be able to look at the file and give a version for it - e.g. with
  4944. executables, bundles, dlls, etc. If no version is available, this will
  4945. return an empty string.
  4946. */
  4947. const String getVersion() const throw();
  4948. /** Creates an empty file if it doesn't already exist.
  4949. If the file that this object refers to doesn't exist, this will create a file
  4950. of zero size.
  4951. If it already exists or is a directory, this method will do nothing.
  4952. @returns true if the file has been created (or if it already existed).
  4953. @see createDirectory
  4954. */
  4955. bool create() const throw();
  4956. /** Creates a new directory for this filename.
  4957. This will try to create the file as a directory, and fill also create
  4958. any parent directories it needs in order to complete the operation.
  4959. @returns true if the directory has been created successfully, (or if it
  4960. already existed beforehand).
  4961. @see create
  4962. */
  4963. bool createDirectory() const throw();
  4964. /** Deletes a file.
  4965. If this file is actually a directory, it may not be deleted correctly if it
  4966. contains files. See deleteRecursively() as a better way of deleting directories.
  4967. @returns true if the file has been successfully deleted (or if it didn't exist to
  4968. begin with).
  4969. @see deleteRecursively
  4970. */
  4971. bool deleteFile() const throw();
  4972. /** Deletes a file or directory and all its subdirectories.
  4973. If this file is a directory, this will try to delete it and all its subfolders. If
  4974. it's just a file, it will just try to delete the file.
  4975. @returns true if the file and all its subfolders have been successfully deleted
  4976. (or if it didn't exist to begin with).
  4977. @see deleteFile
  4978. */
  4979. bool deleteRecursively() const throw();
  4980. /** Moves this file or folder to the trash.
  4981. @returns true if the operation succeeded. It could fail if the trash is full, or
  4982. if the file is write-protected, so you should check the return value
  4983. and act appropriately.
  4984. */
  4985. bool moveToTrash() const throw();
  4986. /** Moves or renames a file.
  4987. Tries to move a file to a different location.
  4988. If the target file already exists, this will attempt to delete it first, and
  4989. will fail if this can't be done.
  4990. Note that the destination file isn't the directory to put it in, it's the actual
  4991. filename that you want the new file to have.
  4992. @returns true if the operation succeeds
  4993. */
  4994. bool moveFileTo (const File& targetLocation) const throw();
  4995. /** Copies a file.
  4996. Tries to copy a file to a different location.
  4997. If the target file already exists, this will attempt to delete it first, and
  4998. will fail if this can't be done.
  4999. @returns true if the operation succeeds
  5000. */
  5001. bool copyFileTo (const File& targetLocation) const throw();
  5002. /** Copies a directory.
  5003. Tries to copy an entire directory, recursively.
  5004. If this file isn't a directory or if any target files can't be created, this
  5005. will return false.
  5006. @param newDirectory the directory that this one should be copied to. Note that this
  5007. is the name of the actual directory to create, not the directory
  5008. into which the new one should be placed, so there must be enough
  5009. write privileges to create it if it doesn't exist. Any files inside
  5010. it will be overwritten by similarly named ones that are copied.
  5011. */
  5012. bool copyDirectoryTo (const File& newDirectory) const throw();
  5013. /** Used in file searching, to specify whether to return files, directories, or both.
  5014. */
  5015. enum TypesOfFileToFind
  5016. {
  5017. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5018. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5019. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5020. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5021. };
  5022. /** Searches inside a directory for files matching a wildcard pattern.
  5023. Assuming that this file is a directory, this method will search it
  5024. for either files or subdirectories whose names match a filename pattern.
  5025. @param results an array to which File objects will be added for the
  5026. files that the search comes up with
  5027. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5028. return files, directories, or both. If the ignoreHiddenFiles flag
  5029. is also added to this value, hidden files won't be returned
  5030. @param searchRecursively if true, all subdirectories will be recursed into to do
  5031. an exhaustive search
  5032. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5033. @returns the number of results that have been found
  5034. @see getNumberOfChildFiles, DirectoryIterator
  5035. */
  5036. int findChildFiles (OwnedArray<File>& results,
  5037. const int whatToLookFor,
  5038. const bool searchRecursively,
  5039. const String& wildCardPattern = JUCE_T("*")) const throw();
  5040. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5041. Assuming that this file is a directory, this method will search it
  5042. for either files or subdirectories whose names match a filename pattern,
  5043. and will return the number of matches found.
  5044. This isn't a recursive call, and will only search this directory, not
  5045. its children.
  5046. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5047. count files, directories, or both. If the ignoreHiddenFiles flag
  5048. is also added to this value, hidden files won't be counted
  5049. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5050. @returns the number of matches found
  5051. @see findChildFiles, DirectoryIterator
  5052. */
  5053. int getNumberOfChildFiles (const int whatToLookFor,
  5054. const String& wildCardPattern = JUCE_T("*")) const throw();
  5055. /** Returns true if this file is a directory that contains one or more subdirectories.
  5056. @see isDirectory, findChildFiles
  5057. */
  5058. bool containsSubDirectories() const throw();
  5059. /** Creates a stream to read from this file.
  5060. @returns a stream that will read from this file (initially positioned at the
  5061. start of the file), or 0 if the file can't be opened for some reason
  5062. @see createOutputStream, loadFileAsData
  5063. */
  5064. FileInputStream* createInputStream() const throw();
  5065. /** Creates a stream to write to this file.
  5066. If the file exists, the stream that is returned will be positioned ready for
  5067. writing at the end of the file, so you might want to use deleteFile() first
  5068. to write to an empty file.
  5069. @returns a stream that will write to this file (initially positioned at the
  5070. end of the file), or 0 if the file can't be opened for some reason
  5071. @see createInputStream, printf, appendData, appendText
  5072. */
  5073. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5074. /** Loads a file's contents into memory as a block of binary data.
  5075. Of course, trying to load a very large file into memory will blow up, so
  5076. it's better to check first.
  5077. @param result the data block to which the file's contents should be appended - note
  5078. that if the memory block might already contain some data, you
  5079. might want to clear it first
  5080. @returns true if the file could all be read into memory
  5081. */
  5082. bool loadFileAsData (MemoryBlock& result) const throw();
  5083. /** Reads a file into memory as a string.
  5084. Attempts to load the entire file as a zero-terminated string.
  5085. This makes use of InputStream::readEntireStreamAsString, which should
  5086. automatically cope with unicode/acsii file formats.
  5087. */
  5088. const String loadFileAsString() const throw();
  5089. /** Writes text to the end of the file.
  5090. This will try to do a printf to the file.
  5091. @returns false if it can't write to the file for some reason
  5092. */
  5093. bool printf (const tchar* format, ...) const throw();
  5094. /** Appends a block of binary data to the end of the file.
  5095. This will try to write the given buffer to the end of the file.
  5096. @returns false if it can't write to the file for some reason
  5097. */
  5098. bool appendData (const void* const dataToAppend,
  5099. const int numberOfBytes) const throw();
  5100. /** Replaces this file's contents with a given block of data.
  5101. This will delete the file and replace it with the given data.
  5102. A nice feature of this method is that it's safe - instead of deleting
  5103. the file first and then re-writing it, it creates a new temporary file,
  5104. writes the data to that, and then moves the new file to replace the existing
  5105. file. This means that if the power gets pulled out or something crashes,
  5106. you're a lot less likely to end up with an empty file..
  5107. Returns true if the operation succeeds, or false if it fails.
  5108. @see appendText
  5109. */
  5110. bool replaceWithData (const void* const dataToWrite,
  5111. const int numberOfBytes) const throw();
  5112. /** Appends a string to the end of the file.
  5113. This will try to append a text string to the file, as either 16-bit unicode
  5114. or 8-bit characters in the default system encoding.
  5115. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5116. the endianness of the file.
  5117. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5118. @see replaceWithText
  5119. */
  5120. bool appendText (const String& textToAppend,
  5121. const bool asUnicode = false,
  5122. const bool writeUnicodeHeaderBytes = false) const throw();
  5123. /** Replaces this file's contents with a given text string.
  5124. This will delete the file and replace it with the given text.
  5125. A nice feature of this method is that it's safe - instead of deleting
  5126. the file first and then re-writing it, it creates a new temporary file,
  5127. writes the text to that, and then moves the new file to replace the existing
  5128. file. This means that if the power gets pulled out or something crashes,
  5129. you're a lot less likely to end up with an empty file..
  5130. For an explanation of the parameters here, see the appendText() method.
  5131. Returns true if the operation succeeds, or false if it fails.
  5132. @see appendText
  5133. */
  5134. bool replaceWithText (const String& textToWrite,
  5135. const bool asUnicode = false,
  5136. const bool writeUnicodeHeaderBytes = false) const throw();
  5137. /** Creates a set of files to represent each file root.
  5138. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5139. to which ones are available. On the Mac/Linux, this will probably
  5140. just add a single entry for "/".
  5141. */
  5142. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5143. /** Finds the name of the drive on which this file lives.
  5144. @returns the volume label of the drive, or an empty string if this isn't possible
  5145. */
  5146. const String getVolumeLabel() const throw();
  5147. /** Returns the serial number of the volume on which this file lives.
  5148. @returns the serial number, or zero if there's a problem doing this
  5149. */
  5150. int getVolumeSerialNumber() const throw();
  5151. /** Returns the number of bytes free on the drive that this file lives on.
  5152. @returns the number of bytes free, or 0 if there's a problem finding this out
  5153. @see getVolumeTotalSize
  5154. */
  5155. int64 getBytesFreeOnVolume() const throw();
  5156. /** Returns the total size of the drive that contains this file.
  5157. @returns the total number of bytes that the volume can hold
  5158. @see getBytesFreeOnVolume
  5159. */
  5160. int64 getVolumeTotalSize() const throw();
  5161. /** Returns true if this file is on a CD or DVD drive. */
  5162. bool isOnCDRomDrive() const throw();
  5163. /** Returns true if this file is on a hard disk.
  5164. This will fail if it's a network drive, but will still be true for
  5165. removable hard-disks.
  5166. */
  5167. bool isOnHardDisk() const throw();
  5168. /** Returns true if this file is on a removable disk drive.
  5169. This might be a usb-drive, a CD-rom, or maybe a network drive.
  5170. */
  5171. bool isOnRemovableDrive() const throw();
  5172. /** Launches the file as a process.
  5173. - if the file is executable, this will run it.
  5174. - if it's a document of some kind, it will launch the document with its
  5175. default viewer application.
  5176. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  5177. */
  5178. bool startAsProcess (const String& parameters = String::empty) const throw();
  5179. /** A set of types of location that can be passed to the getSpecialLocation() method.
  5180. */
  5181. enum SpecialLocationType
  5182. {
  5183. /** The user's home folder. This is the same as using File ("~"). */
  5184. userHomeDirectory,
  5185. /** The user's default documents folder. On Windows, this might be the user's
  5186. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  5187. doesn't tend to have one of these, so it might just return their home folder.
  5188. */
  5189. userDocumentsDirectory,
  5190. /** The folder that contains the user's desktop objects. */
  5191. userDesktopDirectory,
  5192. /** The folder in which applications store their persistent user-specific settings.
  5193. On Windows, this might be "\Documents and Settings\username\Application Data".
  5194. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  5195. always create your own sub-folder to put them in, to avoid making a mess.
  5196. */
  5197. userApplicationDataDirectory,
  5198. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  5199. of the computer, rather than just the current user.
  5200. On the Mac it'll be "/Library", on Windows, it could be something like
  5201. "\Documents and Settings\All Users\Application Data".
  5202. Depending on the setup, this folder may be read-only.
  5203. */
  5204. commonApplicationDataDirectory,
  5205. /** The folder that should be used for temporary files.
  5206. Always delete them when you're finished, to keep the user's computer tidy!
  5207. */
  5208. tempDirectory,
  5209. /** Returns this application's executable file.
  5210. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5211. host app.
  5212. On the mac this will return the unix binary, not the package folder - see
  5213. currentApplicationFile for that.
  5214. */
  5215. currentExecutableFile,
  5216. /** Returns this application's location.
  5217. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  5218. host app.
  5219. On the mac this will return the package folder (if it's in one), not the unix binary
  5220. that's inside it - compare with currentExecutableFile.
  5221. */
  5222. currentApplicationFile,
  5223. /** The directory in which applications normally get installed.
  5224. So on windows, this would be something like "c:\program files", on the
  5225. Mac "/Applications", or "/usr" on linux.
  5226. */
  5227. globalApplicationsDirectory,
  5228. /** The most likely place where a user might store their music files.
  5229. */
  5230. userMusicDirectory,
  5231. /** The most likely place where a user might store their movie files.
  5232. */
  5233. userMoviesDirectory,
  5234. };
  5235. /** Finds the location of a special type of file or directory, such as a home folder or
  5236. documents folder.
  5237. @see SpecialLocationType
  5238. */
  5239. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  5240. /** Returns a temporary file in the system's temp directory.
  5241. This will try to return the name of a non-existent temp file.
  5242. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  5243. */
  5244. static const File createTempFile (const String& fileNameEnding) throw();
  5245. /** Returns the current working directory.
  5246. @see setAsCurrentWorkingDirectory
  5247. */
  5248. static const File getCurrentWorkingDirectory() throw();
  5249. /** Sets the current working directory to be this file.
  5250. For this to work the file must point to a valid directory.
  5251. @returns true if the current directory has been changed.
  5252. @see getCurrentWorkingDirectory
  5253. */
  5254. bool setAsCurrentWorkingDirectory() const throw();
  5255. /** The system-specific file separator character.
  5256. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5257. */
  5258. static const tchar separator;
  5259. /** The system-specific file separator character, as a string.
  5260. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  5261. */
  5262. static const tchar* separatorString;
  5263. /** Removes illegal characters from a filename.
  5264. This will return a copy of the given string after removing characters
  5265. that are not allowed in a legal filename, and possibly shortening the
  5266. string if it's too long.
  5267. Because this will remove slashes, don't use it on an absolute pathname.
  5268. @see createLegalPathName
  5269. */
  5270. static const String createLegalFileName (const String& fileNameToFix) throw();
  5271. /** Removes illegal characters from a pathname.
  5272. Similar to createLegalFileName(), but this won't remove slashes, so can
  5273. be used on a complete pathname.
  5274. @see createLegalFileName
  5275. */
  5276. static const String createLegalPathName (const String& pathNameToFix) throw();
  5277. /** Indicates whether filenames are case-sensitive on the current operating system.
  5278. */
  5279. static bool areFileNamesCaseSensitive();
  5280. /** Returns true if the string seems to be a fully-specified absolute path.
  5281. */
  5282. static bool isAbsolutePath (const String& path) throw();
  5283. juce_UseDebuggingNewOperator
  5284. private:
  5285. String fullPath;
  5286. // internal way of contructing a file without checking the path
  5287. friend class DirectoryIterator;
  5288. File (const String&, int) throw();
  5289. const String getPathUpToLastSlash() const throw();
  5290. };
  5291. #endif // __JUCE_FILE_JUCEHEADER__
  5292. /********* End of inlined file: juce_File.h *********/
  5293. /**
  5294. A simple implemenation of a Logger that writes to a file.
  5295. @see Logger
  5296. */
  5297. class JUCE_API FileLogger : public Logger
  5298. {
  5299. public:
  5300. /** Creates a FileLogger for a given file.
  5301. @param fileToWriteTo the file that to use - new messages will be appended
  5302. to the file. If the file doesn't exist, it will be created,
  5303. along with any parent directories that are needed.
  5304. @param welcomeMessage when opened, the logger will write a header to the log, along
  5305. with the current date and time, and this welcome message
  5306. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  5307. but is larger than this number of bytes, then the start of the
  5308. file will be truncated to keep the size down. This prevents a log
  5309. file getting ridiculously large over time. The file will be truncated
  5310. at a new-line boundary. If this value is less than zero, no size limit
  5311. will be imposed; if it's zero, the file will always be deleted. Note that
  5312. the size is only checked once when this object is created - any logging
  5313. that is done later will be appended without any checking
  5314. */
  5315. FileLogger (const File& fileToWriteTo,
  5316. const String& welcomeMessage,
  5317. const int maxInitialFileSizeBytes = 128 * 1024);
  5318. /** Destructor. */
  5319. ~FileLogger();
  5320. void logMessage (const String& message);
  5321. /** Helper function to create a log file in the correct place for this platform.
  5322. On Windows this will return a logger with a path such as:
  5323. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  5324. On the Mac it'll create something like:
  5325. ~/Library/Logs/[logFileName]
  5326. The method might return 0 if the file can't be created for some reason.
  5327. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  5328. it's best to use the something like the name of your application here.
  5329. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  5330. call it "log.txt" because if it goes in a directory with logs
  5331. from other applications (as it will do on the Mac) then no-one
  5332. will know which one is yours!
  5333. @param welcomeMessage a message that will be written to the log when it's opened.
  5334. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  5335. */
  5336. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  5337. const String& logFileName,
  5338. const String& welcomeMessage,
  5339. const int maxInitialFileSizeBytes = 128 * 1024);
  5340. juce_UseDebuggingNewOperator
  5341. private:
  5342. File logFile;
  5343. CriticalSection logLock;
  5344. FileOutputStream* logStream;
  5345. void trimFileSize (int maxFileSizeBytes) const;
  5346. FileLogger (const FileLogger&);
  5347. const FileLogger& operator= (const FileLogger&);
  5348. };
  5349. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  5350. /********* End of inlined file: juce_FileLogger.h *********/
  5351. #endif
  5352. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5353. /********* Start of inlined file: juce_Initialisation.h *********/
  5354. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  5355. #define __JUCE_INITIALISATION_JUCEHEADER__
  5356. /** Initialises Juce's GUI classes.
  5357. If you're embedding Juce into an application that uses its own event-loop rather
  5358. than using the START_JUCE_APPLICATION macro, call this function before making any
  5359. Juce calls, to make sure things are initialised correctly.
  5360. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5361. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5362. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  5363. */
  5364. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  5365. /** Clears up any static data being used by Juce's GUI classes.
  5366. If you're embedding Juce into an application that uses its own event-loop rather
  5367. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  5368. code to clean up any juce objects that might be lying around.
  5369. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  5370. */
  5371. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  5372. /** Initialises the core parts of Juce.
  5373. If you're embedding Juce into either a command-line program, call this function
  5374. at the start of your main() function to make sure that Juce is initialised correctly.
  5375. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  5376. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  5377. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  5378. */
  5379. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  5380. /** Clears up any static data being used by Juce's non-gui core classes.
  5381. If you're embedding Juce into either a command-line program, call this function
  5382. at the end of your main() function if you want to make sure any Juce objects are
  5383. cleaned up correctly.
  5384. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  5385. */
  5386. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  5387. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  5388. /********* End of inlined file: juce_Initialisation.h *********/
  5389. #endif
  5390. #ifndef __JUCE_LOGGER_JUCEHEADER__
  5391. #endif
  5392. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  5393. #endif
  5394. #ifndef __JUCE_MEMORY_JUCEHEADER__
  5395. #endif
  5396. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5397. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  5398. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5399. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5400. /** A timer for measuring performance of code and dumping the results to a file.
  5401. e.g. @code
  5402. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  5403. for (;;)
  5404. {
  5405. pc.start();
  5406. doSomethingFishy();
  5407. pc.stop();
  5408. }
  5409. @endcode
  5410. In this example, the time of each period between calling start/stop will be
  5411. measured and averaged over 50 runs, and the results printed to a file
  5412. every 50 times round the loop.
  5413. */
  5414. class JUCE_API PerformanceCounter
  5415. {
  5416. public:
  5417. /** Creates a PerformanceCounter object.
  5418. @param counterName the name used when printing out the statistics
  5419. @param runsPerPrintout the number of start/stop iterations before calling
  5420. printStatistics()
  5421. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  5422. the results are just written to the debugger output
  5423. */
  5424. PerformanceCounter (const String& counterName,
  5425. int runsPerPrintout = 100,
  5426. const File& loggingFile = File::nonexistent);
  5427. /** Destructor. */
  5428. ~PerformanceCounter();
  5429. /** Starts timing.
  5430. @see stop
  5431. */
  5432. void start();
  5433. /** Stops timing and prints out the results.
  5434. The number of iterations before doing a printout of the
  5435. results is set in the constructor.
  5436. @see start
  5437. */
  5438. void stop();
  5439. /** Dumps the current metrics to the debugger output and to a file.
  5440. As well as using Logger::outputDebugString to print the results,
  5441. this will write then to the file specified in the constructor (if
  5442. this was valid).
  5443. */
  5444. void printStatistics();
  5445. juce_UseDebuggingNewOperator
  5446. private:
  5447. String name;
  5448. int numRuns, runsPerPrint;
  5449. double totalTime;
  5450. int64 started;
  5451. File outputFile;
  5452. };
  5453. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  5454. /********* End of inlined file: juce_PerformanceCounter.h *********/
  5455. #endif
  5456. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  5457. #endif
  5458. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5459. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  5460. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5461. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5462. /**
  5463. A collection of miscellaneous platform-specific utilities.
  5464. */
  5465. class JUCE_API PlatformUtilities
  5466. {
  5467. public:
  5468. /** Plays the operating system's default alert 'beep' sound. */
  5469. static void beep();
  5470. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  5471. const String& emailSubject,
  5472. const String& bodyText,
  5473. const StringArray& filesToAttach);
  5474. #if JUCE_MAC || DOXYGEN
  5475. /** MAC ONLY - Turns a Core CF String into a juce one. */
  5476. static const String cfStringToJuceString (CFStringRef cfString);
  5477. /** MAC ONLY - Turns a juce string into a Core CF one. */
  5478. static CFStringRef juceStringToCFString (const String& s);
  5479. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  5480. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  5481. /** MAC ONLY - Turns an FSRef into a juce string path. */
  5482. static const String makePathFromFSRef (FSRef* file);
  5483. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  5484. their precomposed equivalents.
  5485. */
  5486. static const String convertToPrecomposedUnicode (const String& s);
  5487. /** MAC ONLY - Gets the type of a file from the file's resources. */
  5488. static OSType getTypeOfFile (const String& filename);
  5489. /** MAC ONLY - Returns true if this file is actually a bundle. */
  5490. static bool isBundle (const String& filename);
  5491. /** MAC ONLY - Adds an item to the dock */
  5492. static void addItemToDock (const File& file);
  5493. #endif
  5494. #if JUCE_WIN32 || DOXYGEN
  5495. // Some registry helper functions:
  5496. /** WIN32 ONLY - Returns a string from the registry.
  5497. The path is a string for the entire path of a value in the registry,
  5498. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  5499. */
  5500. static const String getRegistryValue (const String& regValuePath,
  5501. const String& defaultValue = String::empty);
  5502. /** WIN32 ONLY - Sets a registry value as a string.
  5503. This will take care of creating any groups needed to get to the given
  5504. registry value.
  5505. */
  5506. static void setRegistryValue (const String& regValuePath,
  5507. const String& value);
  5508. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  5509. static bool registryValueExists (const String& regValuePath);
  5510. /** WIN32 ONLY - Deletes a registry value. */
  5511. static void deleteRegistryValue (const String& regValuePath);
  5512. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  5513. static void deleteRegistryKey (const String& regKeyPath);
  5514. /** WIN32 ONLY - Creates a file association in the registry.
  5515. This lets you set the exe that should be launched by a given file extension.
  5516. @param fileExtension the file extension to associate, including the
  5517. initial dot, e.g. ".txt"
  5518. @param symbolicDescription a space-free short token to identify the file type
  5519. @param fullDescription a human-readable description of the file type
  5520. @param targetExecutable the executable that should be launched
  5521. @param iconResourceNumber the icon that gets displayed for the file type will be
  5522. found by looking up this resource number in the
  5523. executable. Pass 0 here to not use an icon
  5524. */
  5525. static void registerFileAssociation (const String& fileExtension,
  5526. const String& symbolicDescription,
  5527. const String& fullDescription,
  5528. const File& targetExecutable,
  5529. int iconResourceNumber);
  5530. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  5531. In a normal Juce application this will be set to the module handle
  5532. of the application executable.
  5533. If you're writing a DLL using Juce and plan to use any Juce messaging or
  5534. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  5535. to set the correct module handle in your DllMain() function, because
  5536. the win32 system relies on the correct instance handle when opening windows.
  5537. */
  5538. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  5539. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  5540. @see getCurrentModuleInstanceHandle()
  5541. */
  5542. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  5543. /** WIN32 ONLY - Gets the command-line params as a string.
  5544. This is needed to avoid unicode problems with the argc type params.
  5545. */
  5546. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  5547. #endif
  5548. /** Clears the floating point unit's flags.
  5549. Only has an effect under win32, currently.
  5550. */
  5551. static void fpuReset();
  5552. #if JUCE_LINUX || JUCE_WIN32
  5553. /** Loads a dynamically-linked library into the process's address space.
  5554. @param pathOrFilename the platform-dependent name and search path
  5555. @returns a handle which can be used by getProcedureEntryPoint(), or
  5556. zero if it fails.
  5557. @see freeDynamicLibrary, getProcedureEntryPoint
  5558. */
  5559. static void* loadDynamicLibrary (const String& pathOrFilename);
  5560. /** Frees a dynamically-linked library.
  5561. @param libraryHandle a handle created by loadDynamicLibrary
  5562. @see loadDynamicLibrary, getProcedureEntryPoint
  5563. */
  5564. static void freeDynamicLibrary (void* libraryHandle);
  5565. /** Finds a procedure call in a dynamically-linked library.
  5566. @param libraryHandle a library handle returned by loadDynamicLibrary
  5567. @param procedureName the name of the procedure call to try to load
  5568. @returns a pointer to the function if found, or 0 if it fails
  5569. @see loadDynamicLibrary
  5570. */
  5571. static void* getProcedureEntryPoint (void* libraryHandle,
  5572. const String& procedureName);
  5573. #endif
  5574. #if JUCE_LINUX || DOXYGEN
  5575. #endif
  5576. };
  5577. #if JUCE_MAC
  5578. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  5579. using RAII.
  5580. */
  5581. class ScopedAutoReleasePool
  5582. {
  5583. public:
  5584. ScopedAutoReleasePool();
  5585. ~ScopedAutoReleasePool();
  5586. private:
  5587. void* pool;
  5588. };
  5589. /**
  5590. A wrapper class for picking up events from an Apple IR remote control device.
  5591. To use it, just create a subclass of this class, implementing the buttonPressed()
  5592. callback, then call start() and stop() to start or stop receiving events.
  5593. */
  5594. class JUCE_API AppleRemoteDevice
  5595. {
  5596. public:
  5597. AppleRemoteDevice();
  5598. virtual ~AppleRemoteDevice();
  5599. /** The set of buttons that may be pressed.
  5600. @see buttonPressed
  5601. */
  5602. enum ButtonType
  5603. {
  5604. menuButton = 0, /**< The menu button (if it's held for a short time). */
  5605. playButton, /**< The play button. */
  5606. plusButton, /**< The plus or volume-up button. */
  5607. minusButton, /**< The minus or volume-down button. */
  5608. rightButton, /**< The right button (if it's held for a short time). */
  5609. leftButton, /**< The left button (if it's held for a short time). */
  5610. rightButton_Long, /**< The right button (if it's held for a long time). */
  5611. leftButton_Long, /**< The menu button (if it's held for a long time). */
  5612. menuButton_Long, /**< The menu button (if it's held for a long time). */
  5613. playButtonSleepMode,
  5614. switched
  5615. };
  5616. /** Override this method to receive the callback about a button press.
  5617. The callback will happen on the application's message thread.
  5618. Some buttons trigger matching up and down events, in which the isDown parameter
  5619. will be true and then false. Others only send a single event when the
  5620. button is pressed.
  5621. */
  5622. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  5623. /** Starts the device running and responding to events.
  5624. Returns true if it managed to open the device.
  5625. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  5626. and will not be available to any other part of the system. If
  5627. false, it will be shared with other apps.
  5628. @see stop
  5629. */
  5630. bool start (const bool inExclusiveMode) throw();
  5631. /** Stops the device running.
  5632. @see start
  5633. */
  5634. void stop() throw();
  5635. /** Returns true if the device has been started successfully.
  5636. */
  5637. bool isActive() const throw();
  5638. /** Returns the ID number of the remote, if it has sent one.
  5639. */
  5640. int getRemoteId() const throw() { return remoteId; }
  5641. juce_UseDebuggingNewOperator
  5642. /** @internal */
  5643. void handleCallbackInternal();
  5644. private:
  5645. void* device;
  5646. void* queue;
  5647. int remoteId;
  5648. bool open (const bool openInExclusiveMode) throw();
  5649. };
  5650. #endif
  5651. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  5652. /********* End of inlined file: juce_PlatformUtilities.h *********/
  5653. #endif
  5654. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5655. /********* Start of inlined file: juce_Random.h *********/
  5656. #ifndef __JUCE_RANDOM_JUCEHEADER__
  5657. #define __JUCE_RANDOM_JUCEHEADER__
  5658. /********* Start of inlined file: juce_BitArray.h *********/
  5659. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  5660. #define __JUCE_BITARRAY_JUCEHEADER__
  5661. class MemoryBlock;
  5662. /**
  5663. An array of on/off bits, also usable to store large binary integers.
  5664. A BitArray acts like an arbitrarily large integer whose bits can be set or
  5665. cleared, and some basic mathematical operations can be done on the number as
  5666. a whole.
  5667. */
  5668. class JUCE_API BitArray
  5669. {
  5670. public:
  5671. /** Creates an empty BitArray */
  5672. BitArray() throw();
  5673. /** Creates a BitArray containing an integer value in its low bits.
  5674. The low 32 bits of the array are initialised with this value.
  5675. */
  5676. BitArray (const unsigned int value) throw();
  5677. /** Creates a BitArray containing an integer value in its low bits.
  5678. The low 32 bits of the array are initialised with the absolute value
  5679. passed in, and its sign is set to reflect the sign of the number.
  5680. */
  5681. BitArray (const int value) throw();
  5682. /** Creates a BitArray containing an integer value in its low bits.
  5683. The low 64 bits of the array are initialised with the absolute value
  5684. passed in, and its sign is set to reflect the sign of the number.
  5685. */
  5686. BitArray (int64 value) throw();
  5687. /** Creates a copy of another BitArray. */
  5688. BitArray (const BitArray& other) throw();
  5689. /** Destructor. */
  5690. ~BitArray() throw();
  5691. /** Copies another BitArray onto this one. */
  5692. const BitArray& operator= (const BitArray& other) throw();
  5693. /** Two arrays are the same if the same bits are set. */
  5694. bool operator== (const BitArray& other) const throw();
  5695. /** Two arrays are the same if the same bits are set. */
  5696. bool operator!= (const BitArray& other) const throw();
  5697. /** Clears all bits in the BitArray to 0. */
  5698. void clear() throw();
  5699. /** Clears a particular bit in the array. */
  5700. void clearBit (const int bitNumber) throw();
  5701. /** Sets a specified bit to 1.
  5702. If the bit number is high, this will grow the array to accomodate it.
  5703. */
  5704. void setBit (const int bitNumber) throw();
  5705. /** Sets or clears a specified bit. */
  5706. void setBit (const int bitNumber,
  5707. const bool shouldBeSet) throw();
  5708. /** Sets a range of bits to be either on or off.
  5709. @param startBit the first bit to change
  5710. @param numBits the number of bits to change
  5711. @param shouldBeSet whether to turn these bits on or off
  5712. */
  5713. void setRange (int startBit,
  5714. int numBits,
  5715. const bool shouldBeSet) throw();
  5716. /** Inserts a bit an a given position, shifting up any bits above it. */
  5717. void insertBit (const int bitNumber,
  5718. const bool shouldBeSet) throw();
  5719. /** Returns the value of a specified bit in the array.
  5720. If the index is out-of-range, the result will be false.
  5721. */
  5722. bool operator[] (const int bit) const throw();
  5723. /** Returns true if no bits are set. */
  5724. bool isEmpty() const throw();
  5725. /** Returns a range of bits in the array as a new BitArray.
  5726. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  5727. @see getBitRangeAsInt
  5728. */
  5729. const BitArray getBitRange (int startBit, int numBits) const throw();
  5730. /** Returns a range of bits in the array as an integer value.
  5731. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  5732. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  5733. getBitRange().
  5734. */
  5735. int getBitRangeAsInt (int startBit, int numBits) const throw();
  5736. /** Sets a range of bits in the array based on an integer value.
  5737. Copies the given integer into the array, starting at startBit,
  5738. and only using up to numBits of the available bits.
  5739. */
  5740. void setBitRangeAsInt (int startBit, int numBits,
  5741. unsigned int valueToSet) throw();
  5742. /** Performs a bitwise OR with another BitArray.
  5743. The result ends up in this array.
  5744. */
  5745. void orWith (const BitArray& other) throw();
  5746. /** Performs a bitwise AND with another BitArray.
  5747. The result ends up in this array.
  5748. */
  5749. void andWith (const BitArray& other) throw();
  5750. /** Performs a bitwise XOR with another BitArray.
  5751. The result ends up in this array.
  5752. */
  5753. void xorWith (const BitArray& other) throw();
  5754. /** Adds another BitArray's value to this one.
  5755. Treating the two arrays as large positive integers, this
  5756. adds them up and puts the result in this array.
  5757. */
  5758. void add (const BitArray& other) throw();
  5759. /** Subtracts another BitArray's value from this one.
  5760. Treating the two arrays as large positive integers, this
  5761. subtracts them and puts the result in this array.
  5762. Note that if the result should be negative, this won't be
  5763. handled correctly.
  5764. */
  5765. void subtract (const BitArray& other) throw();
  5766. /** Multiplies another BitArray's value with this one.
  5767. Treating the two arrays as large positive integers, this
  5768. multiplies them and puts the result in this array.
  5769. */
  5770. void multiplyBy (const BitArray& other) throw();
  5771. /** Divides another BitArray's value into this one and also produces a remainder.
  5772. Treating the two arrays as large positive integers, this
  5773. divides this value by the other, leaving the quotient in this
  5774. array, and the remainder is copied into the other BitArray passed in.
  5775. */
  5776. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  5777. /** Returns the largest value that will divide both this value and the one
  5778. passed-in.
  5779. */
  5780. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  5781. /** Performs a modulo operation on this value.
  5782. The result is stored in this value.
  5783. */
  5784. void modulo (const BitArray& divisor) throw();
  5785. /** Performs a combined exponent and modulo operation.
  5786. This BitArray's value becomes (this ^ exponent) % modulus.
  5787. */
  5788. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  5789. /** Performs an inverse modulo on the value.
  5790. i.e. the result is (this ^ -1) mod (modulus).
  5791. */
  5792. void inverseModulo (const BitArray& modulus) throw();
  5793. /** Shifts a section of bits left or right.
  5794. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  5795. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  5796. */
  5797. void shiftBits (int howManyBitsLeft,
  5798. int startBit = 0) throw();
  5799. /** Does a signed comparison of two BitArrays.
  5800. Return values are:
  5801. - 0 if the numbers are the same
  5802. - < 0 if this number is smaller than the other
  5803. - > 0 if this number is bigger than the other
  5804. */
  5805. int compare (const BitArray& other) const throw();
  5806. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  5807. Return values are:
  5808. - 0 if the numbers are the same
  5809. - < 0 if this number is smaller than the other
  5810. - > 0 if this number is bigger than the other
  5811. */
  5812. int compareAbsolute (const BitArray& other) const throw();
  5813. /** Returns true if the value is less than zero.
  5814. @see setNegative, negate
  5815. */
  5816. bool isNegative() const throw();
  5817. /** Changes the sign of the number to be positive or negative.
  5818. @see isNegative, negate
  5819. */
  5820. void setNegative (const bool shouldBeNegative) throw();
  5821. /** Inverts the sign of the number.
  5822. @see isNegative, setNegative
  5823. */
  5824. void negate() throw();
  5825. /** Counts the total number of set bits in the array. */
  5826. int countNumberOfSetBits() const throw();
  5827. /** Looks for the index of the next set bit after a given starting point.
  5828. searches from startIndex (inclusive) upwards for the first set bit,
  5829. and returns its index.
  5830. If no set bits are found, it returns -1.
  5831. */
  5832. int findNextSetBit (int startIndex = 0) const throw();
  5833. /** Looks for the index of the next clear bit after a given starting point.
  5834. searches from startIndex (inclusive) upwards for the first clear bit,
  5835. and returns its index.
  5836. */
  5837. int findNextClearBit (int startIndex = 0) const throw();
  5838. /** Returns the index of the highest set bit in the array.
  5839. If the array is empty, this will return -1.
  5840. */
  5841. int getHighestBit() const throw();
  5842. /** Converts the array to a number string.
  5843. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5844. If minuimumNumCharacters is greater than 0, the returned string will be
  5845. padded with leading zeros to reach at least that length.
  5846. */
  5847. const String toString (const int base, const int minimumNumCharacters = 1) const throw();
  5848. /** Converts a number string to an array.
  5849. Any non-valid characters will be ignored.
  5850. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  5851. */
  5852. void parseString (const String& text,
  5853. const int base) throw();
  5854. /** Turns the array into a block of binary data.
  5855. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5856. of the array, and so on.
  5857. @see loadFromMemoryBlock
  5858. */
  5859. const MemoryBlock toMemoryBlock() const throw();
  5860. /** Copies a block of raw data onto this array.
  5861. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  5862. of the array, and so on.
  5863. @see toMemoryBlock
  5864. */
  5865. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  5866. juce_UseDebuggingNewOperator
  5867. private:
  5868. void ensureSize (const int numVals) throw();
  5869. unsigned int* values;
  5870. int numValues, highestBit;
  5871. bool negative;
  5872. };
  5873. #endif // __JUCE_BITARRAY_JUCEHEADER__
  5874. /********* End of inlined file: juce_BitArray.h *********/
  5875. /**
  5876. A simple pseudo-random number generator.
  5877. */
  5878. class JUCE_API Random
  5879. {
  5880. public:
  5881. /** Creates a Random object based on a seed value.
  5882. For a given seed value, the subsequent numbers generated by this object
  5883. will be predictable, so a good idea is to set this value based
  5884. on the time, e.g.
  5885. new Random (Time::currentTimeMillis())
  5886. */
  5887. Random (const int64 seedValue) throw();
  5888. /** Destructor. */
  5889. ~Random() throw();
  5890. /** Returns the next random 32 bit integer.
  5891. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  5892. */
  5893. int nextInt() throw();
  5894. /** Returns the next random number, limited to a given range.
  5895. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  5896. */
  5897. int nextInt (const int maxValue) throw();
  5898. /** Returns the next 64-bit random number.
  5899. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  5900. */
  5901. int64 nextInt64() throw();
  5902. /** Returns the next random floating-point number.
  5903. @returns a random value in the range 0 to 1.0
  5904. */
  5905. float nextFloat() throw();
  5906. /** Returns the next random floating-point number.
  5907. @returns a random value in the range 0 to 1.0
  5908. */
  5909. double nextDouble() throw();
  5910. /** Returns the next random boolean value.
  5911. */
  5912. bool nextBool() throw();
  5913. /** Returns a BitArray containing a random number.
  5914. @returns a random value in the range 0 to (maximumValue - 1).
  5915. */
  5916. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  5917. /** Sets a range of bits in a BitArray to random values. */
  5918. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  5919. /** To avoid the overhead of having to create a new Random object whenever
  5920. you need a number, this is a shared application-wide object that
  5921. can be used.
  5922. It's not thread-safe though, so threads should use their own Random object.
  5923. */
  5924. static Random& getSystemRandom() throw();
  5925. /** Resets this Random object to a given seed value. */
  5926. void setSeed (const int64 newSeed) throw();
  5927. /** Reseeds this generator using a value generated from various semi-random system
  5928. properties like the current time, etc.
  5929. Because this function convolves the time with the last seed value, calling
  5930. it repeatedly will increase the randomness of the final result.
  5931. */
  5932. void setSeedRandomly();
  5933. juce_UseDebuggingNewOperator
  5934. private:
  5935. int64 seed;
  5936. };
  5937. #endif // __JUCE_RANDOM_JUCEHEADER__
  5938. /********* End of inlined file: juce_Random.h *********/
  5939. #endif
  5940. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5941. #endif
  5942. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5943. /********* Start of inlined file: juce_Singleton.h *********/
  5944. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  5945. #define __JUCE_SINGLETON_JUCEHEADER__
  5946. /********* Start of inlined file: juce_ScopedLock.h *********/
  5947. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  5948. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  5949. /**
  5950. Automatically locks and unlocks a CriticalSection object.
  5951. Use one of these as a local variable to control access to a CriticalSection.
  5952. e.g. @code
  5953. CriticalSection myCriticalSection;
  5954. for (;;)
  5955. {
  5956. const ScopedLock myScopedLock (myCriticalSection);
  5957. // myCriticalSection is now locked
  5958. ...do some stuff...
  5959. // myCriticalSection gets unlocked here.
  5960. }
  5961. @endcode
  5962. @see CriticalSection, ScopedUnlock
  5963. */
  5964. class JUCE_API ScopedLock
  5965. {
  5966. public:
  5967. /** Creates a ScopedLock.
  5968. As soon as it is created, this will lock the CriticalSection, and
  5969. when the ScopedLock object is deleted, the CriticalSection will
  5970. be unlocked.
  5971. Make sure this object is created and deleted by the same thread,
  5972. otherwise there are no guarantees what will happen! Best just to use it
  5973. as a local stack object, rather than creating one with the new() operator.
  5974. */
  5975. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  5976. /** Destructor.
  5977. The CriticalSection will be unlocked when the destructor is called.
  5978. Make sure this object is created and deleted by the same thread,
  5979. otherwise there are no guarantees what will happen!
  5980. */
  5981. inline ~ScopedLock() throw() { lock_.exit(); }
  5982. private:
  5983. const CriticalSection& lock_;
  5984. ScopedLock (const ScopedLock&);
  5985. const ScopedLock& operator= (const ScopedLock&);
  5986. };
  5987. /**
  5988. Automatically unlocks and re-locks a CriticalSection object.
  5989. This is the reverse of a ScopedLock object - instead of locking the critical
  5990. section for the lifetime of this object, it unlocks it.
  5991. Make sure you don't try to unlock critical sections that aren't actually locked!
  5992. e.g. @code
  5993. CriticalSection myCriticalSection;
  5994. for (;;)
  5995. {
  5996. const ScopedLock myScopedLock (myCriticalSection);
  5997. // myCriticalSection is now locked
  5998. ... do some stuff with it locked ..
  5999. while (xyz)
  6000. {
  6001. ... do some stuff with it locked ..
  6002. const ScopedUnlock unlocker (myCriticalSection);
  6003. // myCriticalSection is now unlocked for the remainder of this block,
  6004. // and re-locked at the end.
  6005. ...do some stuff with it unlocked ...
  6006. }
  6007. // myCriticalSection gets unlocked here.
  6008. }
  6009. @endcode
  6010. @see CriticalSection, ScopedLock
  6011. */
  6012. class ScopedUnlock
  6013. {
  6014. public:
  6015. /** Creates a ScopedUnlock.
  6016. As soon as it is created, this will unlock the CriticalSection, and
  6017. when the ScopedLock object is deleted, the CriticalSection will
  6018. be re-locked.
  6019. Make sure this object is created and deleted by the same thread,
  6020. otherwise there are no guarantees what will happen! Best just to use it
  6021. as a local stack object, rather than creating one with the new() operator.
  6022. */
  6023. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  6024. /** Destructor.
  6025. The CriticalSection will be unlocked when the destructor is called.
  6026. Make sure this object is created and deleted by the same thread,
  6027. otherwise there are no guarantees what will happen!
  6028. */
  6029. inline ~ScopedUnlock() throw() { lock_.enter(); }
  6030. private:
  6031. const CriticalSection& lock_;
  6032. ScopedUnlock (const ScopedLock&);
  6033. const ScopedUnlock& operator= (const ScopedUnlock&);
  6034. };
  6035. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  6036. /********* End of inlined file: juce_ScopedLock.h *********/
  6037. /**
  6038. Macro to declare member variables and methods for a singleton class.
  6039. To use this, add the line juce_DeclareSingleton (MyClass, allowOnlyOneInstance)
  6040. to the class's definition.
  6041. If allowOnlyOneInstance == true, it won't allow the object to be created
  6042. more than once in the process's lifetime.
  6043. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  6044. implementation code.
  6045. Clients can then call the static MyClass::getInstance() to get a pointer to the
  6046. singleton, or MyClass::getInstanceWithoutCreating() which may return 0 if no instance
  6047. is currently extant
  6048. it's a very good idea to also add the call clearSingletonInstance() to the
  6049. destructor of the class, in case it is deleted by other means than deleteInstance()
  6050. e.g. @code
  6051. class MySingleton
  6052. {
  6053. public:
  6054. MySingleton()
  6055. {
  6056. }
  6057. ~MySingleton()
  6058. {
  6059. // this ensures that no dangling pointers are left when the
  6060. // singleton is deleted.
  6061. clearSingletonInstance();
  6062. }
  6063. juce_DeclareSingleton (MySingleton, false)
  6064. };
  6065. juce_ImplementSingleton (MySingleton)
  6066. // example of usage:
  6067. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  6068. ...
  6069. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  6070. @endcode
  6071. If you know that your object will only be created and deleted by a single thread, you
  6072. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  6073. of this one.
  6074. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  6075. */
  6076. #define juce_DeclareSingleton(classname, allowOnlyOneInstance) \
  6077. \
  6078. static classname* _singletonInstance; \
  6079. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  6080. \
  6081. static classname* getInstance() \
  6082. { \
  6083. if (_singletonInstance == 0) \
  6084. {\
  6085. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  6086. \
  6087. if (_singletonInstance == 0) \
  6088. { \
  6089. static bool alreadyInside = false; \
  6090. static bool createdOnceAlready = false; \
  6091. \
  6092. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  6093. jassert (! problem); \
  6094. if (! problem) \
  6095. { \
  6096. createdOnceAlready = true; \
  6097. alreadyInside = true; \
  6098. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  6099. alreadyInside = false; \
  6100. \
  6101. _singletonInstance = newObject; \
  6102. } \
  6103. } \
  6104. } \
  6105. \
  6106. return _singletonInstance; \
  6107. } \
  6108. \
  6109. static inline classname* getInstanceWithoutCreating() throw() \
  6110. { \
  6111. return _singletonInstance; \
  6112. } \
  6113. \
  6114. static void deleteInstance() \
  6115. { \
  6116. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  6117. if (_singletonInstance != 0) \
  6118. { \
  6119. classname* const old = _singletonInstance; \
  6120. _singletonInstance = 0; \
  6121. delete old; \
  6122. } \
  6123. } \
  6124. \
  6125. void clearSingletonInstance() throw() \
  6126. { \
  6127. if (_singletonInstance == this) \
  6128. _singletonInstance = 0; \
  6129. }
  6130. /** This is a counterpart to the juce_DeclareSingleton macro.
  6131. After adding the juce_DeclareSingleton to the class definition, this macro has
  6132. to be used in the cpp file.
  6133. */
  6134. #define juce_ImplementSingleton(classname) \
  6135. \
  6136. classname* classname::_singletonInstance = 0; \
  6137. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  6138. /**
  6139. Macro to declare member variables and methods for a singleton class.
  6140. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  6141. section to make access to it thread-safe. If you know that your object will
  6142. only ever be created or deleted by a single thread, then this is a
  6143. more efficient version to use.
  6144. See the documentation for juce_DeclareSingleton for more information about
  6145. how to use it, the only difference being that you have to use
  6146. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  6147. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  6148. */
  6149. #define juce_DeclareSingleton_SingleThreaded(classname, allowOnlyOneInstance) \
  6150. \
  6151. static classname* _singletonInstance; \
  6152. \
  6153. static classname* getInstance() \
  6154. { \
  6155. if (_singletonInstance == 0) \
  6156. { \
  6157. static bool alreadyInside = false; \
  6158. static bool createdOnceAlready = false; \
  6159. \
  6160. const bool problem = alreadyInside || ((allowOnlyOneInstance) && createdOnceAlready); \
  6161. jassert (! problem); \
  6162. if (! problem) \
  6163. { \
  6164. createdOnceAlready = true; \
  6165. alreadyInside = true; \
  6166. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  6167. alreadyInside = false; \
  6168. \
  6169. _singletonInstance = newObject; \
  6170. } \
  6171. } \
  6172. \
  6173. return _singletonInstance; \
  6174. } \
  6175. \
  6176. static inline classname* getInstanceWithoutCreating() throw() \
  6177. { \
  6178. return _singletonInstance; \
  6179. } \
  6180. \
  6181. static void deleteInstance() \
  6182. { \
  6183. if (_singletonInstance != 0) \
  6184. { \
  6185. classname* const old = _singletonInstance; \
  6186. _singletonInstance = 0; \
  6187. delete old; \
  6188. } \
  6189. } \
  6190. \
  6191. void clearSingletonInstance() throw() \
  6192. { \
  6193. if (_singletonInstance == this) \
  6194. _singletonInstance = 0; \
  6195. }
  6196. /**
  6197. Macro to declare member variables and methods for a singleton class.
  6198. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  6199. for recursion or repeated instantiation. It's intended for use as a lightweight
  6200. version of a singleton, where you're using it in very straightforward
  6201. circumstances and don't need the extra checking.
  6202. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  6203. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  6204. See the documentation for juce_DeclareSingleton for more information about
  6205. how to use it, the only difference being that you have to use
  6206. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  6207. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  6208. */
  6209. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  6210. \
  6211. static classname* _singletonInstance; \
  6212. \
  6213. static classname* getInstance() \
  6214. { \
  6215. if (_singletonInstance == 0) \
  6216. _singletonInstance = new classname(); \
  6217. \
  6218. return _singletonInstance; \
  6219. } \
  6220. \
  6221. static inline classname* getInstanceWithoutCreating() throw() \
  6222. { \
  6223. return _singletonInstance; \
  6224. } \
  6225. \
  6226. static void deleteInstance() \
  6227. { \
  6228. if (_singletonInstance != 0) \
  6229. { \
  6230. classname* const old = _singletonInstance; \
  6231. _singletonInstance = 0; \
  6232. delete old; \
  6233. } \
  6234. } \
  6235. \
  6236. void clearSingletonInstance() throw() \
  6237. { \
  6238. if (_singletonInstance == this) \
  6239. _singletonInstance = 0; \
  6240. }
  6241. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  6242. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  6243. to the class definition, this macro has to be used somewhere in the cpp file.
  6244. */
  6245. #define juce_ImplementSingleton_SingleThreaded(classname) \
  6246. \
  6247. classname* classname::_singletonInstance = 0;
  6248. #endif // __JUCE_SINGLETON_JUCEHEADER__
  6249. /********* End of inlined file: juce_Singleton.h *********/
  6250. #endif
  6251. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  6252. #endif
  6253. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  6254. /********* Start of inlined file: juce_SystemStats.h *********/
  6255. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  6256. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  6257. /**
  6258. Contains methods for finding out about the current hardware and OS configuration.
  6259. */
  6260. class JUCE_API SystemStats
  6261. {
  6262. public:
  6263. /** Returns the current version of JUCE,
  6264. (just in case you didn't already know at compile-time.)
  6265. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  6266. */
  6267. static const String getJUCEVersion() throw();
  6268. /** The set of possible results of the getOperatingSystemType() method.
  6269. */
  6270. enum OperatingSystemType
  6271. {
  6272. UnknownOS = 0,
  6273. MacOSX = 0x1000,
  6274. Linux = 0x2000,
  6275. Win95 = 0x4001,
  6276. Win98 = 0x4002,
  6277. WinNT351 = 0x4103,
  6278. WinNT40 = 0x4104,
  6279. Win2000 = 0x4105,
  6280. WinXP = 0x4106,
  6281. WinVista = 0x4107,
  6282. Windows7 = 0x4108,
  6283. Windows = 0x4000, /**< To test whether any version of Windows is running,
  6284. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  6285. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  6286. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  6287. };
  6288. /** Returns the type of operating system we're running on.
  6289. @returns one of the values from the OperatingSystemType enum.
  6290. @see getOperatingSystemName
  6291. */
  6292. static OperatingSystemType getOperatingSystemType() throw();
  6293. /** Returns the name of the type of operating system we're running on.
  6294. @returns a string describing the OS type.
  6295. @see getOperatingSystemType
  6296. */
  6297. static const String getOperatingSystemName() throw();
  6298. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  6299. */
  6300. static bool isOperatingSystem64Bit() throw();
  6301. // CPU and memory information..
  6302. /** Returns the approximate CPU speed.
  6303. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  6304. what year you're reading this...)
  6305. */
  6306. static int getCpuSpeedInMegaherz() throw();
  6307. /** Returns a string to indicate the CPU vendor.
  6308. Might not be known on some systems.
  6309. */
  6310. static const String getCpuVendor() throw();
  6311. /** Checks whether Intel MMX instructions are available. */
  6312. static bool hasMMX() throw();
  6313. /** Checks whether Intel SSE instructions are available. */
  6314. static bool hasSSE() throw();
  6315. /** Checks whether Intel SSE2 instructions are available. */
  6316. static bool hasSSE2() throw();
  6317. /** Checks whether AMD 3DNOW instructions are available. */
  6318. static bool has3DNow() throw();
  6319. /** Returns the number of CPUs.
  6320. */
  6321. static int getNumCpus() throw();
  6322. /** Returns a clock-cycle tick counter, if available.
  6323. If the machine can do it, this will return a tick-count
  6324. where each tick is one cpu clock cycle - used for profiling
  6325. code.
  6326. @returns the tick count, or zero if not available.
  6327. */
  6328. static int64 getClockCycleCounter() throw();
  6329. /** Finds out how much RAM is in the machine.
  6330. @returns the approximate number of megabytes of memory, or zero if
  6331. something goes wrong when finding out.
  6332. */
  6333. static int getMemorySizeInMegabytes() throw();
  6334. /** Returns the system page-size.
  6335. This is only used by programmers with beards.
  6336. */
  6337. static int getPageSize() throw();
  6338. /** Returns a list of MAC addresses found on this machine.
  6339. @param addresses an array into which the MAC addresses should be copied
  6340. @param maxNum the number of elements in this array
  6341. @param littleEndian the endianness of the numbers to return. Note that
  6342. the default values of this parameter are different on
  6343. Mac/PC to avoid breaking old software that was written
  6344. before this parameter was added (when the two systems
  6345. defaulted to using different endiannesses). In newer
  6346. software you probably want to specify an explicit value
  6347. for this.
  6348. @returns the number of MAC addresses that were found
  6349. */
  6350. static int getMACAddresses (int64* addresses, int maxNum,
  6351. #if JUCE_MAC
  6352. const bool littleEndian = true) throw();
  6353. #else
  6354. const bool littleEndian = false) throw();
  6355. #endif
  6356. // not-for-public-use platform-specific method gets called at startup to initialise things.
  6357. static void initialiseStats() throw();
  6358. };
  6359. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  6360. /********* End of inlined file: juce_SystemStats.h *********/
  6361. #endif
  6362. #ifndef __JUCE_TIME_JUCEHEADER__
  6363. #endif
  6364. #ifndef __JUCE_UUID_JUCEHEADER__
  6365. /********* Start of inlined file: juce_Uuid.h *********/
  6366. #ifndef __JUCE_UUID_JUCEHEADER__
  6367. #define __JUCE_UUID_JUCEHEADER__
  6368. /**
  6369. A universally unique 128-bit identifier.
  6370. This class generates very random unique numbers based on the system time
  6371. and MAC addresses if any are available. It's extremely unlikely that two identical
  6372. UUIDs would ever be created by chance.
  6373. The class includes methods for saving the ID as a string or as raw binary data.
  6374. */
  6375. class JUCE_API Uuid
  6376. {
  6377. public:
  6378. /** Creates a new unique ID. */
  6379. Uuid();
  6380. /** Destructor. */
  6381. ~Uuid() throw();
  6382. /** Creates a copy of another UUID. */
  6383. Uuid (const Uuid& other);
  6384. /** Copies another UUID. */
  6385. Uuid& operator= (const Uuid& other);
  6386. /** Returns true if the ID is zero. */
  6387. bool isNull() const throw();
  6388. /** Compares two UUIDs. */
  6389. bool operator== (const Uuid& other) const;
  6390. /** Compares two UUIDs. */
  6391. bool operator!= (const Uuid& other) const;
  6392. /** Returns a stringified version of this UUID.
  6393. A Uuid object can later be reconstructed from this string using operator= or
  6394. the constructor that takes a string parameter.
  6395. @returns a 32 character hex string.
  6396. */
  6397. const String toString() const;
  6398. /** Creates an ID from an encoded string version.
  6399. @see toString
  6400. */
  6401. Uuid (const String& uuidString);
  6402. /** Copies from a stringified UUID.
  6403. The string passed in should be one that was created with the toString() method.
  6404. */
  6405. Uuid& operator= (const String& uuidString);
  6406. /** Returns a pointer to the internal binary representation of the ID.
  6407. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  6408. the constructor or operator= method that takes an array of uint8s.
  6409. */
  6410. const uint8* getRawData() const throw() { return value.asBytes; }
  6411. /** Creates a UUID from a 16-byte array.
  6412. @see getRawData
  6413. */
  6414. Uuid (const uint8* const rawData);
  6415. /** Sets this UUID from 16-bytes of raw data. */
  6416. Uuid& operator= (const uint8* const rawData);
  6417. juce_UseDebuggingNewOperator
  6418. private:
  6419. union
  6420. {
  6421. uint8 asBytes [16];
  6422. int asInt[4];
  6423. int64 asInt64[2];
  6424. } value;
  6425. };
  6426. #endif // __JUCE_UUID_JUCEHEADER__
  6427. /********* End of inlined file: juce_Uuid.h *********/
  6428. #endif
  6429. #ifndef __JUCE_ARRAY_JUCEHEADER__
  6430. #endif
  6431. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  6432. #endif
  6433. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  6434. #endif
  6435. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  6436. #endif
  6437. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  6438. #endif
  6439. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  6440. #endif
  6441. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6442. /********* Start of inlined file: juce_PropertySet.h *********/
  6443. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  6444. #define __JUCE_PROPERTYSET_JUCEHEADER__
  6445. /********* Start of inlined file: juce_StringPairArray.h *********/
  6446. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6447. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6448. /**
  6449. A container for holding a set of strings which are keyed by another string.
  6450. @see StringArray
  6451. */
  6452. class JUCE_API StringPairArray
  6453. {
  6454. public:
  6455. /** Creates an empty array */
  6456. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  6457. /** Creates a copy of another array */
  6458. StringPairArray (const StringPairArray& other) throw();
  6459. /** Destructor. */
  6460. ~StringPairArray() throw();
  6461. /** Copies the contents of another string array into this one */
  6462. const StringPairArray& operator= (const StringPairArray& other) throw();
  6463. /** Compares two arrays.
  6464. Comparisons are case-sensitive.
  6465. @returns true only if the other array contains exactly the same strings with the same keys
  6466. */
  6467. bool operator== (const StringPairArray& other) const throw();
  6468. /** Compares two arrays.
  6469. Comparisons are case-sensitive.
  6470. @returns false if the other array contains exactly the same strings with the same keys
  6471. */
  6472. bool operator!= (const StringPairArray& other) const throw();
  6473. /** Finds the value corresponding to a key string.
  6474. If no such key is found, this will just return an empty string. To check whether
  6475. a given key actually exists (because it might actually be paired with an empty string), use
  6476. the getAllKeys() method to obtain a list.
  6477. Obviously the reference returned shouldn't be stored for later use, as the
  6478. string it refers to may disappear when the array changes.
  6479. @see getValue
  6480. */
  6481. const String& operator[] (const String& key) const throw();
  6482. /** Finds the value corresponding to a key string.
  6483. If no such key is found, this will just return the value provided as a default.
  6484. @see operator[]
  6485. */
  6486. const String getValue (const String& key, const String& defaultReturnValue) const;
  6487. /** Returns a list of all keys in the array. */
  6488. const StringArray& getAllKeys() const throw() { return keys; }
  6489. /** Returns a list of all values in the array. */
  6490. const StringArray& getAllValues() const throw() { return values; }
  6491. /** Returns the number of strings in the array */
  6492. inline int size() const throw() { return keys.size(); };
  6493. /** Adds or amends a key/value pair.
  6494. If a value already exists with this key, its value will be overwritten,
  6495. otherwise the key/value pair will be added to the array.
  6496. */
  6497. void set (const String& key,
  6498. const String& value) throw();
  6499. /** Adds the items from another array to this one.
  6500. This is equivalent to using set() to add each of the pairs from the other array.
  6501. */
  6502. void addArray (const StringPairArray& other);
  6503. /** Removes all elements from the array. */
  6504. void clear() throw();
  6505. /** Removes a string from the array based on its key.
  6506. If the key isn't found, nothing will happen.
  6507. */
  6508. void remove (const String& key) throw();
  6509. /** Removes a string from the array based on its index.
  6510. If the index is out-of-range, no action will be taken.
  6511. */
  6512. void remove (const int index) throw();
  6513. /** Indicates whether to use a case-insensitive search when looking up a key string.
  6514. */
  6515. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  6516. /** Returns a descriptive string containing the items.
  6517. This is handy for dumping the contents of an array.
  6518. */
  6519. const String getDescription() const;
  6520. /** Reduces the amount of storage being used by the array.
  6521. Arrays typically allocate slightly more storage than they need, and after
  6522. removing elements, they may have quite a lot of unused space allocated.
  6523. This method will reduce the amount of allocated storage to a minimum.
  6524. */
  6525. void minimiseStorageOverheads() throw();
  6526. juce_UseDebuggingNewOperator
  6527. private:
  6528. StringArray keys, values;
  6529. bool ignoreCase;
  6530. };
  6531. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  6532. /********* End of inlined file: juce_StringPairArray.h *********/
  6533. /********* Start of inlined file: juce_XmlElement.h *********/
  6534. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  6535. #define __JUCE_XMLELEMENT_JUCEHEADER__
  6536. /********* Start of inlined file: juce_OutputStream.h *********/
  6537. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6538. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6539. /********* Start of inlined file: juce_InputStream.h *********/
  6540. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  6541. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  6542. /** The base class for streams that read data.
  6543. Input and output streams are used throughout the library - subclasses can override
  6544. some or all of the virtual functions to implement their behaviour.
  6545. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  6546. */
  6547. class JUCE_API InputStream
  6548. {
  6549. public:
  6550. /** Destructor. */
  6551. virtual ~InputStream() {}
  6552. /** Returns the total number of bytes available for reading in this stream.
  6553. Note that this is the number of bytes available from the start of the
  6554. stream, not from the current position.
  6555. If the size of the stream isn't actually known, this may return -1.
  6556. */
  6557. virtual int64 getTotalLength() = 0;
  6558. /** Returns true if the stream has no more data to read. */
  6559. virtual bool isExhausted() = 0;
  6560. /** Reads a set of bytes from the stream into a memory buffer.
  6561. This is the only read method that subclasses actually need to implement, as the
  6562. InputStream base class implements the other read methods in terms of this one (although
  6563. it's often more efficient for subclasses to implement them directly).
  6564. @param destBuffer the destination buffer for the data
  6565. @param maxBytesToRead the maximum number of bytes to read - make sure the
  6566. memory block passed in is big enough to contain this
  6567. many bytes.
  6568. @returns the actual number of bytes that were read, which may be less than
  6569. maxBytesToRead if the stream is exhausted before it gets that far
  6570. */
  6571. virtual int read (void* destBuffer,
  6572. int maxBytesToRead) = 0;
  6573. /** Reads a byte from the stream.
  6574. If the stream is exhausted, this will return zero.
  6575. @see OutputStream::writeByte
  6576. */
  6577. virtual char readByte();
  6578. /** Reads a boolean from the stream.
  6579. The bool is encoded as a single byte - 1 for true, 0 for false.
  6580. If the stream is exhausted, this will return false.
  6581. @see OutputStream::writeBool
  6582. */
  6583. virtual bool readBool();
  6584. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6585. If the next two bytes read are byte1 and byte2, this returns
  6586. (byte1 | (byte2 << 8)).
  6587. If the stream is exhausted partway through reading the bytes, this will return zero.
  6588. @see OutputStream::writeShort, readShortBigEndian
  6589. */
  6590. virtual short readShort();
  6591. /** Reads two bytes from the stream as a little-endian 16-bit value.
  6592. If the next two bytes read are byte1 and byte2, this returns
  6593. (byte2 | (byte1 << 8)).
  6594. If the stream is exhausted partway through reading the bytes, this will return zero.
  6595. @see OutputStream::writeShortBigEndian, readShort
  6596. */
  6597. virtual short readShortBigEndian();
  6598. /** Reads four bytes from the stream as a little-endian 32-bit value.
  6599. If the next four bytes are byte1 to byte4, this returns
  6600. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  6601. If the stream is exhausted partway through reading the bytes, this will return zero.
  6602. @see OutputStream::writeInt, readIntBigEndian
  6603. */
  6604. virtual int readInt();
  6605. /** Reads four bytes from the stream as a big-endian 32-bit value.
  6606. If the next four bytes are byte1 to byte4, this returns
  6607. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  6608. If the stream is exhausted partway through reading the bytes, this will return zero.
  6609. @see OutputStream::writeIntBigEndian, readInt
  6610. */
  6611. virtual int readIntBigEndian();
  6612. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  6613. If the next eight bytes are byte1 to byte8, this returns
  6614. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  6615. If the stream is exhausted partway through reading the bytes, this will return zero.
  6616. @see OutputStream::writeInt64, readInt64BigEndian
  6617. */
  6618. virtual int64 readInt64();
  6619. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  6620. If the next eight bytes are byte1 to byte8, this returns
  6621. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  6622. If the stream is exhausted partway through reading the bytes, this will return zero.
  6623. @see OutputStream::writeInt64BigEndian, readInt64
  6624. */
  6625. virtual int64 readInt64BigEndian();
  6626. /** Reads four bytes as a 32-bit floating point value.
  6627. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  6628. If the stream is exhausted partway through reading the bytes, this will return zero.
  6629. @see OutputStream::writeFloat, readDouble
  6630. */
  6631. virtual float readFloat();
  6632. /** Reads four bytes as a 32-bit floating point value.
  6633. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  6634. If the stream is exhausted partway through reading the bytes, this will return zero.
  6635. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  6636. */
  6637. virtual float readFloatBigEndian();
  6638. /** Reads eight bytes as a 64-bit floating point value.
  6639. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  6640. If the stream is exhausted partway through reading the bytes, this will return zero.
  6641. @see OutputStream::writeDouble, readFloat
  6642. */
  6643. virtual double readDouble();
  6644. /** Reads eight bytes as a 64-bit floating point value.
  6645. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  6646. If the stream is exhausted partway through reading the bytes, this will return zero.
  6647. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  6648. */
  6649. virtual double readDoubleBigEndian();
  6650. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  6651. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  6652. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6653. @see OutputStream::writeCompressedInt()
  6654. */
  6655. virtual int readCompressedInt();
  6656. /** Reads a string from the stream, up to the next linefeed or carriage return.
  6657. The stream is treated as 8-bit characters encoded with the system's default encoding,
  6658. and this will read up to the next "\n" or "\r\n" or end-of-stream.
  6659. After this call, the stream's position will be left pointing to the character
  6660. following the line-feed, but the linefeeds aren't included in the string that
  6661. is returned.
  6662. */
  6663. virtual const String readNextLine();
  6664. /** Reads a zero-terminated string from the stream.
  6665. This will read characters from the stream until it hits a zero character or
  6666. end-of-stream.
  6667. @see OutputStream::writeString, readEntireStreamAsString
  6668. */
  6669. virtual const String readString();
  6670. /** Tries to read the whole stream and turn it into a string.
  6671. This will read from the stream's current position until the end-of-stream, and
  6672. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  6673. */
  6674. virtual const String readEntireStreamAsString();
  6675. /** Reads from the stream and appends the data to a MemoryBlock.
  6676. @param destBlock the block to append the data onto
  6677. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  6678. of bytes that will be read - if it's negative, data
  6679. will be read until the stream is exhausted.
  6680. @returns the number of bytes that were added to the memory block
  6681. */
  6682. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  6683. int maxNumBytesToRead = -1);
  6684. /** Returns the offset of the next byte that will be read from the stream.
  6685. @see setPosition
  6686. */
  6687. virtual int64 getPosition() = 0;
  6688. /** Tries to move the current read position of the stream.
  6689. The position is an absolute number of bytes from the stream's start.
  6690. Some streams might not be able to do this, in which case they should do
  6691. nothing and return false. Others might be able to manage it by resetting
  6692. themselves and skipping to the correct position, although this is
  6693. obviously a bit slow.
  6694. @returns true if the stream manages to reposition itself correctly
  6695. @see getPosition
  6696. */
  6697. virtual bool setPosition (int64 newPosition) = 0;
  6698. /** Reads and discards a number of bytes from the stream.
  6699. Some input streams might implement this efficiently, but the base
  6700. class will just keep reading data until the requisite number of bytes
  6701. have been done.
  6702. */
  6703. virtual void skipNextBytes (int64 numBytesToSkip);
  6704. juce_UseDebuggingNewOperator
  6705. protected:
  6706. InputStream() throw() {}
  6707. };
  6708. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  6709. /********* End of inlined file: juce_InputStream.h *********/
  6710. /**
  6711. The base class for streams that write data to some kind of destination.
  6712. Input and output streams are used throughout the library - subclasses can override
  6713. some or all of the virtual functions to implement their behaviour.
  6714. @see InputStream, MemoryOutputStream, FileOutputStream
  6715. */
  6716. class JUCE_API OutputStream
  6717. {
  6718. public:
  6719. /** Destructor.
  6720. Some subclasses might want to do things like call flush() during their
  6721. destructors.
  6722. */
  6723. virtual ~OutputStream();
  6724. /** If the stream is using a buffer, this will ensure it gets written
  6725. out to the destination. */
  6726. virtual void flush() = 0;
  6727. /** Tries to move the stream's output position.
  6728. Not all streams will be able to seek to a new position - this will return
  6729. false if it fails to work.
  6730. @see getPosition
  6731. */
  6732. virtual bool setPosition (int64 newPosition) = 0;
  6733. /** Returns the stream's current position.
  6734. @see setPosition
  6735. */
  6736. virtual int64 getPosition() = 0;
  6737. /** Writes a block of data to the stream.
  6738. When creating a subclass of OutputStream, this is the only write method
  6739. that needs to be overloaded - the base class has methods for writing other
  6740. types of data which use this to do the work.
  6741. @returns false if the write operation fails for some reason
  6742. */
  6743. virtual bool write (const void* dataToWrite,
  6744. int howManyBytes) = 0;
  6745. /** Writes a single byte to the stream.
  6746. @see InputStream::readByte
  6747. */
  6748. virtual void writeByte (char byte);
  6749. /** Writes a boolean to the stream.
  6750. This is encoded as a byte - either 1 or 0.
  6751. @see InputStream::readBool
  6752. */
  6753. virtual void writeBool (bool boolValue);
  6754. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  6755. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  6756. @see InputStream::readShort
  6757. */
  6758. virtual void writeShort (short value);
  6759. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  6760. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  6761. @see InputStream::readShortBigEndian
  6762. */
  6763. virtual void writeShortBigEndian (short value);
  6764. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  6765. @see InputStream::readInt
  6766. */
  6767. virtual void writeInt (int value);
  6768. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  6769. @see InputStream::readIntBigEndian
  6770. */
  6771. virtual void writeIntBigEndian (int value);
  6772. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  6773. @see InputStream::readInt64
  6774. */
  6775. virtual void writeInt64 (int64 value);
  6776. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  6777. @see InputStream::readInt64BigEndian
  6778. */
  6779. virtual void writeInt64BigEndian (int64 value);
  6780. /** Writes a 32-bit floating point value to the stream.
  6781. The binary 32-bit encoding of the float is written as a little-endian int.
  6782. @see InputStream::readFloat
  6783. */
  6784. virtual void writeFloat (float value);
  6785. /** Writes a 32-bit floating point value to the stream.
  6786. The binary 32-bit encoding of the float is written as a big-endian int.
  6787. @see InputStream::readFloatBigEndian
  6788. */
  6789. virtual void writeFloatBigEndian (float value);
  6790. /** Writes a 64-bit floating point value to the stream.
  6791. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  6792. @see InputStream::readDouble
  6793. */
  6794. virtual void writeDouble (double value);
  6795. /** Writes a 64-bit floating point value to the stream.
  6796. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  6797. @see InputStream::readDoubleBigEndian
  6798. */
  6799. virtual void writeDoubleBigEndian (double value);
  6800. /** Writes a condensed encoding of a 32-bit integer.
  6801. If you're storing a lot of integers which are unlikely to have very large values,
  6802. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  6803. under 0xffff only 3 bytes, etc.
  6804. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  6805. @see InputStream::readCompressedInt
  6806. */
  6807. virtual void writeCompressedInt (int value);
  6808. /** Stores a string in the stream.
  6809. This isn't the method to use if you're trying to append text to the end of a
  6810. text-file! It's intended for storing a string for later retrieval
  6811. by InputStream::readString.
  6812. For appending text to a file, instead use writeText, printf, or operator<<
  6813. @see InputStream::readString, writeText, printf, operator<<
  6814. */
  6815. virtual void writeString (const String& text);
  6816. /** Writes a string of text to the stream.
  6817. It can either write it as 8-bit system-encoded characters, or as unicode, and
  6818. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  6819. should only be done at the start of a file).
  6820. The method also replaces '\\n' characters in the text with '\\r\\n'.
  6821. */
  6822. virtual void writeText (const String& text,
  6823. const bool asUnicode,
  6824. const bool writeUnicodeHeaderBytes);
  6825. /** Writes a string of text to the stream.
  6826. @see writeText
  6827. */
  6828. virtual void printf (const char* format, ...);
  6829. /** Reads data from an input stream and writes it to this stream.
  6830. @param source the stream to read from
  6831. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  6832. less than zero, it will keep reading until the input
  6833. is exhausted)
  6834. */
  6835. virtual int writeFromInputStream (InputStream& source,
  6836. int maxNumBytesToWrite);
  6837. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6838. virtual OutputStream& operator<< (const int number);
  6839. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  6840. virtual OutputStream& operator<< (const double number);
  6841. /** Writes a character to the stream. */
  6842. virtual OutputStream& operator<< (const char character);
  6843. /** Writes a null-terminated string to the stream. */
  6844. virtual OutputStream& operator<< (const char* const text);
  6845. /** Writes a null-terminated unicode text string to the stream, converting it
  6846. to 8-bit characters in the default system encoding. */
  6847. virtual OutputStream& operator<< (const juce_wchar* const text);
  6848. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  6849. virtual OutputStream& operator<< (const String& text);
  6850. juce_UseDebuggingNewOperator
  6851. protected:
  6852. OutputStream() throw();
  6853. };
  6854. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  6855. /********* End of inlined file: juce_OutputStream.h *********/
  6856. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6857. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6858. will be the name of a pointer to each child element.
  6859. E.g. @code
  6860. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6861. forEachXmlChildElement (*myParentXml, child)
  6862. {
  6863. if (child->hasTagName ("FOO"))
  6864. doSomethingWithXmlElement (child);
  6865. }
  6866. @endcode
  6867. @see forEachXmlChildElementWithTagName
  6868. */
  6869. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6870. \
  6871. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6872. childElementVariableName != 0; \
  6873. childElementVariableName = childElementVariableName->getNextElement())
  6874. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6875. which have a specified tag.
  6876. This does the same job as the forEachXmlChildElement macro, but only for those
  6877. elements that have a particular tag name.
  6878. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6879. will be the name of a pointer to each child element. The requiredTagName is the
  6880. tag name to match.
  6881. E.g. @code
  6882. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6883. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6884. {
  6885. // the child object is now guaranteed to be a <MYTAG> element..
  6886. doSomethingWithMYTAGElement (child);
  6887. }
  6888. @endcode
  6889. @see forEachXmlChildElement
  6890. */
  6891. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6892. \
  6893. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6894. childElementVariableName != 0; \
  6895. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6896. /** Used to build a tree of elements representing an XML document.
  6897. An XML document can be parsed into a tree of XmlElements, each of which
  6898. represents an XML tag structure, and which may itself contain other
  6899. nested elements.
  6900. An XmlElement can also be converted back into a text document, and has
  6901. lots of useful methods for manipulating its attributes and sub-elements,
  6902. so XmlElements can actually be used as a handy general-purpose data
  6903. structure.
  6904. Here's an example of parsing some elements: @code
  6905. // check we're looking at the right kind of document..
  6906. if (myElement->hasTagName ("ANIMALS"))
  6907. {
  6908. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6909. forEachXmlChildElement (*myElement, e)
  6910. {
  6911. if (e->hasTagName ("GIRAFFE"))
  6912. {
  6913. // found a giraffe, so use some of its attributes..
  6914. String giraffeName = e->getStringAttribute ("name");
  6915. int giraffeAge = e->getIntAttribute ("age");
  6916. bool isFriendly = e->getBoolAttribute ("friendly");
  6917. }
  6918. }
  6919. }
  6920. @endcode
  6921. And here's an example of how to create an XML document from scratch: @code
  6922. // create an outer node called "ANIMALS"
  6923. XmlElement animalsList ("ANIMALS");
  6924. for (int i = 0; i < numAnimals; ++i)
  6925. {
  6926. // create an inner element..
  6927. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6928. giraffe->setAttribute ("name", "nigel");
  6929. giraffe->setAttribute ("age", 10);
  6930. giraffe->setAttribute ("friendly", true);
  6931. // ..and add our new element to the parent node
  6932. animalsList.addChildElement (giraffe);
  6933. }
  6934. // now we can turn the whole thing into a text document..
  6935. String myXmlDoc = animalsList.createDocument (String::empty);
  6936. @endcode
  6937. @see XmlDocument
  6938. */
  6939. class JUCE_API XmlElement
  6940. {
  6941. public:
  6942. /** Creates an XmlElement with this tag name. */
  6943. XmlElement (const String& tagName) throw();
  6944. /** Creates a (deep) copy of another element. */
  6945. XmlElement (const XmlElement& other) throw();
  6946. /** Creates a (deep) copy of another element. */
  6947. const XmlElement& operator= (const XmlElement& other) throw();
  6948. /** Deleting an XmlElement will also delete all its child elements. */
  6949. ~XmlElement() throw();
  6950. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6951. The elements are only considered equivalent if they contain the same attiributes
  6952. with the same values, and have the same sub-nodes.
  6953. @param other the other element to compare to
  6954. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6955. same attributes in a different order will be
  6956. considered the same; if false, the attributes must
  6957. be in the same order as well
  6958. */
  6959. bool isEquivalentTo (const XmlElement* const other,
  6960. const bool ignoreOrderOfAttributes) const throw();
  6961. /** Returns an XML text document that represents this element.
  6962. The string returned can be parsed to recreate the same XmlElement that
  6963. was used to create it.
  6964. @param dtdToUse the DTD to add to the document
  6965. @param allOnOneLine if true, this means that the document will not contain any
  6966. linefeeds, so it'll be smaller but not very easy to read.
  6967. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6968. document
  6969. @param encodingType the character encoding format string to put into the xml
  6970. header
  6971. @param lineWrapLength the line length that will be used before items get placed on
  6972. a new line. This isn't an absolute maximum length, it just
  6973. determines how lists of attributes get broken up
  6974. @see writeToFile
  6975. */
  6976. const String createDocument (const String& dtdToUse,
  6977. const bool allOnOneLine = false,
  6978. const bool includeXmlHeader = true,
  6979. const tchar* const encodingType = JUCE_T("UTF-8"),
  6980. const int lineWrapLength = 60) const throw();
  6981. /** Writes the element to a file as an XML document.
  6982. To improve safety in case something goes wrong while writing the file, this
  6983. will actually write the document to a new temporary file in the same
  6984. directory as the destination file, and if this succeeds, it will rename this
  6985. new file as the destination file (overwriting any existing file that was there).
  6986. @param destinationFile the file to write to. If this already exists, it will be
  6987. overwritten.
  6988. @param dtdToUse the DTD to add to the document
  6989. @param encodingType the character encoding format string to put into the xml
  6990. header
  6991. @param lineWrapLength the line length that will be used before items get placed on
  6992. a new line. This isn't an absolute maximum length, it just
  6993. determines how lists of attributes get broken up
  6994. @returns true if the file is written successfully; false if something goes wrong
  6995. in the process
  6996. @see createDocument
  6997. */
  6998. bool writeToFile (const File& destinationFile,
  6999. const String& dtdToUse,
  7000. const tchar* const encodingType = JUCE_T("UTF-8"),
  7001. const int lineWrapLength = 60) const throw();
  7002. /** Returns this element's tag type name.
  7003. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7004. "MOOSE".
  7005. @see hasTagName
  7006. */
  7007. inline const String& getTagName() const throw() { return tagName; }
  7008. /** Tests whether this element has a particular tag name.
  7009. @param possibleTagName the tag name you're comparing it with
  7010. @see getTagName
  7011. */
  7012. bool hasTagName (const tchar* const possibleTagName) const throw();
  7013. /** Returns the number of XML attributes this element contains.
  7014. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7015. return 2.
  7016. */
  7017. int getNumAttributes() const throw();
  7018. /** Returns the name of one of the elements attributes.
  7019. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7020. getAttributeName(1) would return "antlers".
  7021. @see getAttributeValue, getStringAttribute
  7022. */
  7023. const String& getAttributeName (const int attributeIndex) const throw();
  7024. /** Returns the value of one of the elements attributes.
  7025. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7026. getAttributeName(1) would return "2".
  7027. @see getAttributeName, getStringAttribute
  7028. */
  7029. const String& getAttributeValue (const int attributeIndex) const throw();
  7030. // Attribute-handling methods..
  7031. /** Checks whether the element contains an attribute with a certain name. */
  7032. bool hasAttribute (const tchar* const attributeName) const throw();
  7033. /** Returns the value of a named attribute.
  7034. @param attributeName the name of the attribute to look up
  7035. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7036. with this name
  7037. */
  7038. const String getStringAttribute (const tchar* const attributeName,
  7039. const tchar* const defaultReturnValue = 0) const throw();
  7040. /** Compares the value of a named attribute with a value passed-in.
  7041. @param attributeName the name of the attribute to look up
  7042. @param stringToCompareAgainst the value to compare it with
  7043. @param ignoreCase whether the comparison should be case-insensitive
  7044. @returns true if the value of the attribute is the same as the string passed-in;
  7045. false if it's different (or if no such attribute exists)
  7046. */
  7047. bool compareAttribute (const tchar* const attributeName,
  7048. const tchar* const stringToCompareAgainst,
  7049. const bool ignoreCase = false) const throw();
  7050. /** Returns the value of a named attribute as an integer.
  7051. This will try to find the attribute and convert it to an integer (using
  7052. the String::getIntValue() method).
  7053. @param attributeName the name of the attribute to look up
  7054. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7055. with this name
  7056. @see setAttribute (const tchar* const, int)
  7057. */
  7058. int getIntAttribute (const tchar* const attributeName,
  7059. const int defaultReturnValue = 0) const throw();
  7060. /** Returns the value of a named attribute as floating-point.
  7061. This will try to find the attribute and convert it to an integer (using
  7062. the String::getDoubleValue() method).
  7063. @param attributeName the name of the attribute to look up
  7064. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7065. with this name
  7066. @see setAttribute (const tchar* const, double)
  7067. */
  7068. double getDoubleAttribute (const tchar* const attributeName,
  7069. const double defaultReturnValue = 0.0) const throw();
  7070. /** Returns the value of a named attribute as a boolean.
  7071. This will try to find the attribute and interpret it as a boolean. To do this,
  7072. it'll return true if the value is "1", "true", "y", etc, or false for other
  7073. values.
  7074. @param attributeName the name of the attribute to look up
  7075. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7076. with this name
  7077. */
  7078. bool getBoolAttribute (const tchar* const attributeName,
  7079. const bool defaultReturnValue = false) const throw();
  7080. /** Adds a named attribute to the element.
  7081. If the element already contains an attribute with this name, it's value will
  7082. be updated to the new value. If there's no such attribute yet, a new one will
  7083. be added.
  7084. Note that there are other setAttribute() methods that take integers,
  7085. doubles, etc. to make it easy to store numbers.
  7086. @param attributeName the name of the attribute to set
  7087. @param newValue the value to set it to
  7088. @see removeAttribute
  7089. */
  7090. void setAttribute (const tchar* const attributeName,
  7091. const String& newValue) throw();
  7092. /** Adds a named attribute to the element.
  7093. If the element already contains an attribute with this name, it's value will
  7094. be updated to the new value. If there's no such attribute yet, a new one will
  7095. be added.
  7096. Note that there are other setAttribute() methods that take integers,
  7097. doubles, etc. to make it easy to store numbers.
  7098. @param attributeName the name of the attribute to set
  7099. @param newValue the value to set it to
  7100. */
  7101. void setAttribute (const tchar* const attributeName,
  7102. const tchar* const newValue) throw();
  7103. /** Adds a named attribute to the element, setting it to an integer value.
  7104. If the element already contains an attribute with this name, it's value will
  7105. be updated to the new value. If there's no such attribute yet, a new one will
  7106. be added.
  7107. Note that there are other setAttribute() methods that take integers,
  7108. doubles, etc. to make it easy to store numbers.
  7109. @param attributeName the name of the attribute to set
  7110. @param newValue the value to set it to
  7111. */
  7112. void setAttribute (const tchar* const attributeName,
  7113. const int newValue) throw();
  7114. /** Adds a named attribute to the element, setting it to a floating-point value.
  7115. If the element already contains an attribute with this name, it's value will
  7116. be updated to the new value. If there's no such attribute yet, a new one will
  7117. be added.
  7118. Note that there are other setAttribute() methods that take integers,
  7119. doubles, etc. to make it easy to store numbers.
  7120. @param attributeName the name of the attribute to set
  7121. @param newValue the value to set it to
  7122. */
  7123. void setAttribute (const tchar* const attributeName,
  7124. const double newValue) throw();
  7125. /** Removes a named attribute from the element.
  7126. @param attributeName the name of the attribute to remove
  7127. @see removeAllAttributes
  7128. */
  7129. void removeAttribute (const tchar* const attributeName) throw();
  7130. /** Removes all attributes from this element.
  7131. */
  7132. void removeAllAttributes() throw();
  7133. // Child element methods..
  7134. /** Returns the first of this element's sub-elements.
  7135. see getNextElement() for an example of how to iterate the sub-elements.
  7136. @see forEachXmlChildElement
  7137. */
  7138. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7139. /** Returns the next of this element's siblings.
  7140. This can be used for iterating an element's sub-elements, e.g.
  7141. @code
  7142. XmlElement* child = myXmlDocument->getFirstChildElement();
  7143. while (child != 0)
  7144. {
  7145. ...do stuff with this child..
  7146. child = child->getNextElement();
  7147. }
  7148. @endcode
  7149. Note that when iterating the child elements, some of them might be
  7150. text elements as well as XML tags - use isTextElement() to work this
  7151. out.
  7152. Also, it's much easier and neater to use this method indirectly via the
  7153. forEachXmlChildElement macro.
  7154. @returns the sibling element that follows this one, or zero if this is the last
  7155. element in its parent
  7156. @see getNextElement, isTextElement, forEachXmlChildElement
  7157. */
  7158. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7159. /** Returns the next of this element's siblings which has the specified tag
  7160. name.
  7161. This is like getNextElement(), but will scan through the list until it
  7162. finds an element with the given tag name.
  7163. @see getNextElement, forEachXmlChildElementWithTagName
  7164. */
  7165. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  7166. /** Returns the number of sub-elements in this element.
  7167. @see getChildElement
  7168. */
  7169. int getNumChildElements() const throw();
  7170. /** Returns the sub-element at a certain index.
  7171. It's not very efficient to iterate the sub-elements by index - see
  7172. getNextElement() for an example of how best to iterate.
  7173. @returns the n'th child of this element, or 0 if the index is out-of-range
  7174. @see getNextElement, isTextElement, getChildByName
  7175. */
  7176. XmlElement* getChildElement (const int index) const throw();
  7177. /** Returns the first sub-element with a given tag-name.
  7178. @param tagNameToLookFor the tag name of the element you want to find
  7179. @returns the first element with this tag name, or 0 if none is found
  7180. @see getNextElement, isTextElement, getChildElement
  7181. */
  7182. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  7183. /** Appends an element to this element's list of children.
  7184. Child elements are deleted automatically when their parent is deleted, so
  7185. make sure the object that you pass in will not be deleted by anything else,
  7186. and make sure it's not already the child of another element.
  7187. @see getFirstChildElement, getNextElement, getNumChildElements,
  7188. getChildElement, removeChildElement
  7189. */
  7190. void addChildElement (XmlElement* const newChildElement) throw();
  7191. /** Inserts an element into this element's list of children.
  7192. Child elements are deleted automatically when their parent is deleted, so
  7193. make sure the object that you pass in will not be deleted by anything else,
  7194. and make sure it's not already the child of another element.
  7195. @param newChildNode the element to add
  7196. @param indexToInsertAt the index at which to insert the new element - if this is
  7197. below zero, it will be added to the end of the list
  7198. @see addChildElement, insertChildElement
  7199. */
  7200. void insertChildElement (XmlElement* const newChildNode,
  7201. int indexToInsertAt) throw();
  7202. /** Replaces one of this element's children with another node.
  7203. If the current element passed-in isn't actually a child of this element,
  7204. this will return false and the new one won't be added. Otherwise, the
  7205. existing element will be deleted, replaced with the new one, and it
  7206. will return true.
  7207. */
  7208. bool replaceChildElement (XmlElement* const currentChildElement,
  7209. XmlElement* const newChildNode) throw();
  7210. /** Removes a child element.
  7211. @param childToRemove the child to look for and remove
  7212. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7213. just remove it
  7214. */
  7215. void removeChildElement (XmlElement* const childToRemove,
  7216. const bool shouldDeleteTheChild) throw();
  7217. /** Deletes all the child elements in the element.
  7218. @see removeChildElement, deleteAllChildElementsWithTagName
  7219. */
  7220. void deleteAllChildElements() throw();
  7221. /** Deletes all the child elements with a given tag name.
  7222. @see removeChildElement
  7223. */
  7224. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  7225. /** Returns true if the given element is a child of this one. */
  7226. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7227. /** Recursively searches all sub-elements to find one that contains the specified
  7228. child element.
  7229. */
  7230. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  7231. /** Sorts the child elements using a comparator.
  7232. This will use a comparator object to sort the elements into order. The object
  7233. passed must have a method of the form:
  7234. @code
  7235. int compareElements (const XmlElement* first, const XmlElement* second);
  7236. @endcode
  7237. ..and this method must return:
  7238. - a value of < 0 if the first comes before the second
  7239. - a value of 0 if the two objects are equivalent
  7240. - a value of > 0 if the second comes before the first
  7241. To improve performance, the compareElements() method can be declared as static or const.
  7242. @param comparator the comparator to use for comparing elements.
  7243. @param retainOrderOfEquivalentItems if this is true, then items
  7244. which the comparator says are equivalent will be
  7245. kept in the order in which they currently appear
  7246. in the array. This is slower to perform, but may
  7247. be important in some cases. If it's false, a faster
  7248. algorithm is used, but equivalent elements may be
  7249. rearranged.
  7250. */
  7251. template <class ElementComparator>
  7252. void sortChildElements (ElementComparator& comparator,
  7253. const bool retainOrderOfEquivalentItems = false) throw()
  7254. {
  7255. const int num = getNumChildElements();
  7256. if (num > 1)
  7257. {
  7258. XmlElement** const elems = getChildElementsAsArray (num);
  7259. sortArray (comparator, elems, 0, num - 1, retainOrderOfEquivalentItems);
  7260. reorderChildElements (elems, num);
  7261. delete[] elems;
  7262. }
  7263. }
  7264. /** Returns true if this element is a section of text.
  7265. Elements can either be an XML tag element or a secton of text, so this
  7266. is used to find out what kind of element this one is.
  7267. @see getAllText, addTextElement, deleteAllTextElements
  7268. */
  7269. bool isTextElement() const throw();
  7270. /** Returns the text for a text element.
  7271. Note that if you have an element like this:
  7272. @code<xyz>hello</xyz>@endcode
  7273. then calling getText on the "xyz" element won't return "hello", because that is
  7274. actually stored in a special text sub-element inside the xyz element. To get the
  7275. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7276. use getAllSubText() to do this automatically.
  7277. @see isTextElement, getAllSubText, getChildElementAllSubText
  7278. */
  7279. const String getText() const throw();
  7280. /** Sets the text in a text element.
  7281. Note that this is only a valid call if this element is a text element. If it's
  7282. not, then no action will be performed.
  7283. */
  7284. void setText (const String& newText) throw();
  7285. /** Returns all the text from this element's child nodes.
  7286. This iterates all the child elements and when it finds text elements,
  7287. it concatenates their text into a big string which it returns.
  7288. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7289. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7290. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7291. */
  7292. const String getAllSubText() const throw();
  7293. /** Returns all the sub-text of a named child element.
  7294. If there is a child element with the given tag name, this will return
  7295. all of its sub-text (by calling getAllSubText() on it). If there is
  7296. no such child element, this will return the default string passed-in.
  7297. @see getAllSubText
  7298. */
  7299. const String getChildElementAllSubText (const tchar* const childTagName,
  7300. const String& defaultReturnValue) const throw();
  7301. /** Appends a section of text to this element.
  7302. @see isTextElement, getText, getAllSubText
  7303. */
  7304. void addTextElement (const String& text) throw();
  7305. /** Removes all the text elements from this element.
  7306. @see isTextElement, getText, getAllSubText, addTextElement
  7307. */
  7308. void deleteAllTextElements() throw();
  7309. /** Creates a text element that can be added to a parent element.
  7310. */
  7311. static XmlElement* createTextElement (const String& text) throw();
  7312. juce_UseDebuggingNewOperator
  7313. private:
  7314. friend class XmlDocument;
  7315. String tagName;
  7316. XmlElement* firstChildElement;
  7317. XmlElement* nextElement;
  7318. struct XmlAttributeNode
  7319. {
  7320. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7321. XmlAttributeNode (const String& name, const String& value) throw();
  7322. String name, value;
  7323. XmlAttributeNode* next;
  7324. };
  7325. XmlAttributeNode* attributes;
  7326. XmlElement (int) throw(); // for internal use
  7327. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  7328. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  7329. void writeElementAsText (OutputStream& out,
  7330. const int indentationLevel,
  7331. const int lineWrapLength) const throw();
  7332. XmlElement** getChildElementsAsArray (const int) const throw();
  7333. void reorderChildElements (XmlElement** const, const int) throw();
  7334. };
  7335. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7336. /********* End of inlined file: juce_XmlElement.h *********/
  7337. /**
  7338. A set of named property values, which can be strings, integers, floating point, etc.
  7339. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7340. to load and save types other than strings.
  7341. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7342. messages and saves/loads the list from a file.
  7343. */
  7344. class JUCE_API PropertySet
  7345. {
  7346. public:
  7347. /** Creates an empty PropertySet.
  7348. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7349. case-insensitive way
  7350. */
  7351. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7352. /** Creates a copy of another PropertySet.
  7353. */
  7354. PropertySet (const PropertySet& other) throw();
  7355. /** Copies another PropertySet over this one.
  7356. */
  7357. const PropertySet& operator= (const PropertySet& other) throw();
  7358. /** Destructor. */
  7359. virtual ~PropertySet();
  7360. /** Returns one of the properties as a string.
  7361. If the value isn't found in this set, then this will look for it in a fallback
  7362. property set (if you've specified one with the setFallbackPropertySet() method),
  7363. and if it can't find one there, it'll return the default value passed-in.
  7364. @param keyName the name of the property to retrieve
  7365. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7366. */
  7367. const String getValue (const String& keyName,
  7368. const String& defaultReturnValue = String::empty) const throw();
  7369. /** Returns one of the properties as an integer.
  7370. If the value isn't found in this set, then this will look for it in a fallback
  7371. property set (if you've specified one with the setFallbackPropertySet() method),
  7372. and if it can't find one there, it'll return the default value passed-in.
  7373. @param keyName the name of the property to retrieve
  7374. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7375. */
  7376. int getIntValue (const String& keyName,
  7377. const int defaultReturnValue = 0) const throw();
  7378. /** Returns one of the properties as an double.
  7379. If the value isn't found in this set, then this will look for it in a fallback
  7380. property set (if you've specified one with the setFallbackPropertySet() method),
  7381. and if it can't find one there, it'll return the default value passed-in.
  7382. @param keyName the name of the property to retrieve
  7383. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7384. */
  7385. double getDoubleValue (const String& keyName,
  7386. const double defaultReturnValue = 0.0) const throw();
  7387. /** Returns one of the properties as an boolean.
  7388. The result will be true if the string found for this key name can be parsed as a non-zero
  7389. integer.
  7390. If the value isn't found in this set, then this will look for it in a fallback
  7391. property set (if you've specified one with the setFallbackPropertySet() method),
  7392. and if it can't find one there, it'll return the default value passed-in.
  7393. @param keyName the name of the property to retrieve
  7394. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7395. */
  7396. bool getBoolValue (const String& keyName,
  7397. const bool defaultReturnValue = false) const throw();
  7398. /** Returns one of the properties as an XML element.
  7399. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7400. key isn't found, or if the entry contains an string that isn't valid XML.
  7401. If the value isn't found in this set, then this will look for it in a fallback
  7402. property set (if you've specified one with the setFallbackPropertySet() method),
  7403. and if it can't find one there, it'll return the default value passed-in.
  7404. @param keyName the name of the property to retrieve
  7405. */
  7406. XmlElement* getXmlValue (const String& keyName) const;
  7407. /** Sets a named property as a string.
  7408. @param keyName the name of the property to set. (This mustn't be an empty string)
  7409. @param value the new value to set it to
  7410. */
  7411. void setValue (const String& keyName, const String& value) throw();
  7412. /** Sets a named property as a string.
  7413. @param keyName the name of the property to set. (This mustn't be an empty string)
  7414. @param value the new value to set it to
  7415. */
  7416. void setValue (const String& keyName, const tchar* const value) throw();
  7417. /** Sets a named property to an integer.
  7418. @param keyName the name of the property to set. (This mustn't be an empty string)
  7419. @param value the new value to set it to
  7420. */
  7421. void setValue (const String& keyName, const int value) throw();
  7422. /** Sets a named property to a double.
  7423. @param keyName the name of the property to set. (This mustn't be an empty string)
  7424. @param value the new value to set it to
  7425. */
  7426. void setValue (const String& keyName, const double value) throw();
  7427. /** Sets a named property to a boolean.
  7428. @param keyName the name of the property to set. (This mustn't be an empty string)
  7429. @param value the new value to set it to
  7430. */
  7431. void setValue (const String& keyName, const bool value) throw();
  7432. /** Sets a named property to an XML element.
  7433. @param keyName the name of the property to set. (This mustn't be an empty string)
  7434. @param xml the new element to set it to. If this is zero, the value will be set to
  7435. an empty string
  7436. @see getXmlValue
  7437. */
  7438. void setValue (const String& keyName, const XmlElement* const xml);
  7439. /** Deletes a property.
  7440. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7441. */
  7442. void removeValue (const String& keyName) throw();
  7443. /** Returns true if the properies include the given key. */
  7444. bool containsKey (const String& keyName) const throw();
  7445. /** Removes all values. */
  7446. void clear();
  7447. /** Returns the keys/value pair array containing all the properties. */
  7448. StringPairArray& getAllProperties() throw() { return properties; }
  7449. /** Returns the lock used when reading or writing to this set */
  7450. const CriticalSection& getLock() const throw() { return lock; }
  7451. /** Returns an XML element which encapsulates all the items in this property set.
  7452. The string parameter is the tag name that should be used for the node.
  7453. @see restoreFromXml
  7454. */
  7455. XmlElement* createXml (const String& nodeName) const throw();
  7456. /** Reloads a set of properties that were previously stored as XML.
  7457. The node passed in must have been created by the createXml() method.
  7458. @see createXml
  7459. */
  7460. void restoreFromXml (const XmlElement& xml) throw();
  7461. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7462. set in this one.
  7463. If you set this up to be a pointer to a second property set, then whenever one
  7464. of the getValue() methods fails to find an entry in this set, it will look up that
  7465. value in the fallback set, and if it finds it, it will return that.
  7466. Make sure that you don't delete the fallback set while it's still being used by
  7467. another set! To remove the fallback set, just call this method with a null pointer.
  7468. @see getFallbackPropertySet
  7469. */
  7470. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7471. /** Returns the fallback property set.
  7472. @see setFallbackPropertySet
  7473. */
  7474. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7475. juce_UseDebuggingNewOperator
  7476. protected:
  7477. /** Subclasses can override this to be told when one of the properies has been changed.
  7478. */
  7479. virtual void propertyChanged();
  7480. private:
  7481. StringPairArray properties;
  7482. PropertySet* fallbackProperties;
  7483. CriticalSection lock;
  7484. bool ignoreCaseOfKeys;
  7485. };
  7486. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7487. /********* End of inlined file: juce_PropertySet.h *********/
  7488. #endif
  7489. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7490. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  7491. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7492. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7493. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  7494. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7495. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7496. /**
  7497. Adds reference-counting to an object.
  7498. To add reference-counting to a class, derive it from this class, and
  7499. use the ReferenceCountedObjectPtr class to point to it.
  7500. e.g. @code
  7501. class MyClass : public ReferenceCountedObject
  7502. {
  7503. void foo();
  7504. // This is a neat way of declaring a typedef for a pointer class,
  7505. // rather than typing out the full templated name each time..
  7506. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  7507. };
  7508. MyClass::Ptr p = new MyClass();
  7509. MyClass::Ptr p2 = p;
  7510. p = 0;
  7511. p2->foo();
  7512. @endcode
  7513. Once a new ReferenceCountedObject has been assigned to a pointer, be
  7514. careful not to delete the object manually.
  7515. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  7516. */
  7517. class JUCE_API ReferenceCountedObject
  7518. {
  7519. public:
  7520. /** Increments the object's reference count.
  7521. This is done automatically by the smart pointer, but is public just
  7522. in case it's needed for nefarious purposes.
  7523. */
  7524. inline void incReferenceCount() throw()
  7525. {
  7526. atomicIncrement (refCounts);
  7527. jassert (refCounts > 0);
  7528. }
  7529. /** Decreases the object's reference count.
  7530. If the count gets to zero, the object will be deleted.
  7531. */
  7532. inline void decReferenceCount() throw()
  7533. {
  7534. jassert (refCounts > 0);
  7535. if (atomicDecrementAndReturn (refCounts) == 0)
  7536. delete this;
  7537. }
  7538. /** Returns the object's current reference count. */
  7539. inline int getReferenceCount() const throw()
  7540. {
  7541. return refCounts;
  7542. }
  7543. protected:
  7544. /** Creates the reference-counted object (with an initial ref count of zero). */
  7545. ReferenceCountedObject()
  7546. : refCounts (0)
  7547. {
  7548. }
  7549. /** Destructor. */
  7550. virtual ~ReferenceCountedObject()
  7551. {
  7552. // it's dangerous to delete an object that's still referenced by something else!
  7553. jassert (refCounts == 0);
  7554. }
  7555. private:
  7556. int refCounts;
  7557. };
  7558. /**
  7559. Used to point to an object of type ReferenceCountedObject.
  7560. It's wise to use a typedef instead of typing out the templated name
  7561. each time - e.g.
  7562. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7563. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7564. */
  7565. template <class ReferenceCountedObjectClass>
  7566. class ReferenceCountedObjectPtr
  7567. {
  7568. public:
  7569. /** Creates a pointer to a null object. */
  7570. inline ReferenceCountedObjectPtr() throw()
  7571. : referencedObject (0)
  7572. {
  7573. }
  7574. /** Creates a pointer to an object.
  7575. This will increment the object's reference-count if it is non-null.
  7576. */
  7577. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7578. : referencedObject (refCountedObject)
  7579. {
  7580. if (refCountedObject != 0)
  7581. refCountedObject->incReferenceCount();
  7582. }
  7583. /** Copies another pointer.
  7584. This will increment the object's reference-count (if it is non-null).
  7585. */
  7586. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7587. : referencedObject (other.referencedObject)
  7588. {
  7589. if (referencedObject != 0)
  7590. referencedObject->incReferenceCount();
  7591. }
  7592. /** Changes this pointer to point at a different object.
  7593. The reference count of the old object is decremented, and it might be
  7594. deleted if it hits zero. The new object's count is incremented.
  7595. */
  7596. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7597. {
  7598. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7599. if (newObject != referencedObject)
  7600. {
  7601. if (newObject != 0)
  7602. newObject->incReferenceCount();
  7603. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7604. referencedObject = newObject;
  7605. if (oldObject != 0)
  7606. oldObject->decReferenceCount();
  7607. }
  7608. return *this;
  7609. }
  7610. /** Changes this pointer to point at a different object.
  7611. The reference count of the old object is decremented, and it might be
  7612. deleted if it hits zero. The new object's count is incremented.
  7613. */
  7614. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7615. {
  7616. if (referencedObject != newObject)
  7617. {
  7618. if (newObject != 0)
  7619. newObject->incReferenceCount();
  7620. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7621. referencedObject = newObject;
  7622. if (oldObject != 0)
  7623. oldObject->decReferenceCount();
  7624. }
  7625. return *this;
  7626. }
  7627. /** Destructor.
  7628. This will decrement the object's reference-count, and may delete it if it
  7629. gets to zero.
  7630. */
  7631. inline ~ReferenceCountedObjectPtr()
  7632. {
  7633. if (referencedObject != 0)
  7634. referencedObject->decReferenceCount();
  7635. }
  7636. /** Returns the object that this pointer references.
  7637. The pointer returned may be zero, of course.
  7638. */
  7639. inline operator ReferenceCountedObjectClass*() const throw()
  7640. {
  7641. return referencedObject;
  7642. }
  7643. /** Returns true if this pointer refers to the given object. */
  7644. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7645. {
  7646. return referencedObject == object;
  7647. }
  7648. /** Returns true if this pointer doesn't refer to the given object. */
  7649. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7650. {
  7651. return referencedObject != object;
  7652. }
  7653. // the -> operator is called on the referenced object
  7654. inline ReferenceCountedObjectClass* operator->() const throw()
  7655. {
  7656. return referencedObject;
  7657. }
  7658. private:
  7659. ReferenceCountedObjectClass* referencedObject;
  7660. };
  7661. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7662. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7663. /**
  7664. Holds a list of objects derived from ReferenceCountedObject.
  7665. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7666. and takes care of incrementing and decrementing their ref counts when they
  7667. are added and removed from the array.
  7668. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7669. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7670. @see Array, OwnedArray, StringArray
  7671. */
  7672. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7673. class ReferenceCountedArray : private ArrayAllocationBase <ObjectClass*>
  7674. {
  7675. public:
  7676. /** Creates an empty array.
  7677. @param granularity this is the size of increment by which the internal storage
  7678. used by the array will grow. Only change it from the default if you know the
  7679. array is going to be very big and needs to be able to grow efficiently.
  7680. @see ReferenceCountedObject, ArrayAllocationBase, Array, OwnedArray
  7681. */
  7682. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7683. : ArrayAllocationBase <ObjectClass*> (granularity),
  7684. numUsed (0)
  7685. {
  7686. }
  7687. /** Creates a copy of another array */
  7688. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7689. : ArrayAllocationBase <ObjectClass*> (other.granularity)
  7690. {
  7691. other.lockArray();
  7692. numUsed = other.numUsed;
  7693. this->setAllocatedSize (numUsed);
  7694. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7695. for (int i = numUsed; --i >= 0;)
  7696. if (this->elements[i] != 0)
  7697. this->elements[i]->incReferenceCount();
  7698. other.unlockArray();
  7699. }
  7700. /** Copies another array into this one.
  7701. Any existing objects in this array will first be released.
  7702. */
  7703. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7704. {
  7705. if (this != &other)
  7706. {
  7707. other.lockArray();
  7708. lock.enter();
  7709. clear();
  7710. this->granularity = other.granularity;
  7711. this->ensureAllocatedSize (other.numUsed);
  7712. numUsed = other.numUsed;
  7713. memcpy (this->elements, other.elements, numUsed * sizeof (ObjectClass*));
  7714. minimiseStorageOverheads();
  7715. for (int i = numUsed; --i >= 0;)
  7716. if (this->elements[i] != 0)
  7717. this->elements[i]->incReferenceCount();
  7718. lock.exit();
  7719. other.unlockArray();
  7720. }
  7721. return *this;
  7722. }
  7723. /** Destructor.
  7724. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7725. */
  7726. ~ReferenceCountedArray()
  7727. {
  7728. clear();
  7729. }
  7730. /** Removes all objects from the array.
  7731. Any objects in the array that are not referenced from elsewhere will be deleted.
  7732. */
  7733. void clear()
  7734. {
  7735. lock.enter();
  7736. while (numUsed > 0)
  7737. if (this->elements [--numUsed] != 0)
  7738. this->elements [numUsed]->decReferenceCount();
  7739. jassert (numUsed == 0);
  7740. this->setAllocatedSize (0);
  7741. lock.exit();
  7742. }
  7743. /** Returns the current number of objects in the array. */
  7744. inline int size() const throw()
  7745. {
  7746. return numUsed;
  7747. }
  7748. /** Returns a pointer to the object at this index in the array.
  7749. If the index is out-of-range, this will return a null pointer, (and
  7750. it could be null anyway, because it's ok for the array to hold null
  7751. pointers as well as objects).
  7752. @see getUnchecked
  7753. */
  7754. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7755. {
  7756. lock.enter();
  7757. const ReferenceCountedObjectPtr<ObjectClass> result ((((unsigned int) index) < (unsigned int) numUsed)
  7758. ? this->elements [index]
  7759. : (ObjectClass*) 0);
  7760. lock.exit();
  7761. return result;
  7762. }
  7763. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7764. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7765. it can be used when you're sure the index if always going to be legal.
  7766. */
  7767. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7768. {
  7769. lock.enter();
  7770. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7771. const ReferenceCountedObjectPtr<ObjectClass> result (this->elements [index]);
  7772. lock.exit();
  7773. return result;
  7774. }
  7775. /** Returns a pointer to the first object in the array.
  7776. This will return a null pointer if the array's empty.
  7777. @see getLast
  7778. */
  7779. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7780. {
  7781. lock.enter();
  7782. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? this->elements [0]
  7783. : (ObjectClass*) 0);
  7784. lock.exit();
  7785. return result;
  7786. }
  7787. /** Returns a pointer to the last object in the array.
  7788. This will return a null pointer if the array's empty.
  7789. @see getFirst
  7790. */
  7791. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7792. {
  7793. lock.enter();
  7794. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? this->elements [numUsed - 1]
  7795. : (ObjectClass*) 0);
  7796. lock.exit();
  7797. return result;
  7798. }
  7799. /** Finds the index of the first occurrence of an object in the array.
  7800. @param objectToLookFor the object to look for
  7801. @returns the index at which the object was found, or -1 if it's not found
  7802. */
  7803. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7804. {
  7805. int result = -1;
  7806. lock.enter();
  7807. ObjectClass** e = this->elements;
  7808. for (int i = numUsed; --i >= 0;)
  7809. {
  7810. if (objectToLookFor == *e)
  7811. {
  7812. result = (int) (e - this->elements);
  7813. break;
  7814. }
  7815. ++e;
  7816. }
  7817. lock.exit();
  7818. return result;
  7819. }
  7820. /** Returns true if the array contains a specified object.
  7821. @param objectToLookFor the object to look for
  7822. @returns true if the object is in the array
  7823. */
  7824. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7825. {
  7826. lock.enter();
  7827. ObjectClass** e = this->elements;
  7828. for (int i = numUsed; --i >= 0;)
  7829. {
  7830. if (objectToLookFor == *e)
  7831. {
  7832. lock.exit();
  7833. return true;
  7834. }
  7835. ++e;
  7836. }
  7837. lock.exit();
  7838. return false;
  7839. }
  7840. /** Appends a new object to the end of the array.
  7841. This will increase the new object's reference count.
  7842. @param newObject the new object to add to the array
  7843. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7844. */
  7845. void add (ObjectClass* const newObject) throw()
  7846. {
  7847. lock.enter();
  7848. this->ensureAllocatedSize (numUsed + 1);
  7849. this->elements [numUsed++] = newObject;
  7850. if (newObject != 0)
  7851. newObject->incReferenceCount();
  7852. lock.exit();
  7853. }
  7854. /** Inserts a new object into the array at the given index.
  7855. If the index is less than 0 or greater than the size of the array, the
  7856. element will be added to the end of the array.
  7857. Otherwise, it will be inserted into the array, moving all the later elements
  7858. along to make room.
  7859. This will increase the new object's reference count.
  7860. @param indexToInsertAt the index at which the new element should be inserted
  7861. @param newObject the new object to add to the array
  7862. @see add, addSorted, addIfNotAlreadyThere, set
  7863. */
  7864. void insert (int indexToInsertAt,
  7865. ObjectClass* const newObject) throw()
  7866. {
  7867. if (indexToInsertAt >= 0)
  7868. {
  7869. lock.enter();
  7870. if (indexToInsertAt > numUsed)
  7871. indexToInsertAt = numUsed;
  7872. this->ensureAllocatedSize (numUsed + 1);
  7873. ObjectClass** const e = this->elements + indexToInsertAt;
  7874. const int numToMove = numUsed - indexToInsertAt;
  7875. if (numToMove > 0)
  7876. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7877. *e = newObject;
  7878. if (newObject != 0)
  7879. newObject->incReferenceCount();
  7880. ++numUsed;
  7881. lock.exit();
  7882. }
  7883. else
  7884. {
  7885. add (newObject);
  7886. }
  7887. }
  7888. /** Appends a new object at the end of the array as long as the array doesn't
  7889. already contain it.
  7890. If the array already contains a matching object, nothing will be done.
  7891. @param newObject the new object to add to the array
  7892. */
  7893. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7894. {
  7895. lock.enter();
  7896. if (! contains (newObject))
  7897. add (newObject);
  7898. lock.exit();
  7899. }
  7900. /** Replaces an object in the array with a different one.
  7901. If the index is less than zero, this method does nothing.
  7902. If the index is beyond the end of the array, the new object is added to the end of the array.
  7903. The object being added has its reference count increased, and if it's replacing
  7904. another object, then that one has its reference count decreased, and may be deleted.
  7905. @param indexToChange the index whose value you want to change
  7906. @param newObject the new value to set for this index.
  7907. @see add, insert, remove
  7908. */
  7909. void set (const int indexToChange,
  7910. ObjectClass* const newObject)
  7911. {
  7912. if (indexToChange >= 0)
  7913. {
  7914. lock.enter();
  7915. if (newObject != 0)
  7916. newObject->incReferenceCount();
  7917. if (indexToChange < numUsed)
  7918. {
  7919. if (this->elements [indexToChange] != 0)
  7920. this->elements [indexToChange]->decReferenceCount();
  7921. this->elements [indexToChange] = newObject;
  7922. }
  7923. else
  7924. {
  7925. this->ensureAllocatedSize (numUsed + 1);
  7926. this->elements [numUsed++] = newObject;
  7927. }
  7928. lock.exit();
  7929. }
  7930. }
  7931. /** Adds elements from another array to the end of this array.
  7932. @param arrayToAddFrom the array from which to copy the elements
  7933. @param startIndex the first element of the other array to start copying from
  7934. @param numElementsToAdd how many elements to add from the other array. If this
  7935. value is negative or greater than the number of available elements,
  7936. all available elements will be copied.
  7937. @see add
  7938. */
  7939. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7940. int startIndex = 0,
  7941. int numElementsToAdd = -1) throw()
  7942. {
  7943. arrayToAddFrom.lockArray();
  7944. lock.enter();
  7945. if (startIndex < 0)
  7946. {
  7947. jassertfalse
  7948. startIndex = 0;
  7949. }
  7950. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7951. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7952. if (numElementsToAdd > 0)
  7953. {
  7954. this->ensureAllocatedSize (numUsed + numElementsToAdd);
  7955. while (--numElementsToAdd >= 0)
  7956. add (arrayToAddFrom.getUnchecked (startIndex++));
  7957. }
  7958. lock.exit();
  7959. arrayToAddFrom.unlockArray();
  7960. }
  7961. /** Inserts a new object into the array assuming that the array is sorted.
  7962. This will use a comparator to find the position at which the new object
  7963. should go. If the array isn't sorted, the behaviour of this
  7964. method will be unpredictable.
  7965. @param comparator the comparator object to use to compare the elements - see the
  7966. sort() method for details about this object's form
  7967. @param newObject the new object to insert to the array
  7968. @see add, sort
  7969. */
  7970. template <class ElementComparator>
  7971. void addSorted (ElementComparator& comparator,
  7972. ObjectClass* newObject) throw()
  7973. {
  7974. lock.enter();
  7975. insert (findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed), newObject);
  7976. lock.exit();
  7977. }
  7978. /** Inserts or replaces an object in the array, assuming it is sorted.
  7979. This is similar to addSorted, but if a matching element already exists, then it will be
  7980. replaced by the new one, rather than the new one being added as well.
  7981. */
  7982. template <class ElementComparator>
  7983. void addOrReplaceSorted (ElementComparator& comparator,
  7984. ObjectClass* newObject) throw()
  7985. {
  7986. lock.enter();
  7987. const int index = findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed);
  7988. if (index > 0 && comparator.compareElements (newObject, this->elements [index - 1]) == 0)
  7989. set (index - 1, newObject); // replace an existing object that matches
  7990. else
  7991. insert (index, newObject); // no match, so insert the new one
  7992. lock.exit();
  7993. }
  7994. /** Removes an object from the array.
  7995. This will remove the object at a given index and move back all the
  7996. subsequent objects to close the gap.
  7997. If the index passed in is out-of-range, nothing will happen.
  7998. The object that is removed will have its reference count decreased,
  7999. and may be deleted if not referenced from elsewhere.
  8000. @param indexToRemove the index of the element to remove
  8001. @see removeObject, removeRange
  8002. */
  8003. void remove (const int indexToRemove)
  8004. {
  8005. lock.enter();
  8006. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8007. {
  8008. ObjectClass** const e = this->elements + indexToRemove;
  8009. if (*e != 0)
  8010. (*e)->decReferenceCount();
  8011. --numUsed;
  8012. const int numberToShift = numUsed - indexToRemove;
  8013. if (numberToShift > 0)
  8014. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8015. if ((numUsed << 1) < this->numAllocated)
  8016. minimiseStorageOverheads();
  8017. }
  8018. lock.exit();
  8019. }
  8020. /** Removes the first occurrence of a specified object from the array.
  8021. If the item isn't found, no action is taken. If it is found, it is
  8022. removed and has its reference count decreased.
  8023. @param objectToRemove the object to try to remove
  8024. @see remove, removeRange
  8025. */
  8026. void removeObject (ObjectClass* const objectToRemove)
  8027. {
  8028. lock.enter();
  8029. remove (indexOf (objectToRemove));
  8030. lock.exit();
  8031. }
  8032. /** Removes a range of objects from the array.
  8033. This will remove a set of objects, starting from the given index,
  8034. and move any subsequent elements down to close the gap.
  8035. If the range extends beyond the bounds of the array, it will
  8036. be safely clipped to the size of the array.
  8037. The objects that are removed will have their reference counts decreased,
  8038. and may be deleted if not referenced from elsewhere.
  8039. @param startIndex the index of the first object to remove
  8040. @param numberToRemove how many objects should be removed
  8041. @see remove, removeObject
  8042. */
  8043. void removeRange (const int startIndex,
  8044. const int numberToRemove)
  8045. {
  8046. lock.enter();
  8047. const int start = jlimit (0, numUsed, startIndex);
  8048. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8049. if (end > start)
  8050. {
  8051. int i;
  8052. for (i = start; i < end; ++i)
  8053. {
  8054. if (this->elements[i] != 0)
  8055. {
  8056. this->elements[i]->decReferenceCount();
  8057. this->elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8058. }
  8059. }
  8060. const int rangeSize = end - start;
  8061. ObjectClass** e = this->elements + start;
  8062. i = numUsed - end;
  8063. numUsed -= rangeSize;
  8064. while (--i >= 0)
  8065. {
  8066. *e = e [rangeSize];
  8067. ++e;
  8068. }
  8069. if ((numUsed << 1) < this->numAllocated)
  8070. minimiseStorageOverheads();
  8071. }
  8072. lock.exit();
  8073. }
  8074. /** Removes the last n objects from the array.
  8075. The objects that are removed will have their reference counts decreased,
  8076. and may be deleted if not referenced from elsewhere.
  8077. @param howManyToRemove how many objects to remove from the end of the array
  8078. @see remove, removeObject, removeRange
  8079. */
  8080. void removeLast (int howManyToRemove = 1)
  8081. {
  8082. lock.enter();
  8083. if (howManyToRemove > numUsed)
  8084. howManyToRemove = numUsed;
  8085. while (--howManyToRemove >= 0)
  8086. remove (numUsed - 1);
  8087. lock.exit();
  8088. }
  8089. /** Swaps a pair of objects in the array.
  8090. If either of the indexes passed in is out-of-range, nothing will happen,
  8091. otherwise the two objects at these positions will be exchanged.
  8092. */
  8093. void swap (const int index1,
  8094. const int index2) throw()
  8095. {
  8096. lock.enter();
  8097. if (((unsigned int) index1) < (unsigned int) numUsed
  8098. && ((unsigned int) index2) < (unsigned int) numUsed)
  8099. {
  8100. swapVariables (this->elements [index1],
  8101. this->elements [index2]);
  8102. }
  8103. lock.exit();
  8104. }
  8105. /** Moves one of the objects to a different position.
  8106. This will move the object to a specified index, shuffling along
  8107. any intervening elements as required.
  8108. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8109. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8110. @param currentIndex the index of the object to be moved. If this isn't a
  8111. valid index, then nothing will be done
  8112. @param newIndex the index at which you'd like this object to end up. If this
  8113. is less than zero, it will be moved to the end of the array
  8114. */
  8115. void move (const int currentIndex,
  8116. int newIndex) throw()
  8117. {
  8118. if (currentIndex != newIndex)
  8119. {
  8120. lock.enter();
  8121. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8122. {
  8123. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8124. newIndex = numUsed - 1;
  8125. ObjectClass* const value = this->elements [currentIndex];
  8126. if (newIndex > currentIndex)
  8127. {
  8128. memmove (this->elements + currentIndex,
  8129. this->elements + currentIndex + 1,
  8130. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8131. }
  8132. else
  8133. {
  8134. memmove (this->elements + newIndex + 1,
  8135. this->elements + newIndex,
  8136. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8137. }
  8138. this->elements [newIndex] = value;
  8139. }
  8140. lock.exit();
  8141. }
  8142. }
  8143. /** Compares this array to another one.
  8144. @returns true only if the other array contains the same objects in the same order
  8145. */
  8146. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8147. {
  8148. other.lockArray();
  8149. lock.enter();
  8150. bool result = numUsed == other.numUsed;
  8151. if (result)
  8152. {
  8153. for (int i = numUsed; --i >= 0;)
  8154. {
  8155. if (this->elements [i] != other.elements [i])
  8156. {
  8157. result = false;
  8158. break;
  8159. }
  8160. }
  8161. }
  8162. lock.exit();
  8163. other.unlockArray();
  8164. return result;
  8165. }
  8166. /** Compares this array to another one.
  8167. @see operator==
  8168. */
  8169. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8170. {
  8171. return ! operator== (other);
  8172. }
  8173. /** Sorts the elements in the array.
  8174. This will use a comparator object to sort the elements into order. The object
  8175. passed must have a method of the form:
  8176. @code
  8177. int compareElements (ElementType first, ElementType second);
  8178. @endcode
  8179. ..and this method must return:
  8180. - a value of < 0 if the first comes before the second
  8181. - a value of 0 if the two objects are equivalent
  8182. - a value of > 0 if the second comes before the first
  8183. To improve performance, the compareElements() method can be declared as static or const.
  8184. @param comparator the comparator to use for comparing elements.
  8185. @param retainOrderOfEquivalentItems if this is true, then items
  8186. which the comparator says are equivalent will be
  8187. kept in the order in which they currently appear
  8188. in the array. This is slower to perform, but may
  8189. be important in some cases. If it's false, a faster
  8190. algorithm is used, but equivalent elements may be
  8191. rearranged.
  8192. @see sortArray
  8193. */
  8194. template <class ElementComparator>
  8195. void sort (ElementComparator& comparator,
  8196. const bool retainOrderOfEquivalentItems = false) const throw()
  8197. {
  8198. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8199. // avoids getting warning messages about the parameter being unused
  8200. lock.enter();
  8201. sortArray (comparator, this->elements, 0, size() - 1, retainOrderOfEquivalentItems);
  8202. lock.exit();
  8203. }
  8204. /** Reduces the amount of storage being used by the array.
  8205. Arrays typically allocate slightly more storage than they need, and after
  8206. removing elements, they may have quite a lot of unused space allocated.
  8207. This method will reduce the amount of allocated storage to a minimum.
  8208. */
  8209. void minimiseStorageOverheads() throw()
  8210. {
  8211. lock.enter();
  8212. if (numUsed == 0)
  8213. {
  8214. this->setAllocatedSize (0);
  8215. }
  8216. else
  8217. {
  8218. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8219. if (newAllocation < this->numAllocated)
  8220. this->setAllocatedSize (newAllocation);
  8221. }
  8222. lock.exit();
  8223. }
  8224. /** Locks the array's CriticalSection.
  8225. Of course if the type of section used is a DummyCriticalSection, this won't
  8226. have any effect.
  8227. @see unlockArray
  8228. */
  8229. void lockArray() const throw()
  8230. {
  8231. lock.enter();
  8232. }
  8233. /** Unlocks the array's CriticalSection.
  8234. Of course if the type of section used is a DummyCriticalSection, this won't
  8235. have any effect.
  8236. @see lockArray
  8237. */
  8238. void unlockArray() const throw()
  8239. {
  8240. lock.exit();
  8241. }
  8242. juce_UseDebuggingNewOperator
  8243. private:
  8244. int numUsed;
  8245. TypeOfCriticalSectionToUse lock;
  8246. };
  8247. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8248. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  8249. #endif
  8250. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8251. #endif
  8252. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8253. /********* Start of inlined file: juce_SortedSet.h *********/
  8254. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8255. #define __JUCE_SORTEDSET_JUCEHEADER__
  8256. #if JUCE_MSVC
  8257. #pragma warning (push)
  8258. #pragma warning (disable: 4512)
  8259. #endif
  8260. /**
  8261. Holds a set of unique primitive objects, such as ints or doubles.
  8262. A set can only hold one item with a given value, so if for example it's a
  8263. set of integers, attempting to add the same integer twice will do nothing
  8264. the second time.
  8265. Internally, the list of items is kept sorted (which means that whatever
  8266. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8267. to determine the order), and searching the set for known values is very fast
  8268. because it uses a binary-chop method.
  8269. Note that if you're using a class or struct as the element type, it must be
  8270. capable of being copied or moved with a straightforward memcpy, rather than
  8271. needing construction and destruction code.
  8272. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8273. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8274. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8275. */
  8276. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8277. class SortedSet : private ArrayAllocationBase <ElementType>
  8278. {
  8279. public:
  8280. /** Creates an empty set.
  8281. @param granularity this is the size of increment by which the internal storage
  8282. used by the array will grow. Only change it from the default if you know the
  8283. array is going to be very big and needs to be able to grow efficiently.
  8284. @see ArrayAllocationBase
  8285. */
  8286. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  8287. : ArrayAllocationBase <ElementType> (granularity),
  8288. numUsed (0)
  8289. {
  8290. }
  8291. /** Creates a copy of another set.
  8292. @param other the set to copy
  8293. */
  8294. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  8295. : ArrayAllocationBase <ElementType> (other.granularity)
  8296. {
  8297. other.lockSet();
  8298. numUsed = other.numUsed;
  8299. setAllocatedSize (other.numUsed);
  8300. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  8301. other.unlockSet();
  8302. }
  8303. /** Destructor. */
  8304. ~SortedSet() throw()
  8305. {
  8306. }
  8307. /** Copies another set over this one.
  8308. @param other the set to copy
  8309. */
  8310. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  8311. {
  8312. if (this != &other)
  8313. {
  8314. other.lockSet();
  8315. lock.enter();
  8316. this->granularity = other.granularity;
  8317. ensureAllocatedSize (other.size());
  8318. numUsed = other.numUsed;
  8319. memcpy (this->elements, other.elements, numUsed * sizeof (ElementType));
  8320. minimiseStorageOverheads();
  8321. lock.exit();
  8322. other.unlockSet();
  8323. }
  8324. return *this;
  8325. }
  8326. /** Compares this set to another one.
  8327. Two sets are considered equal if they both contain the same set of
  8328. elements.
  8329. @param other the other set to compare with
  8330. */
  8331. bool operator== (const SortedSet<ElementType>& other) const throw()
  8332. {
  8333. lock.enter();
  8334. if (numUsed != other.numUsed)
  8335. {
  8336. lock.exit();
  8337. return false;
  8338. }
  8339. for (int i = numUsed; --i >= 0;)
  8340. {
  8341. if (this->elements [i] != other.elements [i])
  8342. {
  8343. lock.exit();
  8344. return false;
  8345. }
  8346. }
  8347. lock.exit();
  8348. return true;
  8349. }
  8350. /** Compares this set to another one.
  8351. Two sets are considered equal if they both contain the same set of
  8352. elements.
  8353. @param other the other set to compare with
  8354. */
  8355. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8356. {
  8357. return ! operator== (other);
  8358. }
  8359. /** Removes all elements from the set.
  8360. This will remove all the elements, and free any storage that the set is
  8361. using. To clear it without freeing the storage, use the clearQuick()
  8362. method instead.
  8363. @see clearQuick
  8364. */
  8365. void clear() throw()
  8366. {
  8367. lock.enter();
  8368. this->setAllocatedSize (0);
  8369. numUsed = 0;
  8370. lock.exit();
  8371. }
  8372. /** Removes all elements from the set without freeing the array's allocated storage.
  8373. @see clear
  8374. */
  8375. void clearQuick() throw()
  8376. {
  8377. lock.enter();
  8378. numUsed = 0;
  8379. lock.exit();
  8380. }
  8381. /** Returns the current number of elements in the set.
  8382. */
  8383. inline int size() const throw()
  8384. {
  8385. return numUsed;
  8386. }
  8387. /** Returns one of the elements in the set.
  8388. If the index passed in is beyond the range of valid elements, this
  8389. will return zero.
  8390. If you're certain that the index will always be a valid element, you
  8391. can call getUnchecked() instead, which is faster.
  8392. @param index the index of the element being requested (0 is the first element in the set)
  8393. @see getUnchecked, getFirst, getLast
  8394. */
  8395. inline ElementType operator[] (const int index) const throw()
  8396. {
  8397. lock.enter();
  8398. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  8399. ? this->elements [index]
  8400. : (ElementType) 0;
  8401. lock.exit();
  8402. return result;
  8403. }
  8404. /** Returns one of the elements in the set, without checking the index passed in.
  8405. Unlike the operator[] method, this will try to return an element without
  8406. checking that the index is within the bounds of the set, so should only
  8407. be used when you're confident that it will always be a valid index.
  8408. @param index the index of the element being requested (0 is the first element in the set)
  8409. @see operator[], getFirst, getLast
  8410. */
  8411. inline ElementType getUnchecked (const int index) const throw()
  8412. {
  8413. lock.enter();
  8414. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8415. const ElementType result = this->elements [index];
  8416. lock.exit();
  8417. return result;
  8418. }
  8419. /** Returns the first element in the set, or 0 if the set is empty.
  8420. @see operator[], getUnchecked, getLast
  8421. */
  8422. inline ElementType getFirst() const throw()
  8423. {
  8424. lock.enter();
  8425. const ElementType result = (numUsed > 0) ? this->elements [0]
  8426. : (ElementType) 0;
  8427. lock.exit();
  8428. return result;
  8429. }
  8430. /** Returns the last element in the set, or 0 if the set is empty.
  8431. @see operator[], getUnchecked, getFirst
  8432. */
  8433. inline ElementType getLast() const throw()
  8434. {
  8435. lock.enter();
  8436. const ElementType result = (numUsed > 0) ? this->elements [numUsed - 1]
  8437. : (ElementType) 0;
  8438. lock.exit();
  8439. return result;
  8440. }
  8441. /** Finds the index of the first element which matches the value passed in.
  8442. This will search the set for the given object, and return the index
  8443. of its first occurrence. If the object isn't found, the method will return -1.
  8444. @param elementToLookFor the value or object to look for
  8445. @returns the index of the object, or -1 if it's not found
  8446. */
  8447. int indexOf (const ElementType elementToLookFor) const throw()
  8448. {
  8449. lock.enter();
  8450. int start = 0;
  8451. int end = numUsed;
  8452. for (;;)
  8453. {
  8454. if (start >= end)
  8455. {
  8456. lock.exit();
  8457. return -1;
  8458. }
  8459. else if (elementToLookFor == this->elements [start])
  8460. {
  8461. lock.exit();
  8462. return start;
  8463. }
  8464. else
  8465. {
  8466. const int halfway = (start + end) >> 1;
  8467. if (halfway == start)
  8468. {
  8469. lock.exit();
  8470. return -1;
  8471. }
  8472. else if (elementToLookFor >= this->elements [halfway])
  8473. start = halfway;
  8474. else
  8475. end = halfway;
  8476. }
  8477. }
  8478. }
  8479. /** Returns true if the set contains at least one occurrence of an object.
  8480. @param elementToLookFor the value or object to look for
  8481. @returns true if the item is found
  8482. */
  8483. bool contains (const ElementType elementToLookFor) const throw()
  8484. {
  8485. lock.enter();
  8486. int start = 0;
  8487. int end = numUsed;
  8488. for (;;)
  8489. {
  8490. if (start >= end)
  8491. {
  8492. lock.exit();
  8493. return false;
  8494. }
  8495. else if (elementToLookFor == this->elements [start])
  8496. {
  8497. lock.exit();
  8498. return true;
  8499. }
  8500. else
  8501. {
  8502. const int halfway = (start + end) >> 1;
  8503. if (halfway == start)
  8504. {
  8505. lock.exit();
  8506. return false;
  8507. }
  8508. else if (elementToLookFor >= this->elements [halfway])
  8509. start = halfway;
  8510. else
  8511. end = halfway;
  8512. }
  8513. }
  8514. }
  8515. /** Adds a new element to the set, (as long as it's not already in there).
  8516. @param newElement the new object to add to the set
  8517. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8518. */
  8519. void add (const ElementType newElement) throw()
  8520. {
  8521. lock.enter();
  8522. int start = 0;
  8523. int end = numUsed;
  8524. for (;;)
  8525. {
  8526. if (start >= end)
  8527. {
  8528. jassert (start <= end);
  8529. insertInternal (start, newElement);
  8530. break;
  8531. }
  8532. else if (newElement == this->elements [start])
  8533. {
  8534. break;
  8535. }
  8536. else
  8537. {
  8538. const int halfway = (start + end) >> 1;
  8539. if (halfway == start)
  8540. {
  8541. if (newElement >= this->elements [halfway])
  8542. insertInternal (start + 1, newElement);
  8543. else
  8544. insertInternal (start, newElement);
  8545. break;
  8546. }
  8547. else if (newElement >= this->elements [halfway])
  8548. start = halfway;
  8549. else
  8550. end = halfway;
  8551. }
  8552. }
  8553. lock.exit();
  8554. }
  8555. /** Adds elements from an array to this set.
  8556. @param elementsToAdd the array of elements to add
  8557. @param numElementsToAdd how many elements are in this other array
  8558. @see add
  8559. */
  8560. void addArray (const ElementType* elementsToAdd,
  8561. int numElementsToAdd) throw()
  8562. {
  8563. lock.enter();
  8564. while (--numElementsToAdd >= 0)
  8565. add (*elementsToAdd++);
  8566. lock.exit();
  8567. }
  8568. /** Adds elements from another set to this one.
  8569. @param setToAddFrom the set from which to copy the elements
  8570. @param startIndex the first element of the other set to start copying from
  8571. @param numElementsToAdd how many elements to add from the other set. If this
  8572. value is negative or greater than the number of available elements,
  8573. all available elements will be copied.
  8574. @see add
  8575. */
  8576. template <class OtherSetType>
  8577. void addSet (const OtherSetType& setToAddFrom,
  8578. int startIndex = 0,
  8579. int numElementsToAdd = -1) throw()
  8580. {
  8581. setToAddFrom.lockSet();
  8582. lock.enter();
  8583. jassert (this != &setToAddFrom);
  8584. if (this != &setToAddFrom)
  8585. {
  8586. if (startIndex < 0)
  8587. {
  8588. jassertfalse
  8589. startIndex = 0;
  8590. }
  8591. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8592. numElementsToAdd = setToAddFrom.size() - startIndex;
  8593. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8594. }
  8595. lock.exit();
  8596. setToAddFrom.unlockSet();
  8597. }
  8598. /** Removes an element from the set.
  8599. This will remove the element at a given index.
  8600. If the index passed in is out-of-range, nothing will happen.
  8601. @param indexToRemove the index of the element to remove
  8602. @returns the element that has been removed
  8603. @see removeValue, removeRange
  8604. */
  8605. ElementType remove (const int indexToRemove) throw()
  8606. {
  8607. lock.enter();
  8608. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8609. {
  8610. --numUsed;
  8611. ElementType* const e = this->elements + indexToRemove;
  8612. ElementType const removed = *e;
  8613. const int numberToShift = numUsed - indexToRemove;
  8614. if (numberToShift > 0)
  8615. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8616. if ((numUsed << 1) < this->numAllocated)
  8617. minimiseStorageOverheads();
  8618. lock.exit();
  8619. return removed;
  8620. }
  8621. else
  8622. {
  8623. lock.exit();
  8624. return 0;
  8625. }
  8626. }
  8627. /** Removes an item from the set.
  8628. This will remove the given element from the set, if it's there.
  8629. @param valueToRemove the object to try to remove
  8630. @see remove, removeRange
  8631. */
  8632. void removeValue (const ElementType valueToRemove) throw()
  8633. {
  8634. lock.enter();
  8635. remove (indexOf (valueToRemove));
  8636. lock.exit();
  8637. }
  8638. /** Removes any elements which are also in another set.
  8639. @param otherSet the other set in which to look for elements to remove
  8640. @see removeValuesNotIn, remove, removeValue, removeRange
  8641. */
  8642. template <class OtherSetType>
  8643. void removeValuesIn (const OtherSetType& otherSet) throw()
  8644. {
  8645. otherSet.lockSet();
  8646. lock.enter();
  8647. if (this == &otherSet)
  8648. {
  8649. clear();
  8650. }
  8651. else
  8652. {
  8653. if (otherSet.size() > 0)
  8654. {
  8655. for (int i = numUsed; --i >= 0;)
  8656. if (otherSet.contains (this->elements [i]))
  8657. remove (i);
  8658. }
  8659. }
  8660. lock.exit();
  8661. otherSet.unlockSet();
  8662. }
  8663. /** Removes any elements which are not found in another set.
  8664. Only elements which occur in this other set will be retained.
  8665. @param otherSet the set in which to look for elements NOT to remove
  8666. @see removeValuesIn, remove, removeValue, removeRange
  8667. */
  8668. template <class OtherSetType>
  8669. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8670. {
  8671. otherSet.lockSet();
  8672. lock.enter();
  8673. if (this != &otherSet)
  8674. {
  8675. if (otherSet.size() <= 0)
  8676. {
  8677. clear();
  8678. }
  8679. else
  8680. {
  8681. for (int i = numUsed; --i >= 0;)
  8682. if (! otherSet.contains (this->elements [i]))
  8683. remove (i);
  8684. }
  8685. }
  8686. lock.exit();
  8687. otherSet.lockSet();
  8688. }
  8689. /** Reduces the amount of storage being used by the set.
  8690. Sets typically allocate slightly more storage than they need, and after
  8691. removing elements, they may have quite a lot of unused space allocated.
  8692. This method will reduce the amount of allocated storage to a minimum.
  8693. */
  8694. void minimiseStorageOverheads() throw()
  8695. {
  8696. lock.enter();
  8697. if (numUsed == 0)
  8698. {
  8699. this->setAllocatedSize (0);
  8700. }
  8701. else
  8702. {
  8703. const int newAllocation = this->granularity * (numUsed / this->granularity + 1);
  8704. if (newAllocation < this->numAllocated)
  8705. this->setAllocatedSize (newAllocation);
  8706. }
  8707. lock.exit();
  8708. }
  8709. /** Locks the set's CriticalSection.
  8710. Of course if the type of section used is a DummyCriticalSection, this won't
  8711. have any effect.
  8712. @see unlockSet
  8713. */
  8714. void lockSet() const throw()
  8715. {
  8716. lock.enter();
  8717. }
  8718. /** Unlocks the set's CriticalSection.
  8719. Of course if the type of section used is a DummyCriticalSection, this won't
  8720. have any effect.
  8721. @see lockSet
  8722. */
  8723. void unlockSet() const throw()
  8724. {
  8725. lock.exit();
  8726. }
  8727. juce_UseDebuggingNewOperator
  8728. private:
  8729. int numUsed;
  8730. TypeOfCriticalSectionToUse lock;
  8731. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8732. {
  8733. this->ensureAllocatedSize (numUsed + 1);
  8734. ElementType* const insertPos = this->elements + indexToInsertAt;
  8735. const int numberToMove = numUsed - indexToInsertAt;
  8736. if (numberToMove > 0)
  8737. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8738. *insertPos = newElement;
  8739. ++numUsed;
  8740. }
  8741. };
  8742. #if JUCE_MSVC
  8743. #pragma warning (pop)
  8744. #endif
  8745. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8746. /********* End of inlined file: juce_SortedSet.h *********/
  8747. #endif
  8748. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8749. /********* Start of inlined file: juce_SparseSet.h *********/
  8750. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8751. #define __JUCE_SPARSESET_JUCEHEADER__
  8752. /**
  8753. Holds a set of primitive values, storing them as a set of ranges.
  8754. This container acts like a simple BitArray, but can efficiently hold large
  8755. continguous ranges of values. It's quite a specialised class, mostly useful
  8756. for things like keeping the set of selected rows in a listbox.
  8757. The type used as a template paramter must be an integer type, such as int, short,
  8758. int64, etc.
  8759. */
  8760. template <class Type>
  8761. class SparseSet
  8762. {
  8763. public:
  8764. /** Creates a new empty set. */
  8765. SparseSet() throw()
  8766. {
  8767. }
  8768. /** Creates a copy of another SparseSet. */
  8769. SparseSet (const SparseSet<Type>& other) throw()
  8770. : values (other.values)
  8771. {
  8772. }
  8773. /** Destructor. */
  8774. ~SparseSet() throw()
  8775. {
  8776. }
  8777. /** Clears the set. */
  8778. void clear() throw()
  8779. {
  8780. values.clear();
  8781. }
  8782. /** Checks whether the set is empty.
  8783. This is much quicker than using (size() == 0).
  8784. */
  8785. bool isEmpty() const throw()
  8786. {
  8787. return values.size() == 0;
  8788. }
  8789. /** Returns the number of values in the set.
  8790. Because of the way the data is stored, this method can take longer if there
  8791. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8792. are any items.
  8793. */
  8794. Type size() const throw()
  8795. {
  8796. Type num = 0;
  8797. for (int i = 0; i < values.size(); i += 2)
  8798. num += values[i + 1] - values[i];
  8799. return num;
  8800. }
  8801. /** Returns one of the values in the set.
  8802. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8803. @returns the value at this index, or 0 if it's out-of-range
  8804. */
  8805. Type operator[] (int index) const throw()
  8806. {
  8807. for (int i = 0; i < values.size(); i += 2)
  8808. {
  8809. const Type s = values.getUnchecked(i);
  8810. const Type e = values.getUnchecked(i + 1);
  8811. if (index < e - s)
  8812. return s + index;
  8813. index -= e - s;
  8814. }
  8815. return (Type) 0;
  8816. }
  8817. /** Checks whether a particular value is in the set. */
  8818. bool contains (const Type valueToLookFor) const throw()
  8819. {
  8820. bool on = false;
  8821. for (int i = 0; i < values.size(); ++i)
  8822. {
  8823. if (values.getUnchecked(i) > valueToLookFor)
  8824. return on;
  8825. on = ! on;
  8826. }
  8827. return false;
  8828. }
  8829. /** Returns the number of contiguous blocks of values.
  8830. @see getRange
  8831. */
  8832. int getNumRanges() const throw()
  8833. {
  8834. return values.size() >> 1;
  8835. }
  8836. /** Returns one of the contiguous ranges of values stored.
  8837. @param rangeIndex the index of the range to look up, between 0
  8838. and (getNumRanges() - 1)
  8839. @param startValue on return, the value at the start of the range
  8840. @param numValues on return, the number of values in the range
  8841. @see getTotalRange
  8842. */
  8843. bool getRange (const int rangeIndex,
  8844. Type& startValue,
  8845. Type& numValues) const throw()
  8846. {
  8847. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8848. {
  8849. startValue = values [rangeIndex << 1];
  8850. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8851. return true;
  8852. }
  8853. return false;
  8854. }
  8855. /** Returns the lowest and highest values in the set.
  8856. @see getRange
  8857. */
  8858. bool getTotalRange (Type& lowestValue,
  8859. Type& highestValue) const throw()
  8860. {
  8861. if (values.size() > 0)
  8862. {
  8863. lowestValue = values.getUnchecked (0);
  8864. highestValue = values.getUnchecked (values.size() - 1);
  8865. return true;
  8866. }
  8867. return false;
  8868. }
  8869. /** Adds a range of contiguous values to the set.
  8870. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8871. @param firstValue the start of the range of values to add
  8872. @param numValuesToAdd how many values to add
  8873. */
  8874. void addRange (const Type firstValue,
  8875. const Type numValuesToAdd) throw()
  8876. {
  8877. jassert (numValuesToAdd >= 0);
  8878. if (numValuesToAdd > 0)
  8879. {
  8880. removeRange (firstValue, numValuesToAdd);
  8881. IntegerElementComparator<Type> sorter;
  8882. values.addSorted (sorter, firstValue);
  8883. values.addSorted (sorter, firstValue + numValuesToAdd);
  8884. simplify();
  8885. }
  8886. }
  8887. /** Removes a range of values from the set.
  8888. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8889. @param firstValue the start of the range of values to remove
  8890. @param numValuesToRemove how many values to remove
  8891. */
  8892. void removeRange (const Type firstValue,
  8893. const Type numValuesToRemove) throw()
  8894. {
  8895. jassert (numValuesToRemove >= 0);
  8896. if (numValuesToRemove >= 0
  8897. && firstValue < values.getLast())
  8898. {
  8899. const bool onAtStart = contains (firstValue - 1);
  8900. const Type lastValue = firstValue + jmin (numValuesToRemove, values.getLast() - firstValue);
  8901. const bool onAtEnd = contains (lastValue);
  8902. for (int i = values.size(); --i >= 0;)
  8903. {
  8904. if (values.getUnchecked(i) <= lastValue)
  8905. {
  8906. while (values.getUnchecked(i) >= firstValue)
  8907. {
  8908. values.remove (i);
  8909. if (--i < 0)
  8910. break;
  8911. }
  8912. break;
  8913. }
  8914. }
  8915. IntegerElementComparator<Type> sorter;
  8916. if (onAtStart)
  8917. values.addSorted (sorter, firstValue);
  8918. if (onAtEnd)
  8919. values.addSorted (sorter, lastValue);
  8920. simplify();
  8921. }
  8922. }
  8923. /** Does an XOR of the values in a given range. */
  8924. void invertRange (const Type firstValue,
  8925. const Type numValues)
  8926. {
  8927. SparseSet newItems;
  8928. newItems.addRange (firstValue, numValues);
  8929. int i;
  8930. for (i = getNumRanges(); --i >= 0;)
  8931. {
  8932. const int start = values [i << 1];
  8933. const int end = values [(i << 1) + 1];
  8934. newItems.removeRange (start, end);
  8935. }
  8936. removeRange (firstValue, numValues);
  8937. for (i = newItems.getNumRanges(); --i >= 0;)
  8938. {
  8939. const int start = newItems.values [i << 1];
  8940. const int end = newItems.values [(i << 1) + 1];
  8941. addRange (start, end);
  8942. }
  8943. }
  8944. /** Checks whether any part of a given range overlaps any part of this one. */
  8945. bool overlapsRange (const Type firstValue,
  8946. const Type numValues) throw()
  8947. {
  8948. jassert (numValues >= 0);
  8949. if (numValues > 0)
  8950. {
  8951. for (int i = getNumRanges(); --i >= 0;)
  8952. {
  8953. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8954. return false;
  8955. if (firstValue + numValues > values.getUnchecked (i << 1))
  8956. return true;
  8957. }
  8958. }
  8959. return false;
  8960. }
  8961. /** Checks whether the whole of a given range is contained within this one. */
  8962. bool containsRange (const Type firstValue,
  8963. const Type numValues) throw()
  8964. {
  8965. jassert (numValues >= 0);
  8966. if (numValues > 0)
  8967. {
  8968. for (int i = getNumRanges(); --i >= 0;)
  8969. {
  8970. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8971. return false;
  8972. if (firstValue >= values.getUnchecked (i << 1)
  8973. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  8974. return true;
  8975. }
  8976. }
  8977. return false;
  8978. }
  8979. bool operator== (const SparseSet<Type>& other) throw()
  8980. {
  8981. return values == other.values;
  8982. }
  8983. bool operator!= (const SparseSet<Type>& other) throw()
  8984. {
  8985. return values != other.values;
  8986. }
  8987. juce_UseDebuggingNewOperator
  8988. private:
  8989. // alternating start/end values of ranges of values that are present.
  8990. Array<Type> values;
  8991. void simplify() throw()
  8992. {
  8993. jassert ((values.size() & 1) == 0);
  8994. for (int i = values.size(); --i > 0;)
  8995. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8996. values.removeRange (i - 1, 2);
  8997. }
  8998. };
  8999. #endif // __JUCE_SPARSESET_JUCEHEADER__
  9000. /********* End of inlined file: juce_SparseSet.h *********/
  9001. #endif
  9002. #ifndef __JUCE_VARIANT_JUCEHEADER__
  9003. /********* Start of inlined file: juce_Variant.h *********/
  9004. #ifndef __JUCE_VARIANT_JUCEHEADER__
  9005. #define __JUCE_VARIANT_JUCEHEADER__
  9006. class JUCE_API DynamicObject;
  9007. /**
  9008. A variant class, that can be used to hold a range of primitive values.
  9009. A var object can hold a range of simple primitive values, strings, or
  9010. a reference-counted pointer to a DynamicObject. The var class is intended
  9011. to act like the values used in dynamic scripting languages.
  9012. @see DynamicObject
  9013. */
  9014. class JUCE_API var
  9015. {
  9016. public:
  9017. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  9018. /** Creates a void variant. */
  9019. var() throw();
  9020. /** Destructor. */
  9021. ~var();
  9022. var (const var& valueToCopy) throw();
  9023. var (const int value) throw();
  9024. var (const bool value) throw();
  9025. var (const double value) throw();
  9026. var (const char* const value) throw();
  9027. var (const juce_wchar* const value) throw();
  9028. var (const String& value) throw();
  9029. var (DynamicObject* const object) throw();
  9030. var (MethodFunction method) throw();
  9031. const var& operator= (const var& valueToCopy) throw();
  9032. const var& operator= (const int value) throw();
  9033. const var& operator= (const bool value) throw();
  9034. const var& operator= (const double value) throw();
  9035. const var& operator= (const char* const value) throw();
  9036. const var& operator= (const juce_wchar* const value) throw();
  9037. const var& operator= (const String& value) throw();
  9038. const var& operator= (DynamicObject* const object) throw();
  9039. const var& operator= (MethodFunction method) throw();
  9040. operator int() const throw();
  9041. operator bool() const throw();
  9042. operator double() const throw();
  9043. operator const String() const throw();
  9044. const String toString() const throw();
  9045. DynamicObject* getObject() const throw();
  9046. bool isVoid() const throw() { return type == voidType; }
  9047. bool isInt() const throw() { return type == intType; }
  9048. bool isBool() const throw() { return type == boolType; }
  9049. bool isDouble() const throw() { return type == doubleType; }
  9050. bool isString() const throw() { return type == stringType; }
  9051. bool isObject() const throw() { return type == objectType; }
  9052. bool isMethod() const throw() { return type == methodType; }
  9053. class JUCE_API identifier
  9054. {
  9055. public:
  9056. identifier (const char* const name) throw();
  9057. identifier (const String& name) throw();
  9058. ~identifier() throw();
  9059. bool operator== (const identifier& other) const throw() { return hashCode == other.hashCode; }
  9060. String name;
  9061. int hashCode;
  9062. };
  9063. /** If this variant is an object, this returns one of its properties. */
  9064. const var operator[] (const identifier& propertyName) const throw();
  9065. /** If this variant is an object, this invokes one of its methods with no arguments. */
  9066. const var call (const identifier& method) const;
  9067. /** If this variant is an object, this invokes one of its methods with one argument. */
  9068. const var call (const identifier& method, const var& arg1) const;
  9069. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  9070. const var call (const identifier& method, const var& arg1, const var& arg2) const;
  9071. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  9072. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3);
  9073. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  9074. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  9075. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  9076. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  9077. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  9078. const var invoke (const identifier& method, const var* arguments, int numArguments) const;
  9079. /** If this variant is a method pointer, this invokes it on a target object. */
  9080. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  9081. juce_UseDebuggingNewOperator
  9082. private:
  9083. enum Type
  9084. {
  9085. voidType = 0,
  9086. intType,
  9087. boolType,
  9088. doubleType,
  9089. stringType,
  9090. objectType,
  9091. methodType
  9092. };
  9093. Type type;
  9094. union
  9095. {
  9096. int intValue;
  9097. bool boolValue;
  9098. double doubleValue;
  9099. String* stringValue;
  9100. DynamicObject* objectValue;
  9101. MethodFunction methodValue;
  9102. } value;
  9103. void releaseValue() throw();
  9104. };
  9105. /**
  9106. Represents a dynamically implemented object.
  9107. An instance of this class can be used to store named properties, and
  9108. by subclassing hasMethod() and invokeMethod(), you can give your object
  9109. methods.
  9110. This is intended for use as a wrapper for scripting language objects.
  9111. */
  9112. class JUCE_API DynamicObject : public ReferenceCountedObject
  9113. {
  9114. public:
  9115. DynamicObject();
  9116. /** Destructor. */
  9117. virtual ~DynamicObject();
  9118. /** Returns true if the object has a property with this name.
  9119. Note that if the property is actually a method, this will return false.
  9120. */
  9121. virtual bool hasProperty (const var::identifier& propertyName) const;
  9122. /** Returns a named property.
  9123. This returns a void if no such property exists.
  9124. */
  9125. virtual const var getProperty (const var::identifier& propertyName) const;
  9126. /** Sets a named property. */
  9127. virtual void setProperty (const var::identifier& propertyName, const var& newValue);
  9128. /** Removes a named property. */
  9129. virtual void removeProperty (const var::identifier& propertyName);
  9130. /** Checks whether this object has the specified method.
  9131. The default implementation of this just checks whether there's a property
  9132. with this name that's actually a method, but this can be overridden for
  9133. building objects with dynamic invocation.
  9134. */
  9135. virtual bool hasMethod (const var::identifier& methodName) const;
  9136. /** Invokes a named method on this object.
  9137. The default implementation looks up the named property, and if it's a method
  9138. call, then it invokes it.
  9139. This method is virtual to allow more dynamic invocation to used for objects
  9140. where the methods may not already be set as properies.
  9141. */
  9142. virtual const var invokeMethod (const var::identifier& methodName,
  9143. const var* parameters,
  9144. int numParameters);
  9145. /** Sets up a method.
  9146. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  9147. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  9148. the code easier to read,
  9149. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  9150. @code
  9151. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  9152. @endcode
  9153. */
  9154. void setMethod (const var::identifier& methodName,
  9155. var::MethodFunction methodFunction);
  9156. /** Removes all properties and methods from the object. */
  9157. void clear();
  9158. juce_UseDebuggingNewOperator
  9159. private:
  9160. Array <int> propertyIds;
  9161. OwnedArray <var> propertyValues;
  9162. };
  9163. #endif // __JUCE_VARIANT_JUCEHEADER__
  9164. /********* End of inlined file: juce_Variant.h *********/
  9165. #endif
  9166. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  9167. #endif
  9168. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9169. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  9170. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9171. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9172. /**
  9173. Searches through a the files in a directory, returning each file that is found.
  9174. A DirectoryIterator will search through a directory and its subdirectories using
  9175. a wildcard filepattern match.
  9176. If you may be finding a large number of files, this is better than
  9177. using File::findChildFiles() because it doesn't block while it finds them
  9178. all, and this is more memory-efficient.
  9179. It can also guess how far it's got using a wildly inaccurate algorithm.
  9180. */
  9181. class JUCE_API DirectoryIterator
  9182. {
  9183. public:
  9184. /** Creates a DirectoryIterator for a given directory.
  9185. After creating one of these, call its next() method to get the
  9186. first file - e.g. @code
  9187. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  9188. while (iter.next())
  9189. {
  9190. File theFileItFound (iter.getFile());
  9191. ... etc
  9192. }
  9193. @endcode
  9194. @param directory the directory to search in
  9195. @param isRecursive whether all the subdirectories should also be searched
  9196. @param wildCard the file pattern to match
  9197. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  9198. whether to look for files, directories, or both.
  9199. */
  9200. DirectoryIterator (const File& directory,
  9201. bool isRecursive,
  9202. const String& wildCard = JUCE_T("*"),
  9203. const int whatToLookFor = File::findFiles) throw();
  9204. /** Destructor. */
  9205. ~DirectoryIterator() throw();
  9206. /** Call this to move the iterator along to the next file.
  9207. @returns true if a file was found (you can then use getFile() to see what it was) - or
  9208. false if there are no more matching files.
  9209. */
  9210. bool next() throw();
  9211. /** Returns the file that the iterator is currently pointing at.
  9212. The result of this call is only valid after a call to next() has returned true.
  9213. */
  9214. const File getFile() const throw();
  9215. /** Returns a guess of how far through the search the iterator has got.
  9216. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  9217. very accurate.
  9218. */
  9219. float getEstimatedProgress() const throw();
  9220. juce_UseDebuggingNewOperator
  9221. private:
  9222. OwnedArray <File> filesFound;
  9223. OwnedArray <File> dirsFound;
  9224. String wildCard;
  9225. int index;
  9226. const int whatToLookFor;
  9227. DirectoryIterator* subIterator;
  9228. DirectoryIterator (const DirectoryIterator&);
  9229. const DirectoryIterator& operator= (const DirectoryIterator&);
  9230. };
  9231. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  9232. /********* End of inlined file: juce_DirectoryIterator.h *********/
  9233. #endif
  9234. #ifndef __JUCE_FILE_JUCEHEADER__
  9235. #endif
  9236. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  9237. /********* Start of inlined file: juce_FileInputStream.h *********/
  9238. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  9239. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  9240. /**
  9241. An input stream that reads from a local file.
  9242. @see InputStream, FileOutputStream, File::createInputStream
  9243. */
  9244. class JUCE_API FileInputStream : public InputStream
  9245. {
  9246. public:
  9247. /** Creates a FileInputStream.
  9248. @param fileToRead the file to read from - if the file can't be accessed for some
  9249. reason, then the stream will just contain no data
  9250. */
  9251. FileInputStream (const File& fileToRead);
  9252. /** Destructor. */
  9253. ~FileInputStream();
  9254. const File& getFile() const throw() { return file; }
  9255. int64 getTotalLength();
  9256. int read (void* destBuffer, int maxBytesToRead);
  9257. bool isExhausted();
  9258. int64 getPosition();
  9259. bool setPosition (int64 pos);
  9260. juce_UseDebuggingNewOperator
  9261. private:
  9262. File file;
  9263. void* fileHandle;
  9264. int64 currentPosition, totalSize;
  9265. bool needToSeek;
  9266. };
  9267. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  9268. /********* End of inlined file: juce_FileInputStream.h *********/
  9269. #endif
  9270. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  9271. /********* Start of inlined file: juce_FileOutputStream.h *********/
  9272. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  9273. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  9274. /**
  9275. An output stream that writes into a local file.
  9276. @see OutputStream, FileInputStream, File::createOutputStream
  9277. */
  9278. class JUCE_API FileOutputStream : public OutputStream
  9279. {
  9280. public:
  9281. /** Creates a FileOutputStream.
  9282. If the file doesn't exist, it will first be created. If the file can't be
  9283. created or opened, the failedToOpen() method will return
  9284. true.
  9285. If the file already exists when opened, the stream's write-postion will
  9286. be set to the end of the file. To overwrite an existing file,
  9287. use File::deleteFile() before opening the stream, or use setPosition(0)
  9288. after it's opened (although this won't truncate the file).
  9289. It's better to use File::createOutputStream() to create one of these, rather
  9290. than using the class directly.
  9291. */
  9292. FileOutputStream (const File& fileToWriteTo,
  9293. const int bufferSizeToUse = 16384);
  9294. /** Destructor. */
  9295. ~FileOutputStream();
  9296. /** Returns the file that this stream is writing to.
  9297. */
  9298. const File& getFile() const throw() { return file; }
  9299. /** Returns true if the stream couldn't be opened for some reason.
  9300. */
  9301. bool failedToOpen() const throw() { return fileHandle == 0; }
  9302. void flush();
  9303. int64 getPosition();
  9304. bool setPosition (int64 pos);
  9305. bool write (const void* data, int numBytes);
  9306. juce_UseDebuggingNewOperator
  9307. private:
  9308. File file;
  9309. void* fileHandle;
  9310. int64 currentPosition;
  9311. int bufferSize, bytesInBuffer;
  9312. char* buffer;
  9313. };
  9314. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  9315. /********* End of inlined file: juce_FileOutputStream.h *********/
  9316. #endif
  9317. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  9318. /********* Start of inlined file: juce_FileSearchPath.h *********/
  9319. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  9320. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  9321. /**
  9322. Encapsulates a set of folders that make up a search path.
  9323. @see File
  9324. */
  9325. class JUCE_API FileSearchPath
  9326. {
  9327. public:
  9328. /** Creates an empty search path. */
  9329. FileSearchPath();
  9330. /** Creates a search path from a string of pathnames.
  9331. The path can be semicolon- or comma-separated, e.g.
  9332. "/foo/bar;/foo/moose;/fish/moose"
  9333. The separate folders are tokenised and added to the search path.
  9334. */
  9335. FileSearchPath (const String& path);
  9336. /** Creates a copy of another search path. */
  9337. FileSearchPath (const FileSearchPath& other);
  9338. /** Destructor. */
  9339. ~FileSearchPath();
  9340. /** Uses a string containing a list of pathnames to re-initialise this list.
  9341. This search path is cleared and the semicolon- or comma-separated folders
  9342. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  9343. */
  9344. const FileSearchPath& operator= (const String& path);
  9345. /** Returns the number of folders in this search path.
  9346. @see operator[]
  9347. */
  9348. int getNumPaths() const;
  9349. /** Returns one of the folders in this search path.
  9350. The file returned isn't guaranteed to actually be a valid directory.
  9351. @see getNumPaths
  9352. */
  9353. const File operator[] (const int index) const;
  9354. /** Returns the search path as a semicolon-separated list of directories. */
  9355. const String toString() const;
  9356. /** Adds a new directory to the search path.
  9357. The new directory is added to the end of the list if the insertIndex parameter is
  9358. less than zero, otherwise it is inserted at the given index.
  9359. */
  9360. void add (const File& directoryToAdd,
  9361. const int insertIndex = -1);
  9362. /** Adds a new directory to the search path if it's not already in there. */
  9363. void addIfNotAlreadyThere (const File& directoryToAdd);
  9364. /** Removes a directory from the search path. */
  9365. void remove (const int indexToRemove);
  9366. /** Merges another search path into this one.
  9367. This will remove any duplicate directories.
  9368. */
  9369. void addPath (const FileSearchPath& other);
  9370. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  9371. If the search is intended to be recursive, there's no point having nested folders in the search
  9372. path, because they'll just get searched twice and you'll get duplicate results.
  9373. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  9374. */
  9375. void removeRedundantPaths();
  9376. /** Removes any directories that don't actually exist. */
  9377. void removeNonExistentPaths();
  9378. /** Searches the path for a wildcard.
  9379. This will search all the directories in the search path in order, adding any
  9380. matching files to the results array.
  9381. @param results an array to append the results to
  9382. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  9383. return files, directories, or both.
  9384. @param searchRecursively whether to recursively search the subdirectories too
  9385. @param wildCardPattern a pattern to match against the filenames
  9386. @returns the number of files added to the array
  9387. @see File::findChildFiles
  9388. */
  9389. int findChildFiles (OwnedArray<File>& results,
  9390. const int whatToLookFor,
  9391. const bool searchRecursively,
  9392. const String& wildCardPattern = JUCE_T("*")) const;
  9393. /** Finds out whether a file is inside one of the path's directories.
  9394. This will return true if the specified file is a child of one of the
  9395. directories specified by this path. Note that this doesn't actually do any
  9396. searching or check that the files exist - it just looks at the pathnames
  9397. to work out whether the file would be inside a directory.
  9398. @param fileToCheck the file to look for
  9399. @param checkRecursively if true, then this will return true if the file is inside a
  9400. subfolder of one of the path's directories (at any depth). If false
  9401. it will only return true if the file is actually a direct child
  9402. of one of the directories.
  9403. @see File::isAChildOf
  9404. */
  9405. bool isFileInPath (const File& fileToCheck,
  9406. const bool checkRecursively) const;
  9407. juce_UseDebuggingNewOperator
  9408. private:
  9409. StringArray directories;
  9410. void init (const String& path);
  9411. };
  9412. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  9413. /********* End of inlined file: juce_FileSearchPath.h *********/
  9414. #endif
  9415. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  9416. /********* Start of inlined file: juce_NamedPipe.h *********/
  9417. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  9418. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  9419. /**
  9420. A cross-process pipe that can have data written to and read from it.
  9421. Two or more processes can use these for inter-process communication.
  9422. @see InterprocessConnection
  9423. */
  9424. class JUCE_API NamedPipe
  9425. {
  9426. public:
  9427. /** Creates a NamedPipe. */
  9428. NamedPipe();
  9429. /** Destructor. */
  9430. ~NamedPipe();
  9431. /** Tries to open a pipe that already exists.
  9432. Returns true if it succeeds.
  9433. */
  9434. bool openExisting (const String& pipeName);
  9435. /** Tries to create a new pipe.
  9436. Returns true if it succeeds.
  9437. */
  9438. bool createNewPipe (const String& pipeName);
  9439. /** Closes the pipe, if it's open. */
  9440. void close();
  9441. /** True if the pipe is currently open. */
  9442. bool isOpen() const throw();
  9443. /** Returns the last name that was used to try to open this pipe. */
  9444. const String getName() const throw();
  9445. /** Reads data from the pipe.
  9446. This will block until another thread has written enough data into the pipe to fill
  9447. the number of bytes specified, or until another thread calls the cancelPendingReads()
  9448. method.
  9449. If the operation fails, it returns -1, otherwise, it will return the number of
  9450. bytes read.
  9451. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  9452. this is a maximum timeout for reading from the pipe.
  9453. */
  9454. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  9455. /** Writes some data to the pipe.
  9456. If the operation fails, it returns -1, otherwise, it will return the number of
  9457. bytes written.
  9458. */
  9459. int write (const void* sourceBuffer, int numBytesToWrite,
  9460. int timeOutMilliseconds = 2000);
  9461. /** If any threads are currently blocked on a read operation, this tells them to abort.
  9462. */
  9463. void cancelPendingReads();
  9464. juce_UseDebuggingNewOperator
  9465. private:
  9466. void* internal;
  9467. String currentPipeName;
  9468. NamedPipe (const NamedPipe&);
  9469. const NamedPipe& operator= (const NamedPipe&);
  9470. bool openInternal (const String& pipeName, const bool createPipe);
  9471. };
  9472. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  9473. /********* End of inlined file: juce_NamedPipe.h *********/
  9474. #endif
  9475. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  9476. /********* Start of inlined file: juce_ZipFile.h *********/
  9477. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  9478. #define __JUCE_ZIPFILE_JUCEHEADER__
  9479. /********* Start of inlined file: juce_InputSource.h *********/
  9480. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  9481. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  9482. /**
  9483. A lightweight object that can create a stream to read some kind of resource.
  9484. This may be used to refer to a file, or some other kind of source, allowing a
  9485. caller to create an input stream that can read from it when required.
  9486. @see FileInputSource
  9487. */
  9488. class JUCE_API InputSource
  9489. {
  9490. public:
  9491. InputSource() throw() {}
  9492. /** Destructor. */
  9493. virtual ~InputSource() {}
  9494. /** Returns a new InputStream to read this item.
  9495. @returns an inputstream that the caller will delete, or 0 if
  9496. the filename isn't found.
  9497. */
  9498. virtual InputStream* createInputStream() = 0;
  9499. /** Returns a new InputStream to read an item, relative.
  9500. @param relatedItemPath the relative pathname of the resource that is required
  9501. @returns an inputstream that the caller will delete, or 0 if
  9502. the item isn't found.
  9503. */
  9504. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  9505. /** Returns a hash code that uniquely represents this item.
  9506. */
  9507. virtual int64 hashCode() const = 0;
  9508. juce_UseDebuggingNewOperator
  9509. };
  9510. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  9511. /********* End of inlined file: juce_InputSource.h *********/
  9512. /**
  9513. Decodes a ZIP file from a stream.
  9514. This can enumerate the items in a ZIP file and can create suitable stream objects
  9515. to read each one.
  9516. */
  9517. class JUCE_API ZipFile
  9518. {
  9519. public:
  9520. /** Creates a ZipFile for a given stream.
  9521. @param inputStream the stream to read from
  9522. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  9523. will be deleted when this ZipFile object is deleted
  9524. */
  9525. ZipFile (InputStream* const inputStream,
  9526. const bool deleteStreamWhenDestroyed) throw();
  9527. /** Creates a ZipFile based for a file. */
  9528. ZipFile (const File& file);
  9529. /** Creates a ZipFile for an input source.
  9530. The inputSource object will be owned by the zip file, which will delete
  9531. it later when not needed.
  9532. */
  9533. ZipFile (InputSource* const inputSource);
  9534. /** Destructor. */
  9535. ~ZipFile() throw();
  9536. /**
  9537. Contains information about one of the entries in a ZipFile.
  9538. @see ZipFile::getEntry
  9539. */
  9540. struct ZipEntry
  9541. {
  9542. /** The name of the file, which may also include a partial pathname. */
  9543. String filename;
  9544. /** The file's original size. */
  9545. unsigned int uncompressedSize;
  9546. /** The last time the file was modified. */
  9547. Time fileTime;
  9548. };
  9549. /** Returns the number of items in the zip file. */
  9550. int getNumEntries() const throw();
  9551. /** Returns a structure that describes one of the entries in the zip file.
  9552. This may return zero if the index is out of range.
  9553. @see ZipFile::ZipEntry
  9554. */
  9555. const ZipEntry* getEntry (const int index) const throw();
  9556. /** Returns the index of the first entry with a given filename.
  9557. This uses a case-sensitive comparison to look for a filename in the
  9558. list of entries. It might return -1 if no match is found.
  9559. @see ZipFile::ZipEntry
  9560. */
  9561. int getIndexOfFileName (const String& fileName) const throw();
  9562. /** Returns a structure that describes one of the entries in the zip file.
  9563. This uses a case-sensitive comparison to look for a filename in the
  9564. list of entries. It might return 0 if no match is found.
  9565. @see ZipFile::ZipEntry
  9566. */
  9567. const ZipEntry* getEntry (const String& fileName) const throw();
  9568. /** Sorts the list of entries, based on the filename.
  9569. */
  9570. void sortEntriesByFilename();
  9571. /** Creates a stream that can read from one of the zip file's entries.
  9572. The stream that is returned must be deleted by the caller (and
  9573. zero might be returned if a stream can't be opened for some reason).
  9574. The stream must not be used after the ZipFile object that created
  9575. has been deleted.
  9576. */
  9577. InputStream* createStreamForEntry (const int index);
  9578. /** Uncompresses all of the files in the zip file.
  9579. This will expand all the entires into a target directory. The relative
  9580. paths of the entries are used.
  9581. @param targetDirectory the root folder to uncompress to
  9582. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  9583. */
  9584. void uncompressTo (const File& targetDirectory,
  9585. const bool shouldOverwriteFiles = true);
  9586. juce_UseDebuggingNewOperator
  9587. private:
  9588. VoidArray entries;
  9589. friend class ZipInputStream;
  9590. CriticalSection lock;
  9591. InputStream* inputStream;
  9592. InputSource* inputSource;
  9593. bool deleteStreamWhenDestroyed;
  9594. int numEntries, centralRecStart;
  9595. #ifdef JUCE_DEBUG
  9596. int numOpenStreams;
  9597. #endif
  9598. void init();
  9599. int findEndOfZipEntryTable (InputStream* in);
  9600. ZipFile (const ZipFile&);
  9601. const ZipFile& operator= (const ZipFile&);
  9602. };
  9603. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  9604. /********* End of inlined file: juce_ZipFile.h *********/
  9605. #endif
  9606. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  9607. /********* Start of inlined file: juce_BlowFish.h *********/
  9608. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  9609. #define __JUCE_BLOWFISH_JUCEHEADER__
  9610. /**
  9611. BlowFish encryption class.
  9612. */
  9613. class JUCE_API BlowFish
  9614. {
  9615. public:
  9616. /** Creates an object that can encode/decode based on the specified key.
  9617. The key data can be up to 72 bytes long.
  9618. */
  9619. BlowFish (const uint8* keyData, int keyBytes);
  9620. /** Creates a copy of another blowfish object. */
  9621. BlowFish (const BlowFish& other);
  9622. /** Copies another blowfish object. */
  9623. const BlowFish& operator= (const BlowFish& other);
  9624. /** Destructor. */
  9625. ~BlowFish();
  9626. /** Encrypts a pair of 32-bit integers. */
  9627. void encrypt (uint32& data1, uint32& data2) const;
  9628. /** Decrypts a pair of 32-bit integers. */
  9629. void decrypt (uint32& data1, uint32& data2) const;
  9630. juce_UseDebuggingNewOperator
  9631. private:
  9632. uint32 p[18];
  9633. uint32* s[4];
  9634. uint32 F (uint32 x) const;
  9635. };
  9636. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  9637. /********* End of inlined file: juce_BlowFish.h *********/
  9638. #endif
  9639. #ifndef __JUCE_MD5_JUCEHEADER__
  9640. /********* Start of inlined file: juce_MD5.h *********/
  9641. #ifndef __JUCE_MD5_JUCEHEADER__
  9642. #define __JUCE_MD5_JUCEHEADER__
  9643. /**
  9644. MD5 checksum class.
  9645. Create one of these with a block of source data or a string, and it calculates the
  9646. MD5 checksum of that data.
  9647. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  9648. */
  9649. class JUCE_API MD5
  9650. {
  9651. public:
  9652. /** Creates a null MD5 object. */
  9653. MD5();
  9654. /** Creates a copy of another MD5. */
  9655. MD5 (const MD5& other);
  9656. /** Copies another MD5. */
  9657. const MD5& operator= (const MD5& other);
  9658. /** Creates a checksum for a block of binary data. */
  9659. MD5 (const MemoryBlock& data);
  9660. /** Creates a checksum for a block of binary data. */
  9661. MD5 (const char* data, const int numBytes);
  9662. /** Creates a checksum for a string.
  9663. Note that this operates on the string as a block of unicode characters, so the
  9664. result you get will differ from the value you'd get if the string was treated
  9665. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  9666. of this method with a checksum created by a different framework, which may have
  9667. used a different encoding.
  9668. */
  9669. MD5 (const String& text);
  9670. /** Creates a checksum for the input from a stream.
  9671. This will read up to the given number of bytes from the stream, and produce the
  9672. checksum of that. If the number of bytes to read is negative, it'll read
  9673. until the stream is exhausted.
  9674. */
  9675. MD5 (InputStream& input, int numBytesToRead = -1);
  9676. /** Creates a checksum for a file. */
  9677. MD5 (const File& file);
  9678. /** Destructor. */
  9679. ~MD5();
  9680. /** Returns the checksum as a 16-byte block of data. */
  9681. const MemoryBlock getRawChecksumData() const;
  9682. /** Returns the checksum as a 32-digit hex string. */
  9683. const String toHexString() const;
  9684. /** Compares this to another MD5. */
  9685. bool operator== (const MD5& other) const;
  9686. /** Compares this to another MD5. */
  9687. bool operator!= (const MD5& other) const;
  9688. juce_UseDebuggingNewOperator
  9689. private:
  9690. uint8 result [16];
  9691. struct ProcessContext
  9692. {
  9693. uint8 buffer [64];
  9694. uint32 state [4];
  9695. uint32 count [2];
  9696. ProcessContext();
  9697. void processBlock (const uint8* const data, int dataSize);
  9698. void transform (const uint8* const buffer);
  9699. void finish (uint8* const result);
  9700. };
  9701. void processStream (InputStream& input, int numBytesToRead);
  9702. };
  9703. #endif // __JUCE_MD5_JUCEHEADER__
  9704. /********* End of inlined file: juce_MD5.h *********/
  9705. #endif
  9706. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9707. /********* Start of inlined file: juce_Primes.h *********/
  9708. #ifndef __JUCE_PRIMES_JUCEHEADER__
  9709. #define __JUCE_PRIMES_JUCEHEADER__
  9710. /**
  9711. Prime number creation class.
  9712. This class contains static methods for generating and testing prime numbers.
  9713. @see BitArray
  9714. */
  9715. class JUCE_API Primes
  9716. {
  9717. public:
  9718. /** Creates a random prime number with a given bit-length.
  9719. The certainty parameter specifies how many iterations to use when testing
  9720. for primality. A safe value might be anything over about 20-30.
  9721. The randomSeeds parameter lets you optionally pass it a set of values with
  9722. which to seed the random number generation, improving the security of the
  9723. keys generated.
  9724. */
  9725. static const BitArray createProbablePrime (int bitLength,
  9726. int certainty,
  9727. const int* randomSeeds = 0,
  9728. int numRandomSeeds = 0) throw();
  9729. /** Tests a number to see if it's prime.
  9730. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  9731. whether the number is prime.
  9732. The certainty parameter specifies how many iterations to use when testing - a
  9733. safe value might be anything over about 20-30.
  9734. */
  9735. static bool isProbablyPrime (const BitArray& number,
  9736. int certainty) throw();
  9737. };
  9738. #endif // __JUCE_PRIMES_JUCEHEADER__
  9739. /********* End of inlined file: juce_Primes.h *********/
  9740. #endif
  9741. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9742. /********* Start of inlined file: juce_RSAKey.h *********/
  9743. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  9744. #define __JUCE_RSAKEY_JUCEHEADER__
  9745. /**
  9746. RSA public/private key-pair encryption class.
  9747. An object of this type makes up one half of a public/private RSA key pair. Use the
  9748. createKeyPair() method to create a matching pair for encoding/decoding.
  9749. */
  9750. class JUCE_API RSAKey
  9751. {
  9752. public:
  9753. /** Creates a null key object.
  9754. Initialise a pair of objects for use with the createKeyPair() method.
  9755. */
  9756. RSAKey() throw();
  9757. /** Loads a key from an encoded string representation.
  9758. This reloads a key from a string created by the toString() method.
  9759. */
  9760. RSAKey (const String& stringRepresentation) throw();
  9761. /** Destructor. */
  9762. ~RSAKey() throw();
  9763. /** Turns the key into a string representation.
  9764. This can be reloaded using the constructor that takes a string.
  9765. */
  9766. const String toString() const throw();
  9767. /** Encodes or decodes a value.
  9768. Call this on the public key object to encode some data, then use the matching
  9769. private key object to decode it.
  9770. Returns false if the operation failed, e.g. if this object isn't a valid key.
  9771. */
  9772. bool applyToValue (BitArray& value) const throw();
  9773. /** Creates a public/private key-pair.
  9774. Each key will perform one-way encryption that can only be reversed by
  9775. using the other key.
  9776. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  9777. sizes are more secure, but this method will take longer to execute.
  9778. The randomSeeds parameter lets you optionally pass it a set of values with
  9779. which to seed the random number generation, improving the security of the
  9780. keys generated.
  9781. */
  9782. static void createKeyPair (RSAKey& publicKey,
  9783. RSAKey& privateKey,
  9784. const int numBits,
  9785. const int* randomSeeds = 0,
  9786. const int numRandomSeeds = 0) throw();
  9787. juce_UseDebuggingNewOperator
  9788. protected:
  9789. BitArray part1, part2;
  9790. };
  9791. #endif // __JUCE_RSAKEY_JUCEHEADER__
  9792. /********* End of inlined file: juce_RSAKey.h *********/
  9793. #endif
  9794. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9795. /********* Start of inlined file: juce_Socket.h *********/
  9796. #ifndef __JUCE_SOCKET_JUCEHEADER__
  9797. #define __JUCE_SOCKET_JUCEHEADER__
  9798. /**
  9799. A wrapper for a streaming (TCP) socket.
  9800. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9801. sockets, you could also try the InterprocessConnection class.
  9802. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  9803. */
  9804. class JUCE_API StreamingSocket
  9805. {
  9806. public:
  9807. /** Creates an uninitialised socket.
  9808. To connect it, use the connect() method, after which you can read() or write()
  9809. to it.
  9810. To wait for other sockets to connect to this one, the createListener() method
  9811. enters "listener" mode, and can be used to spawn new sockets for each connection
  9812. that comes along.
  9813. */
  9814. StreamingSocket();
  9815. /** Destructor. */
  9816. ~StreamingSocket();
  9817. /** Binds the socket to the specified local port.
  9818. @returns true on success; false may indicate that another socket is already bound
  9819. on the same port
  9820. */
  9821. bool bindToPort (const int localPortNumber);
  9822. /** Tries to connect the socket to hostname:port.
  9823. If timeOutMillisecs is 0, then this method will block until the operating system
  9824. rejects the connection (which could take a long time).
  9825. @returns true if it succeeds.
  9826. @see isConnected
  9827. */
  9828. bool connect (const String& remoteHostname,
  9829. const int remotePortNumber,
  9830. const int timeOutMillisecs = 3000);
  9831. /** True if the socket is currently connected. */
  9832. bool isConnected() const throw() { return connected; }
  9833. /** Closes the connection. */
  9834. void close();
  9835. /** Returns the name of the currently connected host. */
  9836. const String& getHostName() const throw() { return hostName; }
  9837. /** Returns the port number that's currently open. */
  9838. int getPort() const throw() { return portNumber; }
  9839. /** True if the socket is connected to this machine rather than over the network. */
  9840. bool isLocal() const throw();
  9841. /** Waits until the socket is ready for reading or writing.
  9842. If readyForReading is true, it will wait until the socket is ready for
  9843. reading; if false, it will wait until it's ready for writing.
  9844. If the timeout is < 0, it will wait forever, or else will give up after
  9845. the specified time.
  9846. If the socket is ready on return, this returns 1. If it times-out before
  9847. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9848. */
  9849. int waitUntilReady (const bool readyForReading,
  9850. const int timeoutMsecs) const;
  9851. /** Reads bytes from the socket.
  9852. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  9853. maxBytesToRead bytes have been read, (or until an error occurs). If this
  9854. flag is false, the method will return as much data as is currently available
  9855. without blocking.
  9856. @returns the number of bytes read, or -1 if there was an error.
  9857. @see waitUntilReady
  9858. */
  9859. int read (void* destBuffer, const int maxBytesToRead,
  9860. const bool blockUntilSpecifiedAmountHasArrived);
  9861. /** Writes bytes to the socket from a buffer.
  9862. Note that this method will block unless you have checked the socket is ready
  9863. for writing before calling it (see the waitUntilReady() method).
  9864. @returns the number of bytes written, or -1 if there was an error.
  9865. */
  9866. int write (const void* sourceBuffer, const int numBytesToWrite);
  9867. /** Puts this socket into "listener" mode.
  9868. When in this mode, your thread can call waitForNextConnection() repeatedly,
  9869. which will spawn new sockets for each new connection, so that these can
  9870. be handled in parallel by other threads.
  9871. This returns true if it manages to open the socket successfully.
  9872. @see waitForNextConnection
  9873. */
  9874. bool createListener (const int portNumber);
  9875. /** When in "listener" mode, this waits for a connection and spawns it as a new
  9876. socket.
  9877. The object that gets returned will be owned by the caller.
  9878. This method can only be called after using createListener().
  9879. @see createListener
  9880. */
  9881. StreamingSocket* waitForNextConnection() const;
  9882. juce_UseDebuggingNewOperator
  9883. private:
  9884. String hostName;
  9885. int volatile portNumber, handle;
  9886. bool connected, isListener;
  9887. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  9888. StreamingSocket (const StreamingSocket&);
  9889. const StreamingSocket& operator= (const StreamingSocket&);
  9890. };
  9891. /**
  9892. A wrapper for a datagram (UDP) socket.
  9893. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  9894. sockets, you could also try the InterprocessConnection class.
  9895. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  9896. */
  9897. class JUCE_API DatagramSocket
  9898. {
  9899. public:
  9900. /**
  9901. Creates an (uninitialised) datagram socket.
  9902. The localPortNumber is the port on which to bind this socket. If this value is 0,
  9903. the port number is assigned by the operating system.
  9904. To use the socket for sending, call the connect() method. This will not immediately
  9905. make a connection, but will save the destination you've provided. After this, you can
  9906. call read() or write().
  9907. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  9908. (may require extra privileges on linux)
  9909. To wait for other sockets to connect to this one, call waitForNextConnection().
  9910. */
  9911. DatagramSocket (const int localPortNumber,
  9912. const bool enableBroadcasting = false);
  9913. /** Destructor. */
  9914. ~DatagramSocket();
  9915. /** Binds the socket to the specified local port.
  9916. @returns true on success; false may indicate that another socket is already bound
  9917. on the same port
  9918. */
  9919. bool bindToPort (const int localPortNumber);
  9920. /** Tries to connect the socket to hostname:port.
  9921. If timeOutMillisecs is 0, then this method will block until the operating system
  9922. rejects the connection (which could take a long time).
  9923. @returns true if it succeeds.
  9924. @see isConnected
  9925. */
  9926. bool connect (const String& remoteHostname,
  9927. const int remotePortNumber,
  9928. const int timeOutMillisecs = 3000);
  9929. /** True if the socket is currently connected. */
  9930. bool isConnected() const throw() { return connected; }
  9931. /** Closes the connection. */
  9932. void close();
  9933. /** Returns the name of the currently connected host. */
  9934. const String& getHostName() const throw() { return hostName; }
  9935. /** Returns the port number that's currently open. */
  9936. int getPort() const throw() { return portNumber; }
  9937. /** True if the socket is connected to this machine rather than over the network. */
  9938. bool isLocal() const throw();
  9939. /** Waits until the socket is ready for reading or writing.
  9940. If readyForReading is true, it will wait until the socket is ready for
  9941. reading; if false, it will wait until it's ready for writing.
  9942. If the timeout is < 0, it will wait forever, or else will give up after
  9943. the specified time.
  9944. If the socket is ready on return, this returns 1. If it times-out before
  9945. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  9946. */
  9947. int waitUntilReady (const bool readyForReading,
  9948. const int timeoutMsecs) const;
  9949. /** Reads bytes from the socket.
  9950. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  9951. maxBytesToRead bytes have been read, (or until an error occurs). If this
  9952. flag is false, the method will return as much data as is currently available
  9953. without blocking.
  9954. @returns the number of bytes read, or -1 if there was an error.
  9955. @see waitUntilReady
  9956. */
  9957. int read (void* destBuffer, const int maxBytesToRead,
  9958. const bool blockUntilSpecifiedAmountHasArrived);
  9959. /** Writes bytes to the socket from a buffer.
  9960. Note that this method will block unless you have checked the socket is ready
  9961. for writing before calling it (see the waitUntilReady() method).
  9962. @returns the number of bytes written, or -1 if there was an error.
  9963. */
  9964. int write (const void* sourceBuffer, const int numBytesToWrite);
  9965. /** This waits for incoming data to be sent, and returns a socket that can be used
  9966. to read it.
  9967. The object that gets returned is owned by the caller, and can't be used for
  9968. sending, but can be used to read the data.
  9969. */
  9970. DatagramSocket* waitForNextConnection() const;
  9971. juce_UseDebuggingNewOperator
  9972. private:
  9973. String hostName;
  9974. int volatile portNumber, handle;
  9975. bool connected, allowBroadcast;
  9976. void* serverAddress;
  9977. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  9978. DatagramSocket (const DatagramSocket&);
  9979. const DatagramSocket& operator= (const DatagramSocket&);
  9980. };
  9981. #endif // __JUCE_SOCKET_JUCEHEADER__
  9982. /********* End of inlined file: juce_Socket.h *********/
  9983. #endif
  9984. #ifndef __JUCE_URL_JUCEHEADER__
  9985. /********* Start of inlined file: juce_URL.h *********/
  9986. #ifndef __JUCE_URL_JUCEHEADER__
  9987. #define __JUCE_URL_JUCEHEADER__
  9988. /**
  9989. Represents a URL and has a bunch of useful functions to manipulate it.
  9990. This class can be used to launch URLs in browsers, and also to create
  9991. InputStreams that can read from remote http or ftp sources.
  9992. */
  9993. class JUCE_API URL
  9994. {
  9995. public:
  9996. /** Creates an empty URL. */
  9997. URL() throw();
  9998. /** Creates a URL from a string. */
  9999. URL (const String& url);
  10000. /** Creates a copy of another URL. */
  10001. URL (const URL& other);
  10002. /** Destructor. */
  10003. ~URL() throw();
  10004. /** Copies this URL from another one. */
  10005. const URL& operator= (const URL& other);
  10006. /** Returns a string version of the URL.
  10007. If includeGetParameters is true and any parameters have been set with the
  10008. withParameter() method, then the string will have these appended on the
  10009. end and url-encoded.
  10010. */
  10011. const String toString (const bool includeGetParameters) const;
  10012. /** True if it seems to be valid. */
  10013. bool isWellFormed() const;
  10014. /** Returns just the domain part of the URL.
  10015. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  10016. */
  10017. const String getDomain() const;
  10018. /** Returns the path part of the URL.
  10019. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  10020. */
  10021. const String getSubPath() const;
  10022. /** Returns the scheme of the URL.
  10023. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  10024. include the colon).
  10025. */
  10026. const String getScheme() const;
  10027. /** Returns a new version of this URL that uses a different sub-path.
  10028. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  10029. "bar", it'll return "http://www.xyz.com/bar?x=1".
  10030. */
  10031. const URL withNewSubPath (const String& newPath) const;
  10032. /** Returns a copy of this URL, with a GET parameter added to the end.
  10033. Any control characters in the value will be encoded.
  10034. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  10035. would produce a new url whose toString(true) method would return
  10036. "www.fish.com?amount=some+fish".
  10037. */
  10038. const URL withParameter (const String& parameterName,
  10039. const String& parameterValue) const;
  10040. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  10041. When performing a POST where one of your parameters is a binary file, this
  10042. lets you specify the file.
  10043. Note that the filename is stored, but the file itself won't actually be read
  10044. until this URL is later used to create a network input stream.
  10045. */
  10046. const URL withFileToUpload (const String& parameterName,
  10047. const File& fileToUpload,
  10048. const String& mimeType) const;
  10049. /** Returns a set of all the parameters encoded into the url.
  10050. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  10051. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  10052. The values returned will have been cleaned up to remove any escape characters.
  10053. @see getNamedParameter, withParameter
  10054. */
  10055. const StringPairArray& getParameters() const throw();
  10056. /** Returns the set of files that should be uploaded as part of a POST operation.
  10057. This is the set of files that were added to the URL with the withFileToUpload()
  10058. method.
  10059. */
  10060. const StringPairArray& getFilesToUpload() const throw();
  10061. /** Returns the set of mime types associated with each of the upload files.
  10062. */
  10063. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  10064. /** Returns a copy of this URL, with a block of data to send as the POST data.
  10065. If you're setting the POST data, be careful not to have any parameters set
  10066. as well, otherwise it'll all get thrown in together, and might not have the
  10067. desired effect.
  10068. If the URL already contains some POST data, this will replace it, rather
  10069. than being appended to it.
  10070. This data will only be used if you specify a post operation when you call
  10071. createInputStream().
  10072. */
  10073. const URL withPOSTData (const String& postData) const;
  10074. /** Returns the data that was set using withPOSTData().
  10075. */
  10076. const String getPostData() const throw() { return postData; }
  10077. /** Tries to launch the system's default browser to open the URL.
  10078. Returns true if this seems to have worked.
  10079. */
  10080. bool launchInDefaultBrowser() const;
  10081. /** Takes a guess as to whether a string might be a valid website address.
  10082. This isn't foolproof!
  10083. */
  10084. static bool isProbablyAWebsiteURL (const String& possibleURL);
  10085. /** Takes a guess as to whether a string might be a valid email address.
  10086. This isn't foolproof!
  10087. */
  10088. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  10089. /** This callback function can be used by the createInputStream() method.
  10090. It allows your app to receive progress updates during a lengthy POST operation. If you
  10091. want to continue the operation, this should return true, or false to abort.
  10092. */
  10093. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  10094. /** Attempts to open a stream that can read from this URL.
  10095. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  10096. the paramters, otherwise it'll encode them into the
  10097. URL and do a 'GET'.
  10098. @param progressCallback if this is non-zero, it lets you supply a callback function
  10099. to keep track of the operation's progress. This can be useful
  10100. for lengthy POST operations, so that you can provide user feedback.
  10101. @param progressCallbackContext if a callback is specified, this value will be passed to
  10102. the function
  10103. @param extraHeaders if not empty, this string is appended onto the headers that
  10104. are used for the request. It must therefore be a valid set of HTML
  10105. header directives, separated by newlines.
  10106. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  10107. a negative number, it will be infinite. Otherwise it specifies a
  10108. time in milliseconds.
  10109. */
  10110. InputStream* createInputStream (const bool usePostCommand,
  10111. OpenStreamProgressCallback* const progressCallback = 0,
  10112. void* const progressCallbackContext = 0,
  10113. const String& extraHeaders = String::empty,
  10114. const int connectionTimeOutMs = 0) const;
  10115. /** Tries to download the entire contents of this URL into a binary data block.
  10116. If it succeeds, this will return true and append the data it read onto the end
  10117. of the memory block.
  10118. @param destData the memory block to append the new data to
  10119. @param usePostCommand whether to use a POST command to get the data (uses
  10120. a GET command if this is false)
  10121. @see readEntireTextStream, readEntireXmlStream
  10122. */
  10123. bool readEntireBinaryStream (MemoryBlock& destData,
  10124. const bool usePostCommand = false) const;
  10125. /** Tries to download the entire contents of this URL as a string.
  10126. If it fails, this will return an empty string, otherwise it will return the
  10127. contents of the downloaded file. If you need to distinguish between a read
  10128. operation that fails and one that returns an empty string, you'll need to use
  10129. a different method, such as readEntireBinaryStream().
  10130. @param usePostCommand whether to use a POST command to get the data (uses
  10131. a GET command if this is false)
  10132. @see readEntireBinaryStream, readEntireXmlStream
  10133. */
  10134. const String readEntireTextStream (const bool usePostCommand = false) const;
  10135. /** Tries to download the entire contents of this URL and parse it as XML.
  10136. If it fails, or if the text that it reads can't be parsed as XML, this will
  10137. return 0.
  10138. When it returns a valid XmlElement object, the caller is responsibile for deleting
  10139. this object when no longer needed.
  10140. @param usePostCommand whether to use a POST command to get the data (uses
  10141. a GET command if this is false)
  10142. @see readEntireBinaryStream, readEntireTextStream
  10143. */
  10144. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  10145. /** Adds escape sequences to a string to encode any characters that aren't
  10146. legal in a URL.
  10147. E.g. any spaces will be replaced with "%20".
  10148. This is the opposite of removeEscapeChars().
  10149. If isParameter is true, it means that the string is going to be used
  10150. as a parameter, so it also encodes '$' and ',' (which would otherwise
  10151. be legal in a URL.
  10152. @see removeEscapeChars
  10153. */
  10154. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  10155. const bool isParameter);
  10156. /** Replaces any escape character sequences in a string with their original
  10157. character codes.
  10158. E.g. any instances of "%20" will be replaced by a space.
  10159. This is the opposite of addEscapeChars().
  10160. @see addEscapeChars
  10161. */
  10162. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  10163. juce_UseDebuggingNewOperator
  10164. private:
  10165. String url, postData;
  10166. StringPairArray parameters, filesToUpload, mimeTypes;
  10167. };
  10168. #endif // __JUCE_URL_JUCEHEADER__
  10169. /********* End of inlined file: juce_URL.h *********/
  10170. #endif
  10171. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10172. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  10173. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10174. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10175. /** Wraps another input stream, and reads from it using an intermediate buffer
  10176. If you're using an input stream such as a file input stream, and making lots of
  10177. small read accesses to it, it's probably sensible to wrap it in one of these,
  10178. so that the source stream gets accessed in larger chunk sizes, meaning less
  10179. work for the underlying stream.
  10180. */
  10181. class JUCE_API BufferedInputStream : public InputStream
  10182. {
  10183. public:
  10184. /** Creates a BufferedInputStream from an input source.
  10185. @param sourceStream the source stream to read from
  10186. @param bufferSize the size of reservoir to use to buffer the source
  10187. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  10188. deleted by this object when it is itself deleted.
  10189. */
  10190. BufferedInputStream (InputStream* const sourceStream,
  10191. const int bufferSize,
  10192. const bool deleteSourceWhenDestroyed) throw();
  10193. /** Destructor.
  10194. This may also delete the source stream, if that option was chosen when the
  10195. buffered stream was created.
  10196. */
  10197. ~BufferedInputStream() throw();
  10198. int64 getTotalLength();
  10199. int64 getPosition();
  10200. bool setPosition (int64 newPosition);
  10201. int read (void* destBuffer, int maxBytesToRead);
  10202. const String readString();
  10203. bool isExhausted();
  10204. juce_UseDebuggingNewOperator
  10205. private:
  10206. InputStream* const source;
  10207. const bool deleteSourceWhenDestroyed;
  10208. int bufferSize;
  10209. int64 position, lastReadPos, bufferStart, bufferOverlap;
  10210. char* buffer;
  10211. void ensureBuffered();
  10212. BufferedInputStream (const BufferedInputStream&);
  10213. const BufferedInputStream& operator= (const BufferedInputStream&);
  10214. };
  10215. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  10216. /********* End of inlined file: juce_BufferedInputStream.h *********/
  10217. #endif
  10218. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  10219. /********* Start of inlined file: juce_FileInputSource.h *********/
  10220. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  10221. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  10222. /**
  10223. A type of InputSource that represents a normal file.
  10224. @see InputSource
  10225. */
  10226. class JUCE_API FileInputSource : public InputSource
  10227. {
  10228. public:
  10229. FileInputSource (const File& file) throw();
  10230. ~FileInputSource();
  10231. InputStream* createInputStream();
  10232. InputStream* createInputStreamFor (const String& relatedItemPath);
  10233. int64 hashCode() const;
  10234. juce_UseDebuggingNewOperator
  10235. private:
  10236. const File file;
  10237. FileInputSource (const FileInputSource&);
  10238. const FileInputSource& operator= (const FileInputSource&);
  10239. };
  10240. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  10241. /********* End of inlined file: juce_FileInputSource.h *********/
  10242. #endif
  10243. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  10244. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  10245. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  10246. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  10247. /**
  10248. A stream which uses zlib to compress the data written into it.
  10249. @see GZIPDecompressorInputStream
  10250. */
  10251. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  10252. {
  10253. public:
  10254. /** Creates a compression stream.
  10255. @param destStream the stream into which the compressed data should
  10256. be written
  10257. @param compressionLevel how much to compress the data, between 1 and 9, where
  10258. 1 is the fastest/lowest compression, and 9 is the
  10259. slowest/highest compression. Any value outside this range
  10260. indicates that a default compression level should be used.
  10261. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  10262. this stream is destroyed
  10263. @param noWrap this is used internally by the ZipFile class
  10264. and should be ignored by user applications
  10265. */
  10266. GZIPCompressorOutputStream (OutputStream* const destStream,
  10267. int compressionLevel = 0,
  10268. const bool deleteDestStreamWhenDestroyed = false,
  10269. const bool noWrap = false);
  10270. /** Destructor. */
  10271. ~GZIPCompressorOutputStream();
  10272. void flush();
  10273. int64 getPosition();
  10274. bool setPosition (int64 newPosition);
  10275. bool write (const void* destBuffer, int howMany);
  10276. juce_UseDebuggingNewOperator
  10277. private:
  10278. OutputStream* const destStream;
  10279. const bool deleteDestStream;
  10280. uint8* buffer;
  10281. void* helper;
  10282. bool doNextBlock();
  10283. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  10284. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  10285. };
  10286. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  10287. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  10288. #endif
  10289. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  10290. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  10291. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  10292. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  10293. /**
  10294. This stream will decompress a source-stream using zlib.
  10295. Tip: if you're reading lots of small items from one of these streams, you
  10296. can increase the performance enormously by passing it through a
  10297. BufferedInputStream, so that it has to read larger blocks less often.
  10298. @see GZIPCompressorOutputStream
  10299. */
  10300. class JUCE_API GZIPDecompressorInputStream : public InputStream
  10301. {
  10302. public:
  10303. /** Creates a decompressor stream.
  10304. @param sourceStream the stream to read from
  10305. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  10306. when this object is destroyed
  10307. @param noWrap this is used internally by the ZipFile class
  10308. and should be ignored by user applications
  10309. @param uncompressedStreamLength if the creator knows the length that the
  10310. uncompressed stream will be, then it can supply this
  10311. value, which will be returned by getTotalLength()
  10312. */
  10313. GZIPDecompressorInputStream (InputStream* const sourceStream,
  10314. const bool deleteSourceWhenDestroyed,
  10315. const bool noWrap = false,
  10316. const int64 uncompressedStreamLength = -1);
  10317. /** Destructor. */
  10318. ~GZIPDecompressorInputStream();
  10319. int64 getPosition();
  10320. bool setPosition (int64 pos);
  10321. int64 getTotalLength();
  10322. bool isExhausted();
  10323. int read (void* destBuffer, int maxBytesToRead);
  10324. juce_UseDebuggingNewOperator
  10325. private:
  10326. InputStream* const sourceStream;
  10327. const int64 uncompressedStreamLength;
  10328. const bool deleteSourceWhenDestroyed, noWrap;
  10329. bool isEof;
  10330. int activeBufferSize;
  10331. int64 originalSourcePos, currentPos;
  10332. uint8* buffer;
  10333. void* helper;
  10334. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  10335. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  10336. };
  10337. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  10338. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  10339. #endif
  10340. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  10341. #endif
  10342. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  10343. #endif
  10344. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  10345. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  10346. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  10347. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  10348. /**
  10349. Allows a block of data and to be accessed as a stream.
  10350. This can either be used to refer to a shared block of memory, or can make its
  10351. own internal copy of the data when the MemoryInputStream is created.
  10352. */
  10353. class JUCE_API MemoryInputStream : public InputStream
  10354. {
  10355. public:
  10356. /** Creates a MemoryInputStream.
  10357. @param sourceData the block of data to use as the stream's source
  10358. @param sourceDataSize the number of bytes in the source data block
  10359. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  10360. the source data, so this data shouldn't be changed
  10361. for the lifetime of the stream; if this parameter is
  10362. true, the stream will make its own copy of the
  10363. data and use that.
  10364. */
  10365. MemoryInputStream (const void* const sourceData,
  10366. const int sourceDataSize,
  10367. const bool keepInternalCopyOfData) throw();
  10368. /** Destructor. */
  10369. ~MemoryInputStream() throw();
  10370. int64 getPosition();
  10371. bool setPosition (int64 pos);
  10372. int64 getTotalLength();
  10373. bool isExhausted();
  10374. int read (void* destBuffer, int maxBytesToRead);
  10375. juce_UseDebuggingNewOperator
  10376. private:
  10377. const char* data;
  10378. int dataSize, position;
  10379. MemoryBlock internalCopy;
  10380. };
  10381. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  10382. /********* End of inlined file: juce_MemoryInputStream.h *********/
  10383. #endif
  10384. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  10385. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  10386. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  10387. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  10388. /** Writes data to an internal memory buffer, which grows as required.
  10389. The data that was written into the stream can then be accessed later as
  10390. a contiguous block of memory.
  10391. */
  10392. class JUCE_API MemoryOutputStream : public OutputStream
  10393. {
  10394. public:
  10395. /** Creates a memory stream ready for writing into.
  10396. @param initialSize the intial amount of space to allocate for writing into
  10397. @param granularity the increments by which the internal storage will be increased
  10398. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  10399. place that the data gets stored. If it's zero, the stream
  10400. will allocate its own storage internally, which you can
  10401. access using getData() and getDataSize()
  10402. */
  10403. MemoryOutputStream (const int initialSize = 256,
  10404. const int granularity = 256,
  10405. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  10406. /** Destructor.
  10407. This will free any data that was written to it.
  10408. */
  10409. ~MemoryOutputStream() throw();
  10410. /** Returns a pointer to the data that has been written to the stream.
  10411. @see getDataSize
  10412. */
  10413. const char* getData() throw();
  10414. /** Returns the number of bytes of data that have been written to the stream.
  10415. @see getData
  10416. */
  10417. int getDataSize() const throw();
  10418. /** Resets the stream, clearing any data that has been written to it so far. */
  10419. void reset() throw();
  10420. void flush();
  10421. bool write (const void* buffer, int howMany);
  10422. int64 getPosition();
  10423. bool setPosition (int64 newPosition);
  10424. juce_UseDebuggingNewOperator
  10425. private:
  10426. MemoryBlock* data;
  10427. int position, size, blockSize;
  10428. bool ownsMemoryBlock;
  10429. };
  10430. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  10431. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  10432. #endif
  10433. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  10434. #endif
  10435. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  10436. /********* Start of inlined file: juce_SubregionStream.h *********/
  10437. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  10438. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  10439. /** Wraps another input stream, and reads from a specific part of it.
  10440. This lets you take a subsection of a stream and present it as an entire
  10441. stream in its own right.
  10442. */
  10443. class JUCE_API SubregionStream : public InputStream
  10444. {
  10445. public:
  10446. /** Creates a SubregionStream from an input source.
  10447. @param sourceStream the source stream to read from
  10448. @param startPositionInSourceStream this is the position in the source stream that
  10449. corresponds to position 0 in this stream
  10450. @param lengthOfSourceStream this specifies the maximum number of bytes
  10451. from the source stream that will be passed through
  10452. by this stream. When the position of this stream
  10453. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  10454. If the length passed in here is greater than the length
  10455. of the source stream (as returned by getTotalLength()),
  10456. then the smaller value will be used.
  10457. Passing a negative value for this parameter means it
  10458. will keep reading until the source's end-of-stream.
  10459. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  10460. deleted by this object when it is itself deleted.
  10461. */
  10462. SubregionStream (InputStream* const sourceStream,
  10463. const int64 startPositionInSourceStream,
  10464. const int64 lengthOfSourceStream,
  10465. const bool deleteSourceWhenDestroyed) throw();
  10466. /** Destructor.
  10467. This may also delete the source stream, if that option was chosen when the
  10468. buffered stream was created.
  10469. */
  10470. ~SubregionStream() throw();
  10471. int64 getTotalLength();
  10472. int64 getPosition();
  10473. bool setPosition (int64 newPosition);
  10474. int read (void* destBuffer, int maxBytesToRead);
  10475. bool isExhausted();
  10476. juce_UseDebuggingNewOperator
  10477. private:
  10478. InputStream* const source;
  10479. const bool deleteSourceWhenDestroyed;
  10480. const int64 startPositionInSourceStream, lengthOfSourceStream;
  10481. SubregionStream (const SubregionStream&);
  10482. const SubregionStream& operator= (const SubregionStream&);
  10483. };
  10484. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  10485. /********* End of inlined file: juce_SubregionStream.h *********/
  10486. #endif
  10487. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  10488. #endif
  10489. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10490. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  10491. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10492. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10493. /** Used in the same way as the T(text) macro, this will attempt to translate a
  10494. string into a localised version using the LocalisedStrings class.
  10495. @see LocalisedStrings
  10496. */
  10497. #define TRANS(stringLiteral) \
  10498. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  10499. /**
  10500. Used to convert strings to localised foreign-language versions.
  10501. This is basically a look-up table of strings and their translated equivalents.
  10502. It can be loaded from a text file, so that you can supply a set of localised
  10503. versions of strings that you use in your app.
  10504. To use it in your code, simply call the translate() method on each string that
  10505. might have foreign versions, and if none is found, the method will just return
  10506. the original string.
  10507. The translation file should start with some lines specifying a description of
  10508. the language it contains, and also a list of ISO country codes where it might
  10509. be appropriate to use the file. After that, each line of the file should contain
  10510. a pair of quoted strings with an '=' sign.
  10511. E.g. for a french translation, the file might be:
  10512. @code
  10513. language: French
  10514. countries: fr be mc ch lu
  10515. "hello" = "bonjour"
  10516. "goodbye" = "au revoir"
  10517. @endcode
  10518. If the strings need to contain a quote character, they can use '\"' instead, and
  10519. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  10520. (you can use this to add comments).
  10521. Note that this is a singleton class, so don't create or destroy the object directly.
  10522. There's also a TRANS(text) macro defined to make it easy to use the this.
  10523. E.g. @code
  10524. printSomething (TRANS("hello"));
  10525. @endcode
  10526. This macro is used in the Juce classes themselves, so your application has a chance to
  10527. intercept and translate any internal Juce text strings that might be shown. (You can easily
  10528. get a list of all the messages by searching for the TRANS() macro in the Juce source
  10529. code).
  10530. */
  10531. class JUCE_API LocalisedStrings
  10532. {
  10533. public:
  10534. /** Creates a set of translations from the text of a translation file.
  10535. When you create one of these, you can call setCurrentMappings() to make it
  10536. the set of mappings that the system's using.
  10537. */
  10538. LocalisedStrings (const String& fileContents) throw();
  10539. /** Creates a set of translations from a file.
  10540. When you create one of these, you can call setCurrentMappings() to make it
  10541. the set of mappings that the system's using.
  10542. */
  10543. LocalisedStrings (const File& fileToLoad) throw();
  10544. /** Destructor. */
  10545. ~LocalisedStrings() throw();
  10546. /** Selects the current set of mappings to be used by the system.
  10547. The object you pass in will be automatically deleted when no longer needed, so
  10548. don't keep a pointer to it. You can also pass in zero to remove the current
  10549. mappings.
  10550. See also the TRANS() macro, which uses the current set to do its translation.
  10551. @see translateWithCurrentMappings
  10552. */
  10553. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  10554. /** Returns the currently selected set of mappings.
  10555. This is the object that was last passed to setCurrentMappings(). It may
  10556. be 0 if none has been created.
  10557. */
  10558. static LocalisedStrings* getCurrentMappings() throw();
  10559. /** Tries to translate a string using the currently selected set of mappings.
  10560. If no mapping has been set, or if the mapping doesn't contain a translation
  10561. for the string, this will just return the original string.
  10562. See also the TRANS() macro, which uses this method to do its translation.
  10563. @see setCurrentMappings, getCurrentMappings
  10564. */
  10565. static const String translateWithCurrentMappings (const String& text) throw();
  10566. /** Tries to translate a string using the currently selected set of mappings.
  10567. If no mapping has been set, or if the mapping doesn't contain a translation
  10568. for the string, this will just return the original string.
  10569. See also the TRANS() macro, which uses this method to do its translation.
  10570. @see setCurrentMappings, getCurrentMappings
  10571. */
  10572. static const String translateWithCurrentMappings (const char* text) throw();
  10573. /** Attempts to look up a string and return its localised version.
  10574. If the string isn't found in the list, the original string will be returned.
  10575. */
  10576. const String translate (const String& text) const throw();
  10577. /** Returns the name of the language specified in the translation file.
  10578. This is specified in the file using a line starting with "language:", e.g.
  10579. @code
  10580. language: german
  10581. @endcode
  10582. */
  10583. const String getLanguageName() const throw() { return languageName; }
  10584. /** Returns the list of suitable country codes listed in the translation file.
  10585. These is specified in the file using a line starting with "countries:", e.g.
  10586. @code
  10587. countries: fr be mc ch lu
  10588. @endcode
  10589. The country codes are supposed to be 2-character ISO complient codes.
  10590. */
  10591. const StringArray getCountryCodes() const throw() { return countryCodes; }
  10592. /** Indicates whether to use a case-insensitive search when looking up a string.
  10593. This defaults to true.
  10594. */
  10595. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  10596. juce_UseDebuggingNewOperator
  10597. private:
  10598. String languageName;
  10599. StringArray countryCodes;
  10600. StringPairArray translations;
  10601. void loadFromText (const String& fileContents) throw();
  10602. };
  10603. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  10604. /********* End of inlined file: juce_LocalisedStrings.h *********/
  10605. #endif
  10606. #ifndef __JUCE_STRING_JUCEHEADER__
  10607. #endif
  10608. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  10609. #endif
  10610. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  10611. #endif
  10612. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10613. /********* Start of inlined file: juce_XmlDocument.h *********/
  10614. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  10615. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  10616. /**
  10617. Parses a text-based XML document and creates an XmlElement object from it.
  10618. The parser will parse DTDs to load external entities but won't
  10619. check the document for validity against the DTD.
  10620. e.g.
  10621. @code
  10622. XmlDocument myDocument (File ("myfile.xml"));
  10623. XmlElement* mainElement = myDocument.getDocumentElement();
  10624. if (mainElement == 0)
  10625. {
  10626. String error = myDocument.getLastParseError();
  10627. }
  10628. else
  10629. {
  10630. ..use the element
  10631. }
  10632. @endcode
  10633. @see XmlElement
  10634. */
  10635. class JUCE_API XmlDocument
  10636. {
  10637. public:
  10638. /** Creates an XmlDocument from the xml text.
  10639. The text doesn't actually get parsed until the getDocumentElement() method is
  10640. called.
  10641. */
  10642. XmlDocument (const String& documentText) throw();
  10643. /** Creates an XmlDocument from a file.
  10644. The text doesn't actually get parsed until the getDocumentElement() method is
  10645. called.
  10646. */
  10647. XmlDocument (const File& file);
  10648. /** Destructor. */
  10649. ~XmlDocument() throw();
  10650. /** Creates an XmlElement object to represent the main document node.
  10651. This method will do the actual parsing of the text, and if there's a
  10652. parse error, it may returns 0 (and you can find out the error using
  10653. the getLastParseError() method).
  10654. @param onlyReadOuterDocumentElement if true, the parser will only read the
  10655. first section of the file, and will only
  10656. return the outer document element - this
  10657. allows quick checking of large files to
  10658. see if they contain the correct type of
  10659. tag, without having to parse the entire file
  10660. @returns a new XmlElement which the caller will need to delete, or null if
  10661. there was an error.
  10662. @see getLastParseError
  10663. */
  10664. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  10665. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  10666. @returns the error, or an empty string if there was no error.
  10667. */
  10668. const String& getLastParseError() const throw();
  10669. /** Sets an input source object to use for parsing documents that reference external entities.
  10670. If the document has been created from a file, this probably won't be needed, but
  10671. if you're parsing some text and there might be a DTD that references external
  10672. files, you may need to create a custom input source that can retrieve the
  10673. other files it needs.
  10674. The object that is passed-in will be deleted automatically when no longer needed.
  10675. @see InputSource
  10676. */
  10677. void setInputSource (InputSource* const newSource) throw();
  10678. /** Sets a flag to change the treatment of empty text elements.
  10679. If this is true (the default state), then any text elements that contain only
  10680. whitespace characters will be ingored during parsing. If you need to catch
  10681. whitespace-only text, then you should set this to false before calling the
  10682. getDocumentElement() method.
  10683. */
  10684. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  10685. juce_UseDebuggingNewOperator
  10686. private:
  10687. String originalText;
  10688. const tchar* input;
  10689. bool outOfData, errorOccurred;
  10690. bool identifierLookupTable [128];
  10691. String lastError, dtdText;
  10692. StringArray tokenisedDTD;
  10693. bool needToLoadDTD, ignoreEmptyTextElements;
  10694. InputSource* inputSource;
  10695. void setLastError (const String& desc, const bool carryOn) throw();
  10696. void skipHeader() throw();
  10697. void skipNextWhiteSpace() throw();
  10698. tchar readNextChar() throw();
  10699. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  10700. void readChildElements (XmlElement* parent) throw();
  10701. int findNextTokenLength() throw();
  10702. void readQuotedString (String& result) throw();
  10703. void readEntity (String& result) throw();
  10704. const String getFileContents (const String& filename) const;
  10705. const String expandEntity (const String& entity);
  10706. const String expandExternalEntity (const String& entity);
  10707. const String getParameterEntity (const String& entity);
  10708. };
  10709. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  10710. /********* End of inlined file: juce_XmlDocument.h *********/
  10711. #endif
  10712. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  10713. #endif
  10714. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  10715. #endif
  10716. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10717. /********* Start of inlined file: juce_InterProcessLock.h *********/
  10718. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10719. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10720. /**
  10721. Acts as a critical section which processes can use to block each other.
  10722. @see CriticalSection
  10723. */
  10724. class JUCE_API InterProcessLock
  10725. {
  10726. public:
  10727. /** Creates a lock object.
  10728. @param name a name that processes will use to identify this lock object
  10729. */
  10730. InterProcessLock (const String& name) throw();
  10731. /** Destructor.
  10732. This will also release the lock if it's currently held by this process.
  10733. */
  10734. ~InterProcessLock() throw();
  10735. /** Attempts to lock the critical section.
  10736. @param timeOutMillisecs how many milliseconds to wait if the lock
  10737. is already held by another process - a value of
  10738. 0 will return immediately, negative values will wait
  10739. forever
  10740. @returns true if the lock could be gained within the timeout period, or
  10741. false if the timeout expired.
  10742. */
  10743. bool enter (int timeOutMillisecs = -1) throw();
  10744. /** Releases the lock if it's currently held by this process.
  10745. */
  10746. void exit() throw();
  10747. juce_UseDebuggingNewOperator
  10748. private:
  10749. void* internal;
  10750. String name;
  10751. int reentrancyLevel;
  10752. InterProcessLock (const InterProcessLock&);
  10753. const InterProcessLock& operator= (const InterProcessLock&);
  10754. };
  10755. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  10756. /********* End of inlined file: juce_InterProcessLock.h *********/
  10757. #endif
  10758. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10759. /********* Start of inlined file: juce_Process.h *********/
  10760. #ifndef __JUCE_PROCESS_JUCEHEADER__
  10761. #define __JUCE_PROCESS_JUCEHEADER__
  10762. /** Represents the current executable's process.
  10763. This contains methods for controlling the current application at the
  10764. process-level.
  10765. @see Thread, JUCEApplication
  10766. */
  10767. class JUCE_API Process
  10768. {
  10769. public:
  10770. enum ProcessPriority
  10771. {
  10772. LowPriority = 0,
  10773. NormalPriority = 1,
  10774. HighPriority = 2,
  10775. RealtimePriority = 3
  10776. };
  10777. /** Changes the current process's priority.
  10778. @param priority the process priority, where
  10779. 0=low, 1=normal, 2=high, 3=realtime
  10780. */
  10781. static void setPriority (const ProcessPriority priority);
  10782. /** Kills the current process immediately.
  10783. This is an emergency process terminator that kills the application
  10784. immediately - it's intended only for use only when something goes
  10785. horribly wrong.
  10786. @see JUCEApplication::quit
  10787. */
  10788. static void terminate();
  10789. /** Returns true if this application process is the one that the user is
  10790. currently using.
  10791. */
  10792. static bool isForegroundProcess() throw();
  10793. /** Raises the current process's privilege level.
  10794. Does nothing if this isn't supported by the current OS, or if process
  10795. privilege level is fixed.
  10796. */
  10797. static void raisePrivilege();
  10798. /** Lowers the current process's privilege level.
  10799. Does nothing if this isn't supported by the current OS, or if process
  10800. privilege level is fixed.
  10801. */
  10802. static void lowerPrivilege();
  10803. /** Returns true if this process is being hosted by a debugger.
  10804. */
  10805. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  10806. };
  10807. #endif // __JUCE_PROCESS_JUCEHEADER__
  10808. /********* End of inlined file: juce_Process.h *********/
  10809. #endif
  10810. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10811. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  10812. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  10813. #define __JUCE_READWRITELOCK_JUCEHEADER__
  10814. /********* Start of inlined file: juce_WaitableEvent.h *********/
  10815. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  10816. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  10817. /**
  10818. Allows threads to wait for events triggered by other threads.
  10819. A thread can call wait() on a WaitableObject, and this will suspend the
  10820. calling thread until another thread wakes it up by calling the signal()
  10821. method.
  10822. */
  10823. class JUCE_API WaitableEvent
  10824. {
  10825. public:
  10826. /** Creates a WaitableEvent object. */
  10827. WaitableEvent() throw();
  10828. /** Destructor.
  10829. If other threads are waiting on this object when it gets deleted, this
  10830. can cause nasty errors, so be careful!
  10831. */
  10832. ~WaitableEvent() throw();
  10833. /** Suspends the calling thread until the event has been signalled.
  10834. This will wait until the object's signal() method is called by another thread,
  10835. or until the timeout expires.
  10836. After the event has been signalled, this method will return true and reset
  10837. the event.
  10838. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  10839. value will cause it to wait forever.
  10840. @returns true if the object has been signalled, false if the timeout expires first.
  10841. @see signal, reset
  10842. */
  10843. bool wait (const int timeOutMilliseconds = -1) const throw();
  10844. /** Wakes up any threads that are currently waiting on this object.
  10845. If signal() is called when nothing is waiting, the next thread to call wait()
  10846. will return immediately and reset the signal.
  10847. @see wait, reset
  10848. */
  10849. void signal() const throw();
  10850. /** Resets the event to an unsignalled state.
  10851. If it's not already signalled, this does nothing.
  10852. */
  10853. void reset() const throw();
  10854. juce_UseDebuggingNewOperator
  10855. private:
  10856. void* internal;
  10857. WaitableEvent (const WaitableEvent&);
  10858. const WaitableEvent& operator= (const WaitableEvent&);
  10859. };
  10860. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  10861. /********* End of inlined file: juce_WaitableEvent.h *********/
  10862. /********* Start of inlined file: juce_Thread.h *********/
  10863. #ifndef __JUCE_THREAD_JUCEHEADER__
  10864. #define __JUCE_THREAD_JUCEHEADER__
  10865. /**
  10866. Encapsulates a thread.
  10867. Subclasses derive from Thread and implement the run() method, in which they
  10868. do their business. The thread can then be started with the startThread() method
  10869. and controlled with various other methods.
  10870. This class also contains some thread-related static methods, such
  10871. as sleep(), yield(), getCurrentThreadId() etc.
  10872. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  10873. MessageManagerLock
  10874. */
  10875. class JUCE_API Thread
  10876. {
  10877. public:
  10878. /**
  10879. Creates a thread.
  10880. When first created, the thread is not running. Use the startThread()
  10881. method to start it.
  10882. */
  10883. Thread (const String& threadName);
  10884. /** Destructor.
  10885. Deleting a Thread object that is running will only give the thread a
  10886. brief opportunity to stop itself cleanly, so it's recommended that you
  10887. should always call stopThread() with a decent timeout before deleting,
  10888. to avoid the thread being forcibly killed (which is a Bad Thing).
  10889. */
  10890. virtual ~Thread();
  10891. /** Must be implemented to perform the thread's actual code.
  10892. Remember that the thread must regularly check the threadShouldExit()
  10893. method whilst running, and if this returns true it should return from
  10894. the run() method as soon as possible to avoid being forcibly killed.
  10895. @see threadShouldExit, startThread
  10896. */
  10897. virtual void run() = 0;
  10898. // Thread control functions..
  10899. /** Starts the thread running.
  10900. This will start the thread's run() method.
  10901. (if it's already started, startThread() won't do anything).
  10902. @see stopThread
  10903. */
  10904. void startThread() throw();
  10905. /** Starts the thread with a given priority.
  10906. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  10907. If the thread is already running, its priority will be changed.
  10908. @see startThread, setPriority
  10909. */
  10910. void startThread (const int priority) throw();
  10911. /** Attempts to stop the thread running.
  10912. This method will cause the threadShouldExit() method to return true
  10913. and call notify() in case the thread is currently waiting.
  10914. Hopefully the thread will then respond to this by exiting cleanly, and
  10915. the stopThread method will wait for a given time-period for this to
  10916. happen.
  10917. If the thread is stuck and fails to respond after the time-out, it gets
  10918. forcibly killed, which is a very bad thing to happen, as it could still
  10919. be holding locks, etc. which are needed by other parts of your program.
  10920. @param timeOutMilliseconds The number of milliseconds to wait for the
  10921. thread to finish before killing it by force. A negative
  10922. value in here will wait forever.
  10923. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  10924. */
  10925. void stopThread (const int timeOutMilliseconds) throw();
  10926. /** Returns true if the thread is currently active */
  10927. bool isThreadRunning() const throw();
  10928. /** Sets a flag to tell the thread it should stop.
  10929. Calling this means that the threadShouldExit() method will then return true.
  10930. The thread should be regularly checking this to see whether it should exit.
  10931. @see threadShouldExit
  10932. @see waitForThreadToExit
  10933. */
  10934. void signalThreadShouldExit() throw();
  10935. /** Checks whether the thread has been told to stop running.
  10936. Threads need to check this regularly, and if it returns true, they should
  10937. return from their run() method at the first possible opportunity.
  10938. @see signalThreadShouldExit
  10939. */
  10940. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  10941. /** Waits for the thread to stop.
  10942. This will waits until isThreadRunning() is false or until a timeout expires.
  10943. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  10944. is less than zero, it will wait forever.
  10945. @returns true if the thread exits, or false if the timeout expires first.
  10946. */
  10947. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  10948. /** Changes the thread's priority.
  10949. May return false if for some reason the priority can't be changed.
  10950. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  10951. of 5 is normal.
  10952. */
  10953. bool setPriority (const int priority) throw();
  10954. /** Changes the priority of the caller thread.
  10955. Similar to setPriority(), but this static method acts on the caller thread.
  10956. May return false if for some reason the priority can't be changed.
  10957. @see setPriority
  10958. */
  10959. static bool setCurrentThreadPriority (const int priority) throw();
  10960. /** Sets the affinity mask for the thread.
  10961. This will only have an effect next time the thread is started - i.e. if the
  10962. thread is already running when called, it'll have no effect.
  10963. @see setCurrentThreadAffinityMask
  10964. */
  10965. void setAffinityMask (const uint32 affinityMask) throw();
  10966. /** Changes the affinity mask for the caller thread.
  10967. This will change the affinity mask for the thread that calls this static method.
  10968. @see setAffinityMask
  10969. */
  10970. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  10971. // this can be called from any thread that needs to pause..
  10972. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  10973. /** Yields the calling thread's current time-slot. */
  10974. static void JUCE_CALLTYPE yield() throw();
  10975. /** Makes the thread wait for a notification.
  10976. This puts the thread to sleep until either the timeout period expires, or
  10977. another thread calls the notify() method to wake it up.
  10978. @returns true if the event has been signalled, false if the timeout expires.
  10979. */
  10980. bool wait (const int timeOutMilliseconds) const throw();
  10981. /** Wakes up the thread.
  10982. If the thread has called the wait() method, this will wake it up.
  10983. @see wait
  10984. */
  10985. void notify() const throw();
  10986. /** A value type used for thread IDs.
  10987. @see getCurrentThreadId(), getThreadId()
  10988. */
  10989. typedef void* ThreadID;
  10990. /** Returns an id that identifies the caller thread.
  10991. To find the ID of a particular thread object, use getThreadId().
  10992. @returns a unique identifier that identifies the calling thread.
  10993. @see getThreadId
  10994. */
  10995. static ThreadID getCurrentThreadId() throw();
  10996. /** Finds the thread object that is currently running.
  10997. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  10998. object associated with them, so this will return 0.
  10999. */
  11000. static Thread* getCurrentThread() throw();
  11001. /** Returns the ID of this thread.
  11002. That means the ID of this thread object - not of the thread that's calling the method.
  11003. This can change when the thread is started and stopped, and will be invalid if the
  11004. thread's not actually running.
  11005. @see getCurrentThreadId
  11006. */
  11007. ThreadID getThreadId() const throw();
  11008. /** Returns the name of the thread.
  11009. This is the name that gets set in the constructor.
  11010. */
  11011. const String getThreadName() const throw() { return threadName_; }
  11012. /** Returns the number of currently-running threads.
  11013. @returns the number of Thread objects known to be currently running.
  11014. @see stopAllThreads
  11015. */
  11016. static int getNumRunningThreads() throw();
  11017. /** Tries to stop all currently-running threads.
  11018. This will attempt to stop all the threads known to be running at the moment.
  11019. */
  11020. static void stopAllThreads (const int timeoutInMillisecs) throw();
  11021. juce_UseDebuggingNewOperator
  11022. private:
  11023. const String threadName_;
  11024. void* volatile threadHandle_;
  11025. CriticalSection startStopLock;
  11026. WaitableEvent startSuspensionEvent_, defaultEvent_;
  11027. int threadPriority_;
  11028. ThreadID threadId_;
  11029. uint32 affinityMask_;
  11030. bool volatile threadShouldExit_;
  11031. friend void JUCE_API juce_threadEntryPoint (void*);
  11032. static void threadEntryPoint (Thread* thread) throw();
  11033. Thread (const Thread&);
  11034. const Thread& operator= (const Thread&);
  11035. };
  11036. #endif // __JUCE_THREAD_JUCEHEADER__
  11037. /********* End of inlined file: juce_Thread.h *********/
  11038. /**
  11039. A critical section that allows multiple simultaneous readers.
  11040. Features of this type of lock are:
  11041. - Multiple readers can hold the lock at the same time, but only one writer
  11042. can hold it at once.
  11043. - Writers trying to gain the lock will be blocked until all readers and writers
  11044. have released it
  11045. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  11046. blocked until the writer has obtained and released it
  11047. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  11048. there are no other readers
  11049. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  11050. - Recursive locking is supported.
  11051. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  11052. */
  11053. class JUCE_API ReadWriteLock
  11054. {
  11055. public:
  11056. /**
  11057. Creates a ReadWriteLock object.
  11058. */
  11059. ReadWriteLock() throw();
  11060. /** Destructor.
  11061. If the object is deleted whilst locked, any subsequent behaviour
  11062. is unpredictable.
  11063. */
  11064. ~ReadWriteLock() throw();
  11065. /** Locks this object for reading.
  11066. Multiple threads can simulaneously lock the object for reading, but if another
  11067. thread has it locked for writing, then this will block until it releases the
  11068. lock.
  11069. @see exitRead, ScopedReadLock
  11070. */
  11071. void enterRead() const throw();
  11072. /** Releases the read-lock.
  11073. If the caller thread hasn't got the lock, this can have unpredictable results.
  11074. If the enterRead() method has been called multiple times by the thread, each
  11075. call must be matched by a call to exitRead() before other threads will be allowed
  11076. to take over the lock.
  11077. @see enterRead, ScopedReadLock
  11078. */
  11079. void exitRead() const throw();
  11080. /** Locks this object for writing.
  11081. This will block until any other threads that have it locked for reading or
  11082. writing have released their lock.
  11083. @see exitWrite, ScopedWriteLock
  11084. */
  11085. void enterWrite() const throw();
  11086. /** Tries to lock this object for writing.
  11087. This is like enterWrite(), but doesn't block - it returns true if it manages
  11088. to obtain the lock.
  11089. @see enterWrite
  11090. */
  11091. bool tryEnterWrite() const throw();
  11092. /** Releases the write-lock.
  11093. If the caller thread hasn't got the lock, this can have unpredictable results.
  11094. If the enterWrite() method has been called multiple times by the thread, each
  11095. call must be matched by a call to exit() before other threads will be allowed
  11096. to take over the lock.
  11097. @see enterWrite, ScopedWriteLock
  11098. */
  11099. void exitWrite() const throw();
  11100. juce_UseDebuggingNewOperator
  11101. private:
  11102. CriticalSection accessLock;
  11103. WaitableEvent waitEvent;
  11104. mutable int numWaitingWriters, numWriters;
  11105. mutable Thread::ThreadID writerThreadId;
  11106. mutable Array <Thread::ThreadID> readerThreads;
  11107. ReadWriteLock (const ReadWriteLock&);
  11108. const ReadWriteLock& operator= (const ReadWriteLock&);
  11109. };
  11110. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  11111. /********* End of inlined file: juce_ReadWriteLock.h *********/
  11112. #endif
  11113. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  11114. #endif
  11115. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11116. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  11117. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11118. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11119. /**
  11120. Automatically locks and unlocks a ReadWriteLock object.
  11121. Use one of these as a local variable to control access to a ReadWriteLock.
  11122. e.g. @code
  11123. ReadWriteLock myLock;
  11124. for (;;)
  11125. {
  11126. const ScopedReadLock myScopedLock (myLock);
  11127. // myLock is now locked
  11128. ...do some stuff...
  11129. // myLock gets unlocked here.
  11130. }
  11131. @endcode
  11132. @see ReadWriteLock, ScopedWriteLock
  11133. */
  11134. class JUCE_API ScopedReadLock
  11135. {
  11136. public:
  11137. /** Creates a ScopedReadLock.
  11138. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  11139. when the ScopedReadLock object is deleted, the ReadWriteLock will
  11140. be unlocked.
  11141. Make sure this object is created and deleted by the same thread,
  11142. otherwise there are no guarantees what will happen! Best just to use it
  11143. as a local stack object, rather than creating one with the new() operator.
  11144. */
  11145. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  11146. /** Destructor.
  11147. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  11148. Make sure this object is created and deleted by the same thread,
  11149. otherwise there are no guarantees what will happen!
  11150. */
  11151. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  11152. private:
  11153. const ReadWriteLock& lock_;
  11154. ScopedReadLock (const ScopedReadLock&);
  11155. const ScopedReadLock& operator= (const ScopedReadLock&);
  11156. };
  11157. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  11158. /********* End of inlined file: juce_ScopedReadLock.h *********/
  11159. #endif
  11160. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11161. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  11162. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11163. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11164. /**
  11165. Automatically tries to lock and unlock a CriticalSection object.
  11166. Use one of these as a local variable to control access to a CriticalSection.
  11167. e.g. @code
  11168. CriticalSection myCriticalSection;
  11169. for (;;)
  11170. {
  11171. const ScopedTryLock myScopedTryLock (myCriticalSection);
  11172. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  11173. // should test this with the isLocked() method before doing your thread-unsafe
  11174. // action..
  11175. if (myScopedTryLock.isLocked())
  11176. {
  11177. ...do some stuff...
  11178. }
  11179. else
  11180. {
  11181. ..our attempt at locking failed because another thread had already locked it..
  11182. }
  11183. // myCriticalSection gets unlocked here (if it was locked)
  11184. }
  11185. @endcode
  11186. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  11187. */
  11188. class JUCE_API ScopedTryLock
  11189. {
  11190. public:
  11191. /** Creates a ScopedTryLock.
  11192. As soon as it is created, this will try to lock the CriticalSection, and
  11193. when the ScopedTryLock object is deleted, the CriticalSection will
  11194. be unlocked if the lock was successful.
  11195. Make sure this object is created and deleted by the same thread,
  11196. otherwise there are no guarantees what will happen! Best just to use it
  11197. as a local stack object, rather than creating one with the new() operator.
  11198. */
  11199. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  11200. /** Destructor.
  11201. The CriticalSection will be unlocked (if locked) when the destructor is called.
  11202. Make sure this object is created and deleted by the same thread,
  11203. otherwise there are no guarantees what will happen!
  11204. */
  11205. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  11206. /** Lock state
  11207. @return True if the CriticalSection is locked.
  11208. */
  11209. bool isLocked() const throw() { return lockWasSuccessful; }
  11210. private:
  11211. const CriticalSection& lock_;
  11212. const bool lockWasSuccessful;
  11213. ScopedTryLock (const ScopedTryLock&);
  11214. const ScopedTryLock& operator= (const ScopedTryLock&);
  11215. };
  11216. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  11217. /********* End of inlined file: juce_ScopedTryLock.h *********/
  11218. #endif
  11219. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11220. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  11221. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11222. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11223. /**
  11224. Automatically locks and unlocks a ReadWriteLock object.
  11225. Use one of these as a local variable to control access to a ReadWriteLock.
  11226. e.g. @code
  11227. ReadWriteLock myLock;
  11228. for (;;)
  11229. {
  11230. const ScopedWriteLock myScopedLock (myLock);
  11231. // myLock is now locked
  11232. ...do some stuff...
  11233. // myLock gets unlocked here.
  11234. }
  11235. @endcode
  11236. @see ReadWriteLock, ScopedReadLock
  11237. */
  11238. class JUCE_API ScopedWriteLock
  11239. {
  11240. public:
  11241. /** Creates a ScopedWriteLock.
  11242. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  11243. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  11244. be unlocked.
  11245. Make sure this object is created and deleted by the same thread,
  11246. otherwise there are no guarantees what will happen! Best just to use it
  11247. as a local stack object, rather than creating one with the new() operator.
  11248. */
  11249. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  11250. /** Destructor.
  11251. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  11252. Make sure this object is created and deleted by the same thread,
  11253. otherwise there are no guarantees what will happen!
  11254. */
  11255. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  11256. private:
  11257. const ReadWriteLock& lock_;
  11258. ScopedWriteLock (const ScopedWriteLock&);
  11259. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  11260. };
  11261. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  11262. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  11263. #endif
  11264. #ifndef __JUCE_THREAD_JUCEHEADER__
  11265. #endif
  11266. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  11267. /********* Start of inlined file: juce_ThreadPool.h *********/
  11268. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  11269. #define __JUCE_THREADPOOL_JUCEHEADER__
  11270. class ThreadPool;
  11271. class ThreadPoolThread;
  11272. /**
  11273. A task that is executed by a ThreadPool object.
  11274. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  11275. its threads.
  11276. The runJob() method needs to be implemented to do the task, and if the code that
  11277. does the work takes a significant time to run, it must keep checking the shouldExit()
  11278. method to see if something is trying to interrupt the job. If shouldExit() returns
  11279. true, the runJob() method must return immediately.
  11280. @see ThreadPool, Thread
  11281. */
  11282. class JUCE_API ThreadPoolJob
  11283. {
  11284. public:
  11285. /** Creates a thread pool job object.
  11286. After creating your job, add it to a thread pool with ThreadPool::addJob().
  11287. */
  11288. ThreadPoolJob (const String& name);
  11289. /** Destructor. */
  11290. virtual ~ThreadPoolJob();
  11291. /** Returns the name of this job.
  11292. @see setJobName
  11293. */
  11294. const String getJobName() const;
  11295. /** Changes the job's name.
  11296. @see getJobName
  11297. */
  11298. void setJobName (const String& newName);
  11299. /** These are the values that can be returned by the runJob() method.
  11300. */
  11301. enum JobStatus
  11302. {
  11303. jobHasFinished = 0, /**< indicates that the job has finished and can be
  11304. removed from the pool. */
  11305. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  11306. should be automatically deleted by the pool. */
  11307. jobNeedsRunningAgain /**< indicates that the job would like to be called
  11308. again when a thread is free. */
  11309. };
  11310. /** Peforms the actual work that this job needs to do.
  11311. Your subclass must implement this method, in which is does its work.
  11312. If the code in this method takes a significant time to run, it must repeatedly check
  11313. the shouldExit() method to see if something is trying to interrupt the job.
  11314. If shouldExit() ever returns true, the runJob() method must return immediately.
  11315. If this method returns jobHasFinished, then the job will be removed from the pool
  11316. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  11317. pool and will get a chance to run again as soon as a thread is free.
  11318. @see shouldExit()
  11319. */
  11320. virtual JobStatus runJob() = 0;
  11321. /** Returns true if this job is currently running its runJob() method. */
  11322. bool isRunning() const throw() { return isActive; }
  11323. /** Returns true if something is trying to interrupt this job and make it stop.
  11324. Your runJob() method must call this whenever it gets a chance, and if it ever
  11325. returns true, the runJob() method must return immediately.
  11326. @see signalJobShouldExit()
  11327. */
  11328. bool shouldExit() const throw() { return shouldStop; }
  11329. /** Calling this will cause the shouldExit() method to return true, and the job
  11330. should (if it's been implemented correctly) stop as soon as possible.
  11331. @see shouldExit()
  11332. */
  11333. void signalJobShouldExit();
  11334. juce_UseDebuggingNewOperator
  11335. private:
  11336. friend class ThreadPool;
  11337. friend class ThreadPoolThread;
  11338. String jobName;
  11339. ThreadPool* pool;
  11340. bool shouldStop, isActive, shouldBeDeleted;
  11341. };
  11342. /**
  11343. A set of threads that will run a list of jobs.
  11344. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  11345. will be called by the next pooled thread that becomes free.
  11346. @see ThreadPoolJob, Thread
  11347. */
  11348. class JUCE_API ThreadPool
  11349. {
  11350. public:
  11351. /** Creates a thread pool.
  11352. Once you've created a pool, you can give it some things to do with the addJob()
  11353. method.
  11354. @param numberOfThreads the maximum number of actual threads to run.
  11355. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  11356. until there are some jobs to run. If false, then
  11357. all the threads will be fired-up immediately so that
  11358. they're ready for action
  11359. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  11360. inactive for this length of time, they will automatically
  11361. be stopped until more jobs come along and they're needed
  11362. */
  11363. ThreadPool (const int numberOfThreads,
  11364. const bool startThreadsOnlyWhenNeeded = true,
  11365. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  11366. /** Destructor.
  11367. This will attempt to remove all the jobs before deleting, but if you want to
  11368. specify a timeout, you should call removeAllJobs() explicitly before deleting
  11369. the pool.
  11370. */
  11371. ~ThreadPool();
  11372. /** Adds a job to the queue.
  11373. Once a job has been added, then the next time a thread is free, it will run
  11374. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  11375. runJob() method, the pool will either remove the job from the pool or add it to
  11376. the back of the queue to be run again.
  11377. */
  11378. void addJob (ThreadPoolJob* const job);
  11379. /** Tries to remove a job from the pool.
  11380. If the job isn't yet running, this will simply remove it. If it is running, it
  11381. will wait for it to finish.
  11382. If the timeout period expires before the job finishes running, then the job will be
  11383. left in the pool and this will return false. It returns true if the job is sucessfully
  11384. stopped and removed.
  11385. @param job the job to remove
  11386. @param interruptIfRunning if true, then if the job is currently busy, its
  11387. ThreadPoolJob::signalJobShouldExit() method will be called to try
  11388. to interrupt it. If false, then if the job will be allowed to run
  11389. until it stops normally (or the timeout expires)
  11390. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  11391. before giving up and returning false
  11392. */
  11393. bool removeJob (ThreadPoolJob* const job,
  11394. const bool interruptIfRunning,
  11395. const int timeOutMilliseconds);
  11396. /** Tries clear all jobs from the pool.
  11397. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  11398. methods called to try to interrupt them
  11399. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  11400. before giving up and returning false
  11401. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  11402. they will simply be removed from the pool. Jobs that are already running when
  11403. this method is called can choose whether they should be deleted by
  11404. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  11405. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  11406. expires while waiting for them to stop
  11407. */
  11408. bool removeAllJobs (const bool interruptRunningJobs,
  11409. const int timeOutMilliseconds,
  11410. const bool deleteInactiveJobs = false);
  11411. /** Returns the number of jobs currently running or queued.
  11412. */
  11413. int getNumJobs() const throw();
  11414. /** Returns one of the jobs in the queue.
  11415. Note that this can be a very volatile list as jobs might be continuously getting shifted
  11416. around in the list, and this method may return 0 if the index is currently out-of-range.
  11417. */
  11418. ThreadPoolJob* getJob (const int index) const;
  11419. /** Returns true if the given job is currently queued or running.
  11420. @see isJobRunning()
  11421. */
  11422. bool contains (const ThreadPoolJob* const job) const throw();
  11423. /** Returns true if the given job is currently being run by a thread.
  11424. */
  11425. bool isJobRunning (const ThreadPoolJob* const job) const;
  11426. /** Waits until a job has finished running and has been removed from the pool.
  11427. This will wait until the job is no longer in the pool - i.e. until its
  11428. runJob() method returns ThreadPoolJob::jobHasFinished.
  11429. If the timeout period expires before the job finishes, this will return false;
  11430. it returns true if the job has finished successfully.
  11431. */
  11432. bool waitForJobToFinish (const ThreadPoolJob* const job,
  11433. const int timeOutMilliseconds) const;
  11434. /** Returns a list of the names of all the jobs currently running or queued.
  11435. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  11436. */
  11437. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const;
  11438. /** Changes the priority of all the threads.
  11439. This will call Thread::setPriority() for each thread in the pool.
  11440. May return false if for some reason the priority can't be changed.
  11441. */
  11442. bool setThreadPriorities (const int newPriority);
  11443. juce_UseDebuggingNewOperator
  11444. private:
  11445. const int numThreads, threadStopTimeout;
  11446. int priority;
  11447. Thread** threads;
  11448. VoidArray jobs;
  11449. CriticalSection lock;
  11450. uint32 lastJobEndTime;
  11451. friend class ThreadPoolThread;
  11452. bool runNextJob();
  11453. ThreadPool (const ThreadPool&);
  11454. const ThreadPool& operator= (const ThreadPool&);
  11455. };
  11456. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  11457. /********* End of inlined file: juce_ThreadPool.h *********/
  11458. #endif
  11459. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11460. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  11461. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11462. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11463. /**
  11464. Used by the TimeSliceThread class.
  11465. To register your class with a TimeSliceThread, derive from this class and
  11466. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  11467. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  11468. deleting your client!
  11469. @see TimeSliceThread
  11470. */
  11471. class JUCE_API TimeSliceClient
  11472. {
  11473. public:
  11474. /** Destructor. */
  11475. virtual ~TimeSliceClient() {}
  11476. /** Called back by a TimeSliceThread.
  11477. When you register this class with it, a TimeSliceThread will repeatedly call
  11478. this method.
  11479. The implementation of this method should use its time-slice to do something that's
  11480. quick - never block for longer than absolutely necessary.
  11481. @returns Your method should return true if it needs more time, or false if it's
  11482. not too busy and doesn't need calling back urgently. If all the thread's
  11483. clients indicate that they're not busy, then it'll save CPU by sleeping for
  11484. up to half a second in between callbacks. You can force the TimeSliceThread
  11485. to wake up and poll again immediately by calling its notify() method.
  11486. */
  11487. virtual bool useTimeSlice() = 0;
  11488. };
  11489. /**
  11490. A thread that keeps a list of clients, and calls each one in turn, giving them
  11491. all a chance to run some sort of short task.
  11492. @see TimeSliceClient, Thread
  11493. */
  11494. class JUCE_API TimeSliceThread : public Thread
  11495. {
  11496. public:
  11497. /**
  11498. Creates a TimeSliceThread.
  11499. When first created, the thread is not running. Use the startThread()
  11500. method to start it.
  11501. */
  11502. TimeSliceThread (const String& threadName);
  11503. /** Destructor.
  11504. Deleting a Thread object that is running will only give the thread a
  11505. brief opportunity to stop itself cleanly, so it's recommended that you
  11506. should always call stopThread() with a decent timeout before deleting,
  11507. to avoid the thread being forcibly killed (which is a Bad Thing).
  11508. */
  11509. ~TimeSliceThread();
  11510. /** Adds a client to the list.
  11511. The client's callbacks will start immediately (possibly before the method
  11512. has returned).
  11513. */
  11514. void addTimeSliceClient (TimeSliceClient* const client);
  11515. /** Removes a client from the list.
  11516. This method will make sure that all callbacks to the client have completely
  11517. finished before the method returns.
  11518. */
  11519. void removeTimeSliceClient (TimeSliceClient* const client);
  11520. /** Returns the number of registered clients. */
  11521. int getNumClients() const throw();
  11522. /** Returns one of the registered clients. */
  11523. TimeSliceClient* getClient (const int index) const throw();
  11524. /** @internal */
  11525. void run();
  11526. juce_UseDebuggingNewOperator
  11527. private:
  11528. CriticalSection callbackLock, listLock;
  11529. Array <TimeSliceClient*> clients;
  11530. int index;
  11531. TimeSliceClient* clientBeingCalled;
  11532. bool clientsChanged;
  11533. TimeSliceThread (const TimeSliceThread&);
  11534. const TimeSliceThread& operator= (const TimeSliceThread&);
  11535. };
  11536. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  11537. /********* End of inlined file: juce_TimeSliceThread.h *********/
  11538. #endif
  11539. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11540. #endif
  11541. #endif
  11542. /********* End of inlined file: juce_core_includes.h *********/
  11543. // if you're compiling a command-line app, you might want to just include the core headers,
  11544. // so you can set this macro before including juce.h
  11545. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11546. /********* Start of inlined file: juce_app_includes.h *********/
  11547. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11548. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  11549. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11550. /********* Start of inlined file: juce_Application.h *********/
  11551. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  11552. #define __JUCE_APPLICATION_JUCEHEADER__
  11553. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  11554. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11555. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  11556. /********* Start of inlined file: juce_Component.h *********/
  11557. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  11558. #define __JUCE_COMPONENT_JUCEHEADER__
  11559. /********* Start of inlined file: juce_MouseCursor.h *********/
  11560. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  11561. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  11562. class Image;
  11563. class RefCountedMouseCursor;
  11564. class ComponentPeer;
  11565. class Component;
  11566. /**
  11567. Represents a mouse cursor image.
  11568. This object can either be used to represent one of the standard mouse
  11569. cursor shapes, or a custom one generated from an image.
  11570. */
  11571. class JUCE_API MouseCursor
  11572. {
  11573. public:
  11574. /** The set of available standard mouse cursors. */
  11575. enum StandardCursorType
  11576. {
  11577. NoCursor = 0, /**< An invisible cursor. */
  11578. NormalCursor, /**< The stardard arrow cursor. */
  11579. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  11580. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  11581. CrosshairCursor, /**< A pair of crosshairs. */
  11582. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  11583. that you're dragging a copy of something. */
  11584. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  11585. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  11586. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  11587. UpDownResizeCursor, /**< an arrow pointing up and down. */
  11588. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  11589. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  11590. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  11591. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  11592. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  11593. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  11594. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  11595. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  11596. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  11597. };
  11598. /** Creates the standard arrow cursor. */
  11599. MouseCursor() throw();
  11600. /** Creates one of the standard mouse cursor */
  11601. MouseCursor (const StandardCursorType type) throw();
  11602. /** Creates a custom cursor from an image.
  11603. @param image the image to use for the cursor - if this is bigger than the
  11604. system can manage, it might get scaled down first, and might
  11605. also have to be turned to black-and-white if it can't do colour
  11606. cursors.
  11607. @param hotSpotX the x position of the cursor's hotspot within the image
  11608. @param hotSpotY the y position of the cursor's hotspot within the image
  11609. */
  11610. MouseCursor (Image& image,
  11611. const int hotSpotX,
  11612. const int hotSpotY) throw();
  11613. /** Creates a copy of another cursor object. */
  11614. MouseCursor (const MouseCursor& other) throw();
  11615. /** Copies this cursor from another object. */
  11616. const MouseCursor& operator= (const MouseCursor& other) throw();
  11617. /** Destructor. */
  11618. ~MouseCursor() throw();
  11619. /** Checks whether two mouse cursors are the same.
  11620. For custom cursors, two cursors created from the same image won't be
  11621. recognised as the same, only MouseCursor objects that have been
  11622. copied from the same object.
  11623. */
  11624. bool operator== (const MouseCursor& other) const throw();
  11625. /** Checks whether two mouse cursors are the same.
  11626. For custom cursors, two cursors created from the same image won't be
  11627. recognised as the same, only MouseCursor objects that have been
  11628. copied from the same object.
  11629. */
  11630. bool operator!= (const MouseCursor& other) const throw();
  11631. /** Makes the system show its default 'busy' cursor.
  11632. This will turn the system cursor to an hourglass or spinning beachball
  11633. until the next time the mouse is moved, or hideWaitCursor() is called.
  11634. This is handy if the message loop is about to block for a couple of
  11635. seconds while busy and you want to give the user feedback about this.
  11636. @see MessageManager::setTimeBeforeShowingWaitCursor
  11637. */
  11638. static void showWaitCursor() throw();
  11639. /** If showWaitCursor has been called, this will return the mouse to its
  11640. normal state.
  11641. This will look at what component is under the mouse, and update the
  11642. cursor to be the correct one for that component.
  11643. @see showWaitCursor
  11644. */
  11645. static void hideWaitCursor() throw();
  11646. juce_UseDebuggingNewOperator
  11647. private:
  11648. RefCountedMouseCursor* cursorHandle;
  11649. friend class Component;
  11650. void showInWindow (ComponentPeer* window) const throw();
  11651. void showInAllWindows() const throw();
  11652. void* getHandle() const throw();
  11653. };
  11654. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  11655. /********* End of inlined file: juce_MouseCursor.h *********/
  11656. /********* Start of inlined file: juce_MouseListener.h *********/
  11657. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  11658. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  11659. /********* Start of inlined file: juce_MouseEvent.h *********/
  11660. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  11661. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  11662. class Component;
  11663. /********* Start of inlined file: juce_ModifierKeys.h *********/
  11664. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  11665. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  11666. /**
  11667. Represents the state of the mouse buttons and modifier keys.
  11668. This is used both by mouse events and by KeyPress objects to describe
  11669. the state of keys such as shift, control, alt, etc.
  11670. @see KeyPress, MouseEvent::mods
  11671. */
  11672. class JUCE_API ModifierKeys
  11673. {
  11674. public:
  11675. /** Creates a ModifierKeys object from a raw set of flags.
  11676. @param flags to represent the keys that are down
  11677. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  11678. rightButtonModifier, commandModifier, popupMenuClickModifier
  11679. */
  11680. ModifierKeys (const int flags = 0) throw();
  11681. /** Creates a copy of another object. */
  11682. ModifierKeys (const ModifierKeys& other) throw();
  11683. /** Copies this object from another one. */
  11684. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  11685. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  11686. This is a platform-agnostic way of checking for the operating system's
  11687. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  11688. Windows/Linux, it's actually checking for the CTRL key.
  11689. */
  11690. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  11691. /** Checks whether the user is trying to launch a pop-up menu.
  11692. This checks for platform-specific modifiers that might indicate that the user
  11693. is following the operating system's normal method of showing a pop-up menu.
  11694. So on Windows/Linux, this method is really testing for a right-click.
  11695. On the Mac, it tests for either the CTRL key being down, or a right-click.
  11696. */
  11697. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  11698. /** Checks whether the flag is set for the left mouse-button. */
  11699. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  11700. /** Checks whether the flag is set for the right mouse-button.
  11701. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  11702. this is platform-independent (and makes your code more explanatory too).
  11703. */
  11704. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  11705. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  11706. /** Tests for any of the mouse-button flags. */
  11707. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  11708. /** Tests for any of the modifier key flags. */
  11709. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  11710. /** Checks whether the shift key's flag is set. */
  11711. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  11712. /** Checks whether the CTRL key's flag is set.
  11713. Remember that it's better to use the platform-agnostic routines to test for command-key and
  11714. popup-menu modifiers.
  11715. @see isCommandDown, isPopupMenu
  11716. */
  11717. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  11718. /** Checks whether the shift key's flag is set. */
  11719. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  11720. /** Flags that represent the different keys. */
  11721. enum Flags
  11722. {
  11723. /** Shift key flag. */
  11724. shiftModifier = 1,
  11725. /** CTRL key flag. */
  11726. ctrlModifier = 2,
  11727. /** ALT key flag. */
  11728. altModifier = 4,
  11729. /** Left mouse button flag. */
  11730. leftButtonModifier = 16,
  11731. /** Right mouse button flag. */
  11732. rightButtonModifier = 32,
  11733. /** Middle mouse button flag. */
  11734. middleButtonModifier = 64,
  11735. #if JUCE_MAC
  11736. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11737. commandModifier = 8,
  11738. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11739. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11740. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  11741. #else
  11742. /** Command key flag - on windows this is the same as the CTRL key flag. */
  11743. commandModifier = ctrlModifier,
  11744. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  11745. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  11746. popupMenuClickModifier = rightButtonModifier,
  11747. #endif
  11748. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  11749. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  11750. /** Represents a combination of all the mouse buttons at once. */
  11751. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  11752. };
  11753. /** Returns the raw flags for direct testing. */
  11754. inline int getRawFlags() const throw() { return flags; }
  11755. /** Tests a combination of flags and returns true if any of them are set. */
  11756. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  11757. /** Creates a ModifierKeys object to represent the last-known state of the
  11758. keyboard and mouse buttons.
  11759. @see getCurrentModifiersRealtime
  11760. */
  11761. static const ModifierKeys getCurrentModifiers() throw();
  11762. /** Creates a ModifierKeys object to represent the current state of the
  11763. keyboard and mouse buttons.
  11764. This isn't often needed and isn't recommended, but will actively check all the
  11765. mouse and key states rather than just returning their last-known state like
  11766. getCurrentModifiers() does.
  11767. This is only needed in special circumstances for up-to-date modifier information
  11768. at times when the app's event loop isn't running normally.
  11769. */
  11770. static const ModifierKeys getCurrentModifiersRealtime() throw();
  11771. private:
  11772. int flags;
  11773. static int currentModifierFlags;
  11774. friend class ComponentPeer;
  11775. static void updateCurrentModifiers() throw();
  11776. };
  11777. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  11778. /********* End of inlined file: juce_ModifierKeys.h *********/
  11779. /**
  11780. Contains position and status information about a mouse event.
  11781. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  11782. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  11783. */
  11784. class JUCE_API MouseEvent
  11785. {
  11786. public:
  11787. /** Creates a MouseEvent.
  11788. Normally an application will never need to use this.
  11789. @param x the x position of the mouse, relative to the component that is passed-in
  11790. @param y the y position of the mouse, relative to the component that is passed-in
  11791. @param modifiers the key modifiers at the time of the event
  11792. @param originator the component that the mouse event applies to
  11793. @param eventTime the time the event happened
  11794. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  11795. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11796. the same as the current mouse-x position.
  11797. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  11798. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11799. the same as the current mouse-y position.
  11800. @param mouseDownTime the time at which the corresponding mouse-down event happened
  11801. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  11802. the same as the current mouse-event time.
  11803. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  11804. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  11805. */
  11806. MouseEvent (const int x, const int y,
  11807. const ModifierKeys& modifiers,
  11808. Component* const originator,
  11809. const Time& eventTime,
  11810. const int mouseDownX,
  11811. const int mouseDownY,
  11812. const Time& mouseDownTime,
  11813. const int numberOfClicks,
  11814. const bool mouseWasDragged) throw();
  11815. /** Destructor. */
  11816. ~MouseEvent() throw();
  11817. /** The x-position of the mouse when the event occurred.
  11818. This value is relative to the top-left of the component to which the
  11819. event applies (as indicated by the MouseEvent::eventComponent field).
  11820. */
  11821. int x;
  11822. /** The y-position of the mouse when the event occurred.
  11823. This value is relative to the top-left of the component to which the
  11824. event applies (as indicated by the MouseEvent::eventComponent field).
  11825. */
  11826. int y;
  11827. /** The key modifiers associated with the event.
  11828. This will let you find out which mouse buttons were down, as well as which
  11829. modifier keys were held down.
  11830. When used for mouse-up events, this will indicate the state of the mouse buttons
  11831. just before they were released, so that you can tell which button they let go of.
  11832. */
  11833. ModifierKeys mods;
  11834. /** The component that this event applies to.
  11835. This is usually the component that the mouse was over at the time, but for mouse-drag
  11836. events the mouse could actually be over a different component and the events are
  11837. still sent to the component that the button was originally pressed on.
  11838. The x and y member variables are relative to this component's position.
  11839. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11840. component, this pointer will be updated, but originalComponent remains unchanged.
  11841. @see originalComponent
  11842. */
  11843. Component* eventComponent;
  11844. /** The component that the event first occurred on.
  11845. If you use getEventRelativeTo() to retarget this object to be relative to a different
  11846. component, this value remains unchanged to indicate the first component that received it.
  11847. @see eventComponent
  11848. */
  11849. Component* originalComponent;
  11850. /** The time that this mouse-event occurred.
  11851. */
  11852. Time eventTime;
  11853. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  11854. The co-ordinate is relative to the component specified in MouseEvent::component.
  11855. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11856. */
  11857. int getMouseDownX() const throw();
  11858. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  11859. The co-ordinate is relative to the component specified in MouseEvent::component.
  11860. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  11861. */
  11862. int getMouseDownY() const throw();
  11863. /** Returns the straight-line distance between where the mouse is now and where it
  11864. was the last time the button was pressed.
  11865. This is quite handy for things like deciding whether the user has moved far enough
  11866. for it to be considered a drag operation.
  11867. @see getDistanceFromDragStartX
  11868. */
  11869. int getDistanceFromDragStart() const throw();
  11870. /** Returns the difference between the mouse's current x postion and where it was
  11871. when the button was last pressed.
  11872. @see getDistanceFromDragStart
  11873. */
  11874. int getDistanceFromDragStartX() const throw();
  11875. /** Returns the difference between the mouse's current y postion and where it was
  11876. when the button was last pressed.
  11877. @see getDistanceFromDragStart
  11878. */
  11879. int getDistanceFromDragStartY() const throw();
  11880. /** Returns true if the mouse has just been clicked.
  11881. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  11882. the user has dragged the mouse more than a few pixels from the place where the
  11883. mouse-down occurred.
  11884. Once they have dragged it far enough for this method to return false, it will continue
  11885. to return false until the mouse-up, even if they move the mouse back to the same
  11886. position where they originally pressed it. This means that it's very handy for
  11887. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  11888. callback to ignore any small movements they might make while clicking.
  11889. @returns true if the mouse wasn't dragged by more than a few pixels between
  11890. the last time the button was pressed and released.
  11891. */
  11892. bool mouseWasClicked() const throw();
  11893. /** For a click event, the number of times the mouse was clicked in succession.
  11894. So for example a double-click event will return 2, a triple-click 3, etc.
  11895. */
  11896. int getNumberOfClicks() const throw() { return numberOfClicks; }
  11897. /** Returns the time that the mouse button has been held down for.
  11898. If called from a mouseDrag or mouseUp callback, this will return the
  11899. number of milliseconds since the corresponding mouseDown event occurred.
  11900. If called in other contexts, e.g. a mouseMove, then the returned value
  11901. may be 0 or an undefined value.
  11902. */
  11903. int getLengthOfMousePress() const throw();
  11904. /** Returns the mouse x position of this event, in global screen co-ordinates.
  11905. The co-ordinates are relative to the top-left of the main monitor.
  11906. @see getMouseDownScreenX, Desktop::getMousePosition
  11907. */
  11908. int getScreenX() const throw();
  11909. /** Returns the mouse y position of this event, in global screen co-ordinates.
  11910. The co-ordinates are relative to the top-left of the main monitor.
  11911. @see getMouseDownScreenY, Desktop::getMousePosition
  11912. */
  11913. int getScreenY() const throw();
  11914. /** Returns the x co-ordinate at which the mouse button was last pressed.
  11915. The co-ordinates are relative to the top-left of the main monitor.
  11916. @see getScreenX, Desktop::getMousePosition
  11917. */
  11918. int getMouseDownScreenX() const throw();
  11919. /** Returns the y co-ordinate at which the mouse button was last pressed.
  11920. The co-ordinates are relative to the top-left of the main monitor.
  11921. @see getScreenY, Desktop::getMousePosition
  11922. */
  11923. int getMouseDownScreenY() const throw();
  11924. /** Creates a version of this event that is relative to a different component.
  11925. The x and y positions of the event that is returned will have been
  11926. adjusted to be relative to the new component.
  11927. */
  11928. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  11929. /** Changes the application-wide setting for the double-click time limit.
  11930. This is the maximum length of time between mouse-clicks for it to be
  11931. considered a double-click. It's used by the Component class.
  11932. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  11933. */
  11934. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  11935. /** Returns the application-wide setting for the double-click time limit.
  11936. This is the maximum length of time between mouse-clicks for it to be
  11937. considered a double-click. It's used by the Component class.
  11938. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  11939. */
  11940. static int getDoubleClickTimeout() throw();
  11941. juce_UseDebuggingNewOperator
  11942. private:
  11943. int mouseDownX, mouseDownY;
  11944. Time mouseDownTime;
  11945. int numberOfClicks;
  11946. bool wasMovedSinceMouseDown;
  11947. };
  11948. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  11949. /********* End of inlined file: juce_MouseEvent.h *********/
  11950. /**
  11951. A MouseListener can be registered with a component to receive callbacks
  11952. about mouse events that happen to that component.
  11953. @see Component::addMouseListener, Component::removeMouseListener
  11954. */
  11955. class JUCE_API MouseListener
  11956. {
  11957. public:
  11958. /** Destructor. */
  11959. virtual ~MouseListener() {}
  11960. /** Called when the mouse moves inside a component.
  11961. If the mouse button isn't pressed and the mouse moves over a component,
  11962. this will be called to let the component react to this.
  11963. A component will always get a mouseEnter callback before a mouseMove.
  11964. @param e details about the position and status of the mouse event, including
  11965. the source component in which it occurred
  11966. @see mouseEnter, mouseExit, mouseDrag, contains
  11967. */
  11968. virtual void mouseMove (const MouseEvent& e);
  11969. /** Called when the mouse first enters a component.
  11970. If the mouse button isn't pressed and the mouse moves into a component,
  11971. this will be called to let the component react to this.
  11972. When the mouse button is pressed and held down while being moved in
  11973. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  11974. mouseDrag messages are sent to the component that the mouse was originally
  11975. clicked on, until the button is released.
  11976. @param e details about the position and status of the mouse event, including
  11977. the source component in which it occurred
  11978. @see mouseExit, mouseDrag, mouseMove, contains
  11979. */
  11980. virtual void mouseEnter (const MouseEvent& e);
  11981. /** Called when the mouse moves out of a component.
  11982. This will be called when the mouse moves off the edge of this
  11983. component.
  11984. If the mouse button was pressed, and it was then dragged off the
  11985. edge of the component and released, then this callback will happen
  11986. when the button is released, after the mouseUp callback.
  11987. @param e details about the position and status of the mouse event, including
  11988. the source component in which it occurred
  11989. @see mouseEnter, mouseDrag, mouseMove, contains
  11990. */
  11991. virtual void mouseExit (const MouseEvent& e);
  11992. /** Called when a mouse button is pressed.
  11993. The MouseEvent object passed in contains lots of methods for finding out
  11994. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  11995. were held down at the time.
  11996. Once a button is held down, the mouseDrag method will be called when the
  11997. mouse moves, until the button is released.
  11998. @param e details about the position and status of the mouse event, including
  11999. the source component in which it occurred
  12000. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  12001. */
  12002. virtual void mouseDown (const MouseEvent& e);
  12003. /** Called when the mouse is moved while a button is held down.
  12004. When a mouse button is pressed inside a component, that component
  12005. receives mouseDrag callbacks each time the mouse moves, even if the
  12006. mouse strays outside the component's bounds.
  12007. @param e details about the position and status of the mouse event, including
  12008. the source component in which it occurred
  12009. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  12010. */
  12011. virtual void mouseDrag (const MouseEvent& e);
  12012. /** Called when a mouse button is released.
  12013. A mouseUp callback is sent to the component in which a button was pressed
  12014. even if the mouse is actually over a different component when the
  12015. button is released.
  12016. The MouseEvent object passed in contains lots of methods for finding out
  12017. which buttons were down just before they were released.
  12018. @param e details about the position and status of the mouse event, including
  12019. the source component in which it occurred
  12020. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  12021. */
  12022. virtual void mouseUp (const MouseEvent& e);
  12023. /** Called when a mouse button has been double-clicked on a component.
  12024. The MouseEvent object passed in contains lots of methods for finding out
  12025. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  12026. were held down at the time.
  12027. @param e details about the position and status of the mouse event, including
  12028. the source component in which it occurred
  12029. @see mouseDown, mouseUp
  12030. */
  12031. virtual void mouseDoubleClick (const MouseEvent& e);
  12032. /** Called when the mouse-wheel is moved.
  12033. This callback is sent to the component that the mouse is over when the
  12034. wheel is moved.
  12035. If not overridden, the component will forward this message to its parent, so
  12036. that parent components can collect mouse-wheel messages that happen to
  12037. child components which aren't interested in them.
  12038. @param e details about the position and status of the mouse event, including
  12039. the source component in which it occurred
  12040. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  12041. value means the wheel has been pushed to the right, negative means it
  12042. was pushed to the left
  12043. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  12044. value means the wheel has been pushed upwards, negative means it
  12045. was pushed downwards
  12046. */
  12047. virtual void mouseWheelMove (const MouseEvent& e,
  12048. float wheelIncrementX,
  12049. float wheelIncrementY);
  12050. private:
  12051. // XXX Deprecated! The parameters for this method have changed to accommodate horizonatal scroll-wheels.
  12052. // This line is here to cause a syntax error if you're trying to use the old-style definition, so
  12053. // if that happens, update your code to use the new one above.
  12054. virtual int mouseWheelMove (const MouseEvent&, float) { return 0; }
  12055. };
  12056. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  12057. /********* End of inlined file: juce_MouseListener.h *********/
  12058. /********* Start of inlined file: juce_ComponentListener.h *********/
  12059. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12060. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12061. class Component;
  12062. /**
  12063. Gets informed about changes to a component's hierarchy or position.
  12064. To monitor a component for changes, register a subclass of ComponentListener
  12065. with the component using Component::addComponentListener().
  12066. Be sure to deregister listeners before you delete them!
  12067. @see Component::addComponentListener, Component::removeComponentListener
  12068. */
  12069. class JUCE_API ComponentListener
  12070. {
  12071. public:
  12072. /** Destructor. */
  12073. virtual ~ComponentListener() {}
  12074. /** Called when the component's position or size changes.
  12075. @param component the component that was moved or resized
  12076. @param wasMoved true if the component's top-left corner has just moved
  12077. @param wasResized true if the component's width or height has just changed
  12078. @see Component::setBounds, Component::resized, Component::moved
  12079. */
  12080. virtual void componentMovedOrResized (Component& component,
  12081. bool wasMoved,
  12082. bool wasResized);
  12083. /** Called when the component is brought to the top of the z-order.
  12084. @param component the component that was moved
  12085. @see Component::toFront, Component::broughtToFront
  12086. */
  12087. virtual void componentBroughtToFront (Component& component);
  12088. /** Called when the component is made visible or invisible.
  12089. @param component the component that changed
  12090. @see Component::setVisible
  12091. */
  12092. virtual void componentVisibilityChanged (Component& component);
  12093. /** Called when the component has children added or removed.
  12094. @param component the component whose children were changed
  12095. @see Component::childrenChanged, Component::addChildComponent,
  12096. Component::removeChildComponent
  12097. */
  12098. virtual void componentChildrenChanged (Component& component);
  12099. /** Called to indicate that the component's parents have changed.
  12100. When a component is added or removed from its parent, all of its children
  12101. will produce this notification (recursively - so all children of its
  12102. children will also be called as well).
  12103. @param component the component that this listener is registered with
  12104. @see Component::parentHierarchyChanged
  12105. */
  12106. virtual void componentParentHierarchyChanged (Component& component);
  12107. /** Called when the component's name is changed.
  12108. @see Component::setName, Component::getName
  12109. */
  12110. virtual void componentNameChanged (Component& component);
  12111. };
  12112. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  12113. /********* End of inlined file: juce_ComponentListener.h *********/
  12114. /********* Start of inlined file: juce_KeyListener.h *********/
  12115. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  12116. #define __JUCE_KEYLISTENER_JUCEHEADER__
  12117. /********* Start of inlined file: juce_KeyPress.h *********/
  12118. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  12119. #define __JUCE_KEYPRESS_JUCEHEADER__
  12120. /**
  12121. Represents a key press, including any modifier keys that are needed.
  12122. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  12123. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  12124. */
  12125. class JUCE_API KeyPress
  12126. {
  12127. public:
  12128. /** Creates an (invalid) KeyPress.
  12129. @see isValid
  12130. */
  12131. KeyPress() throw();
  12132. /** Creates a KeyPress for a key and some modifiers.
  12133. e.g.
  12134. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  12135. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  12136. @param keyCode a code that represents the key - this value must be
  12137. one of special constants listed in this class, or an
  12138. 8-bit character code such as a letter (case is ignored),
  12139. digit or a simple key like "," or ".". Note that this
  12140. isn't the same as the textCharacter parameter, so for example
  12141. a keyCode of 'a' and a shift-key modifier should have a
  12142. textCharacter value of 'A'.
  12143. @param modifiers the modifiers to associate with the keystroke
  12144. @param textCharacter the character that would be printed if someone typed
  12145. this keypress into a text editor. This value may be
  12146. null if the keypress is a non-printing character
  12147. @see getKeyCode, isKeyCode, getModifiers
  12148. */
  12149. KeyPress (const int keyCode,
  12150. const ModifierKeys& modifiers,
  12151. const juce_wchar textCharacter) throw();
  12152. /** Creates a keypress with a keyCode but no modifiers or text character.
  12153. */
  12154. KeyPress (const int keyCode) throw();
  12155. /** Creates a copy of another KeyPress. */
  12156. KeyPress (const KeyPress& other) throw();
  12157. /** Copies this KeyPress from another one. */
  12158. const KeyPress& operator= (const KeyPress& other) throw();
  12159. /** Compares two KeyPress objects. */
  12160. bool operator== (const KeyPress& other) const throw();
  12161. /** Compares two KeyPress objects. */
  12162. bool operator!= (const KeyPress& other) const throw();
  12163. /** Returns true if this is a valid KeyPress.
  12164. A null keypress can be created by the default constructor, in case it's
  12165. needed.
  12166. */
  12167. bool isValid() const throw() { return keyCode != 0; }
  12168. /** Returns the key code itself.
  12169. This will either be one of the special constants defined in this class,
  12170. or an 8-bit character code.
  12171. */
  12172. int getKeyCode() const throw() { return keyCode; }
  12173. /** Returns the key modifiers.
  12174. @see ModifierKeys
  12175. */
  12176. const ModifierKeys getModifiers() const throw() { return mods; }
  12177. /** Returns the character that is associated with this keypress.
  12178. This is the character that you'd expect to see printed if you press this
  12179. keypress in a text editor or similar component.
  12180. */
  12181. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  12182. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  12183. the modifiers.
  12184. The values for key codes can either be one of the special constants defined in
  12185. this class, or an 8-bit character code.
  12186. @see getKeyCode
  12187. */
  12188. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  12189. /** Converts a textual key description to a KeyPress.
  12190. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  12191. This isn't designed to cope with any kind of input, but should be given the
  12192. strings that are created by the getTextDescription() method.
  12193. If the string can't be parsed, the object returned will be invalid.
  12194. @see getTextDescription
  12195. */
  12196. static const KeyPress createFromDescription (const String& textVersion) throw();
  12197. /** Creates a textual description of the key combination.
  12198. e.g. "CTRL + C" or "DELETE".
  12199. To store a keypress in a file, use this method, along with createFromDescription()
  12200. to retrieve it later.
  12201. */
  12202. const String getTextDescription() const throw();
  12203. /** Checks whether the user is currently holding down the keys that make up this
  12204. KeyPress.
  12205. Note that this will return false if any extra modifier keys are
  12206. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  12207. then it will be false.
  12208. */
  12209. bool isCurrentlyDown() const throw();
  12210. /** Checks whether a particular key is held down, irrespective of modifiers.
  12211. The values for key codes can either be one of the special constants defined in
  12212. this class, or an 8-bit character code.
  12213. */
  12214. static bool isKeyCurrentlyDown (int keyCode) throw();
  12215. // Key codes
  12216. //
  12217. // Note that the actual values of these are platform-specific and may change
  12218. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  12219. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  12220. //
  12221. static const int spaceKey; /**< key-code for the space bar */
  12222. static const int escapeKey; /**< key-code for the escape key */
  12223. static const int returnKey; /**< key-code for the return key*/
  12224. static const int tabKey; /**< key-code for the tab key*/
  12225. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  12226. static const int backspaceKey; /**< key-code for the backspace key */
  12227. static const int insertKey; /**< key-code for the insert key */
  12228. static const int upKey; /**< key-code for the cursor-up key */
  12229. static const int downKey; /**< key-code for the cursor-down key */
  12230. static const int leftKey; /**< key-code for the cursor-left key */
  12231. static const int rightKey; /**< key-code for the cursor-right key */
  12232. static const int pageUpKey; /**< key-code for the page-up key */
  12233. static const int pageDownKey; /**< key-code for the page-down key */
  12234. static const int homeKey; /**< key-code for the home key */
  12235. static const int endKey; /**< key-code for the end key */
  12236. static const int F1Key; /**< key-code for the F1 key */
  12237. static const int F2Key; /**< key-code for the F2 key */
  12238. static const int F3Key; /**< key-code for the F3 key */
  12239. static const int F4Key; /**< key-code for the F4 key */
  12240. static const int F5Key; /**< key-code for the F5 key */
  12241. static const int F6Key; /**< key-code for the F6 key */
  12242. static const int F7Key; /**< key-code for the F7 key */
  12243. static const int F8Key; /**< key-code for the F8 key */
  12244. static const int F9Key; /**< key-code for the F9 key */
  12245. static const int F10Key; /**< key-code for the F10 key */
  12246. static const int F11Key; /**< key-code for the F11 key */
  12247. static const int F12Key; /**< key-code for the F12 key */
  12248. static const int F13Key; /**< key-code for the F13 key */
  12249. static const int F14Key; /**< key-code for the F14 key */
  12250. static const int F15Key; /**< key-code for the F15 key */
  12251. static const int F16Key; /**< key-code for the F16 key */
  12252. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  12253. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  12254. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  12255. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  12256. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  12257. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  12258. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  12259. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  12260. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  12261. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  12262. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  12263. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  12264. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  12265. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  12266. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  12267. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  12268. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  12269. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  12270. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  12271. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  12272. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  12273. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  12274. juce_UseDebuggingNewOperator
  12275. private:
  12276. int keyCode;
  12277. ModifierKeys mods;
  12278. juce_wchar textCharacter;
  12279. };
  12280. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  12281. /********* End of inlined file: juce_KeyPress.h *********/
  12282. class Component;
  12283. /**
  12284. Receives callbacks when keys are pressed.
  12285. You can add a key listener to a component to be informed when that component
  12286. gets key events. See the Component::addListener method for more details.
  12287. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  12288. */
  12289. class JUCE_API KeyListener
  12290. {
  12291. public:
  12292. /** Destructor. */
  12293. virtual ~KeyListener() {}
  12294. /** Called to indicate that a key has been pressed.
  12295. If your implementation returns true, then the key event is considered to have
  12296. been consumed, and will not be passed on to any other components. If it returns
  12297. false, then the key will be passed to other components that might want to use it.
  12298. @param key the keystroke, including modifier keys
  12299. @param originatingComponent the component that received the key event
  12300. @see keyStateChanged, Component::keyPressed
  12301. */
  12302. virtual bool keyPressed (const KeyPress& key,
  12303. Component* originatingComponent) = 0;
  12304. /** Called when any key is pressed or released.
  12305. When this is called, classes that might be interested in
  12306. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  12307. check whether their key has changed.
  12308. If your implementation returns true, then the key event is considered to have
  12309. been consumed, and will not be passed on to any other components. If it returns
  12310. false, then the key will be passed to other components that might want to use it.
  12311. @param originatingComponent the component that received the key event
  12312. @param isKeyDown true if a key is being pressed, false if one is being released
  12313. @see KeyPress, Component::keyStateChanged
  12314. */
  12315. virtual bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  12316. private:
  12317. // (dummy method to cause a deliberate compile error - if you hit this, you need to update your
  12318. // subclass to use the new parameters to keyStateChanged)
  12319. virtual void keyStateChanged (Component*) {};
  12320. };
  12321. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  12322. /********* End of inlined file: juce_KeyListener.h *********/
  12323. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  12324. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12325. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12326. class Component;
  12327. /**
  12328. Controls the order in which focus moves between components.
  12329. The default algorithm used by this class to work out the order of traversal
  12330. is as follows:
  12331. - if two components both have an explicit focus order specified, then the
  12332. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  12333. method).
  12334. - any component with an explicit focus order greater than 0 comes before ones
  12335. that don't have an order specified.
  12336. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  12337. order.
  12338. If you need traversal in a more customised way, you can create a subclass
  12339. of KeyboardFocusTraverser that uses your own algorithm, and use
  12340. Component::createFocusTraverser() to create it.
  12341. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  12342. */
  12343. class JUCE_API KeyboardFocusTraverser
  12344. {
  12345. public:
  12346. KeyboardFocusTraverser();
  12347. /** Destructor. */
  12348. virtual ~KeyboardFocusTraverser();
  12349. /** Returns the component that should be given focus after the specified one
  12350. when moving "forwards".
  12351. The default implementation will return the next component which is to the
  12352. right of or below this one.
  12353. This may return 0 if there's no suitable candidate.
  12354. */
  12355. virtual Component* getNextComponent (Component* current);
  12356. /** Returns the component that should be given focus after the specified one
  12357. when moving "backwards".
  12358. The default implementation will return the next component which is to the
  12359. left of or above this one.
  12360. This may return 0 if there's no suitable candidate.
  12361. */
  12362. virtual Component* getPreviousComponent (Component* current);
  12363. /** Returns the component that should receive focus be default within the given
  12364. parent component.
  12365. The default implementation will just return the foremost child component that
  12366. wants focus.
  12367. This may return 0 if there's no suitable candidate.
  12368. */
  12369. virtual Component* getDefaultComponent (Component* parentComponent);
  12370. };
  12371. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  12372. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  12373. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  12374. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12375. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  12376. /********* Start of inlined file: juce_Graphics.h *********/
  12377. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  12378. #define __JUCE_GRAPHICS_JUCEHEADER__
  12379. /********* Start of inlined file: juce_Font.h *********/
  12380. #ifndef __JUCE_FONT_JUCEHEADER__
  12381. #define __JUCE_FONT_JUCEHEADER__
  12382. /********* Start of inlined file: juce_Typeface.h *********/
  12383. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  12384. #define __JUCE_TYPEFACE_JUCEHEADER__
  12385. /********* Start of inlined file: juce_Path.h *********/
  12386. #ifndef __JUCE_PATH_JUCEHEADER__
  12387. #define __JUCE_PATH_JUCEHEADER__
  12388. /********* Start of inlined file: juce_AffineTransform.h *********/
  12389. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12390. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12391. /**
  12392. Represents a 2D affine-transformation matrix.
  12393. An affine transformation is a transformation such as a rotation, scale, shear,
  12394. resize or translation.
  12395. These are used for various 2D transformation tasks, e.g. with Path objects.
  12396. @see Path, Point, Line
  12397. */
  12398. class JUCE_API AffineTransform
  12399. {
  12400. public:
  12401. /** Creates an identity transform. */
  12402. AffineTransform() throw();
  12403. /** Creates a copy of another transform. */
  12404. AffineTransform (const AffineTransform& other) throw();
  12405. /** Creates a transform from a set of raw matrix values.
  12406. The resulting matrix is:
  12407. (mat00 mat01 mat02)
  12408. (mat10 mat11 mat12)
  12409. ( 0 0 1 )
  12410. */
  12411. AffineTransform (const float mat00, const float mat01, const float mat02,
  12412. const float mat10, const float mat11, const float mat12) throw();
  12413. /** Copies from another AffineTransform object */
  12414. const AffineTransform& operator= (const AffineTransform& other) throw();
  12415. /** Compares two transforms. */
  12416. bool operator== (const AffineTransform& other) const throw();
  12417. /** Compares two transforms. */
  12418. bool operator!= (const AffineTransform& other) const throw();
  12419. /** A ready-to-use identity transform, which you can use to append other
  12420. transformations to.
  12421. e.g. @code
  12422. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  12423. .scaled (2.0f);
  12424. @endcode
  12425. */
  12426. static const AffineTransform identity;
  12427. /** Transforms a 2D co-ordinate using this matrix. */
  12428. void transformPoint (float& x,
  12429. float& y) const throw();
  12430. /** Transforms a 2D co-ordinate using this matrix. */
  12431. void transformPoint (double& x,
  12432. double& y) const throw();
  12433. /** Returns a new transform which is the same as this one followed by a translation. */
  12434. const AffineTransform translated (const float deltaX,
  12435. const float deltaY) const throw();
  12436. /** Returns a new transform which is a translation. */
  12437. static const AffineTransform translation (const float deltaX,
  12438. const float deltaY) throw();
  12439. /** Returns a transform which is the same as this one followed by a rotation.
  12440. The rotation is specified by a number of radians to rotate clockwise, centred around
  12441. the origin (0, 0).
  12442. */
  12443. const AffineTransform rotated (const float angleInRadians) const throw();
  12444. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  12445. The rotation is specified by a number of radians to rotate clockwise, centred around
  12446. the co-ordinates passed in.
  12447. */
  12448. const AffineTransform rotated (const float angleInRadians,
  12449. const float pivotX,
  12450. const float pivotY) const throw();
  12451. /** Returns a new transform which is a rotation about (0, 0). */
  12452. static const AffineTransform rotation (const float angleInRadians) throw();
  12453. /** Returns a new transform which is a rotation about a given point. */
  12454. static const AffineTransform rotation (const float angleInRadians,
  12455. const float pivotX,
  12456. const float pivotY) throw();
  12457. /** Returns a transform which is the same as this one followed by a re-scaling.
  12458. The scaling is centred around the origin (0, 0).
  12459. */
  12460. const AffineTransform scaled (const float factorX,
  12461. const float factorY) const throw();
  12462. /** Returns a new transform which is a re-scale about the origin. */
  12463. static const AffineTransform scale (const float factorX,
  12464. const float factorY) throw();
  12465. /** Returns a transform which is the same as this one followed by a shear.
  12466. The shear is centred around the origin (0, 0).
  12467. */
  12468. const AffineTransform sheared (const float shearX,
  12469. const float shearY) const throw();
  12470. /** Returns a matrix which is the inverse operation of this one.
  12471. Some matrices don't have an inverse - in this case, the method will just return
  12472. an identity transform.
  12473. */
  12474. const AffineTransform inverted() const throw();
  12475. /** Returns the result of concatenating another transformation after this one. */
  12476. const AffineTransform followedBy (const AffineTransform& other) const throw();
  12477. /** Returns true if this transform has no effect on points. */
  12478. bool isIdentity() const throw();
  12479. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  12480. bool isSingularity() const throw();
  12481. juce_UseDebuggingNewOperator
  12482. /* The transform matrix is:
  12483. (mat00 mat01 mat02)
  12484. (mat10 mat11 mat12)
  12485. ( 0 0 1 )
  12486. */
  12487. float mat00, mat01, mat02;
  12488. float mat10, mat11, mat12;
  12489. private:
  12490. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  12491. const float mat10, const float mat11, const float mat12) const throw();
  12492. };
  12493. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  12494. /********* End of inlined file: juce_AffineTransform.h *********/
  12495. /********* Start of inlined file: juce_Point.h *********/
  12496. #ifndef __JUCE_POINT_JUCEHEADER__
  12497. #define __JUCE_POINT_JUCEHEADER__
  12498. /**
  12499. A pair of (x, y) co-ordinates.
  12500. Uses 32-bit floating point accuracy.
  12501. @see Line, Path, AffineTransform
  12502. */
  12503. class JUCE_API Point
  12504. {
  12505. public:
  12506. /** Creates a point with co-ordinates (0, 0). */
  12507. Point() throw();
  12508. /** Creates a copy of another point. */
  12509. Point (const Point& other) throw();
  12510. /** Creates a point from an (x, y) position. */
  12511. Point (const float x, const float y) throw();
  12512. /** Copies this point from another one.
  12513. @see setXY
  12514. */
  12515. const Point& operator= (const Point& other) throw();
  12516. /** Destructor. */
  12517. ~Point() throw();
  12518. /** Returns the point's x co-ordinate. */
  12519. inline float getX() const throw() { return x; }
  12520. /** Returns the point's y co-ordinate. */
  12521. inline float getY() const throw() { return y; }
  12522. /** Changes the point's x and y co-ordinates. */
  12523. void setXY (const float x,
  12524. const float y) throw();
  12525. /** Uses a transform to change the point's co-ordinates.
  12526. @see AffineTransform::transformPoint
  12527. */
  12528. void applyTransform (const AffineTransform& transform) throw();
  12529. juce_UseDebuggingNewOperator
  12530. private:
  12531. float x, y;
  12532. };
  12533. #endif // __JUCE_POINT_JUCEHEADER__
  12534. /********* End of inlined file: juce_Point.h *********/
  12535. /********* Start of inlined file: juce_Justification.h *********/
  12536. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  12537. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  12538. /**
  12539. Represents a type of justification to be used when positioning graphical items.
  12540. e.g. it indicates whether something should be placed top-left, top-right,
  12541. centred, etc.
  12542. It is used in various places wherever this kind of information is needed.
  12543. */
  12544. class JUCE_API Justification
  12545. {
  12546. public:
  12547. /** Creates a Justification object using a combination of flags. */
  12548. inline Justification (const int flags_) throw() : flags (flags_) {}
  12549. /** Creates a copy of another Justification object. */
  12550. Justification (const Justification& other) throw();
  12551. /** Copies another Justification object. */
  12552. const Justification& operator= (const Justification& other) throw();
  12553. /** Returns the raw flags that are set for this Justification object. */
  12554. inline int getFlags() const throw() { return flags; }
  12555. /** Tests a set of flags for this object.
  12556. @returns true if any of the flags passed in are set on this object.
  12557. */
  12558. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12559. /** Returns just the flags from this object that deal with vertical layout. */
  12560. int getOnlyVerticalFlags() const throw();
  12561. /** Returns just the flags from this object that deal with horizontal layout. */
  12562. int getOnlyHorizontalFlags() const throw();
  12563. /** Adjusts the position of a rectangle to fit it into a space.
  12564. The (x, y) position of the rectangle will be updated to position it inside the
  12565. given space according to the justification flags.
  12566. */
  12567. void applyToRectangle (int& x, int& y,
  12568. const int w, const int h,
  12569. const int spaceX, const int spaceY,
  12570. const int spaceW, const int spaceH) const throw();
  12571. /** Flag values that can be combined and used in the constructor. */
  12572. enum
  12573. {
  12574. /** Indicates that the item should be aligned against the left edge of the available space. */
  12575. left = 1,
  12576. /** Indicates that the item should be aligned against the right edge of the available space. */
  12577. right = 2,
  12578. /** Indicates that the item should be placed in the centre between the left and right
  12579. sides of the available space. */
  12580. horizontallyCentred = 4,
  12581. /** Indicates that the item should be aligned against the top edge of the available space. */
  12582. top = 8,
  12583. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  12584. bottom = 16,
  12585. /** Indicates that the item should be placed in the centre between the top and bottom
  12586. sides of the available space. */
  12587. verticallyCentred = 32,
  12588. /** Indicates that lines of text should be spread out to fill the maximum width
  12589. available, so that both margins are aligned vertically.
  12590. */
  12591. horizontallyJustified = 64,
  12592. /** Indicates that the item should be centred vertically and horizontally.
  12593. This is equivalent to (horizontallyCentred | verticallyCentred)
  12594. */
  12595. centred = 36,
  12596. /** Indicates that the item should be centred vertically but placed on the left hand side.
  12597. This is equivalent to (left | verticallyCentred)
  12598. */
  12599. centredLeft = 33,
  12600. /** Indicates that the item should be centred vertically but placed on the right hand side.
  12601. This is equivalent to (right | verticallyCentred)
  12602. */
  12603. centredRight = 34,
  12604. /** Indicates that the item should be centred horizontally and placed at the top.
  12605. This is equivalent to (horizontallyCentred | top)
  12606. */
  12607. centredTop = 12,
  12608. /** Indicates that the item should be centred horizontally and placed at the bottom.
  12609. This is equivalent to (horizontallyCentred | bottom)
  12610. */
  12611. centredBottom = 20,
  12612. /** Indicates that the item should be placed in the top-left corner.
  12613. This is equivalent to (left | top)
  12614. */
  12615. topLeft = 9,
  12616. /** Indicates that the item should be placed in the top-right corner.
  12617. This is equivalent to (right | top)
  12618. */
  12619. topRight = 10,
  12620. /** Indicates that the item should be placed in the bottom-left corner.
  12621. This is equivalent to (left | bottom)
  12622. */
  12623. bottomLeft = 17,
  12624. /** Indicates that the item should be placed in the bottom-left corner.
  12625. This is equivalent to (right | bottom)
  12626. */
  12627. bottomRight = 18
  12628. };
  12629. private:
  12630. int flags;
  12631. };
  12632. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  12633. /********* End of inlined file: juce_Justification.h *********/
  12634. /**
  12635. A path is a sequence of lines and curves that may either form a closed shape
  12636. or be open-ended.
  12637. To use a path, you can create an empty one, then add lines and curves to it
  12638. to create shapes, then it can be rendered by a Graphics context or used
  12639. for geometric operations.
  12640. e.g. @code
  12641. Path myPath;
  12642. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  12643. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  12644. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  12645. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  12646. // add an ellipse as well, which will form a second sub-path within the path..
  12647. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  12648. // double the width of the whole thing..
  12649. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  12650. // and draw it to a graphics context with a 5-pixel thick outline.
  12651. g.strokePath (myPath, PathStrokeType (5.0f));
  12652. @endcode
  12653. A path object can actually contain multiple sub-paths, which may themselves
  12654. be open or closed.
  12655. @see PathFlatteningIterator, PathStrokeType, Graphics
  12656. */
  12657. class JUCE_API Path : private ArrayAllocationBase <float>
  12658. {
  12659. public:
  12660. /** Creates an empty path. */
  12661. Path() throw();
  12662. /** Creates a copy of another path. */
  12663. Path (const Path& other) throw();
  12664. /** Destructor. */
  12665. ~Path() throw();
  12666. /** Copies this path from another one. */
  12667. const Path& operator= (const Path& other) throw();
  12668. /** Returns true if the path doesn't contain any lines or curves. */
  12669. bool isEmpty() const throw();
  12670. /** Returns the smallest rectangle that contains all points within the path.
  12671. */
  12672. void getBounds (float& x, float& y,
  12673. float& w, float& h) const throw();
  12674. /** Returns the smallest rectangle that contains all points within the path
  12675. after it's been transformed with the given tranasform matrix.
  12676. */
  12677. void getBoundsTransformed (const AffineTransform& transform,
  12678. float& x, float& y,
  12679. float& w, float& h) const throw();
  12680. /** Checks whether a point lies within the path.
  12681. This is only relevent for closed paths (see closeSubPath()), and
  12682. may produce false results if used on a path which has open sub-paths.
  12683. The path's winding rule is taken into account by this method.
  12684. The tolerence parameter is passed to the PathFlatteningIterator that
  12685. is used to trace the path - for more info about it, see the notes for
  12686. the PathFlatteningIterator constructor.
  12687. @see closeSubPath, setUsingNonZeroWinding
  12688. */
  12689. bool contains (const float x,
  12690. const float y,
  12691. const float tolerence = 10.0f) const throw();
  12692. /** Checks whether a line crosses the path.
  12693. This will return positive if the line crosses any of the paths constituent
  12694. lines or curves. It doesn't take into account whether the line is inside
  12695. or outside the path, or whether the path is open or closed.
  12696. The tolerence parameter is passed to the PathFlatteningIterator that
  12697. is used to trace the path - for more info about it, see the notes for
  12698. the PathFlatteningIterator constructor.
  12699. */
  12700. bool intersectsLine (const float x1, const float y1,
  12701. const float x2, const float y2,
  12702. const float tolerence = 10.0f) throw();
  12703. /** Removes all lines and curves, resetting the path completely. */
  12704. void clear() throw();
  12705. /** Begins a new subpath with a given starting position.
  12706. This will move the path's current position to the co-ordinates passed in and
  12707. make it ready to draw lines or curves starting from this position.
  12708. After adding whatever lines and curves are needed, you can either
  12709. close the current sub-path using closeSubPath() or call startNewSubPath()
  12710. to move to a new sub-path, leaving the old one open-ended.
  12711. @see lineTo, quadraticTo, cubicTo, closeSubPath
  12712. */
  12713. void startNewSubPath (const float startX,
  12714. const float startY) throw();
  12715. /** Closes a the current sub-path with a line back to its start-point.
  12716. When creating a closed shape such as a triangle, don't use 3 lineTo()
  12717. calls - instead use two lineTo() calls, followed by a closeSubPath()
  12718. to join the final point back to the start.
  12719. This ensures that closes shapes are recognised as such, and this is
  12720. important for tasks like drawing strokes, which needs to know whether to
  12721. draw end-caps or not.
  12722. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  12723. */
  12724. void closeSubPath() throw();
  12725. /** Adds a line from the shape's last position to a new end-point.
  12726. This will connect the end-point of the last line or curve that was added
  12727. to a new point, using a straight line.
  12728. See the class description for an example of how to add lines and curves to a path.
  12729. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  12730. */
  12731. void lineTo (const float endX,
  12732. const float endY) throw();
  12733. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  12734. This will connect the end-point of the last line or curve that was added
  12735. to a new point, using a quadratic spline with one control-point.
  12736. See the class description for an example of how to add lines and curves to a path.
  12737. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  12738. */
  12739. void quadraticTo (const float controlPointX,
  12740. const float controlPointY,
  12741. const float endPointX,
  12742. const float endPointY) throw();
  12743. /** Adds a cubic bezier curve from the shape's last position to a new position.
  12744. This will connect the end-point of the last line or curve that was added
  12745. to a new point, using a cubic spline with two control-points.
  12746. See the class description for an example of how to add lines and curves to a path.
  12747. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  12748. */
  12749. void cubicTo (const float controlPoint1X,
  12750. const float controlPoint1Y,
  12751. const float controlPoint2X,
  12752. const float controlPoint2Y,
  12753. const float endPointX,
  12754. const float endPointY) throw();
  12755. /** Returns the last point that was added to the path by one of the drawing methods.
  12756. */
  12757. const Point getCurrentPosition() const;
  12758. /** Adds a rectangle to the path.
  12759. The rectangle is added as a new sub-path. (Any currently open paths will be
  12760. left open).
  12761. @see addRoundedRectangle, addTriangle
  12762. */
  12763. void addRectangle (const float x, const float y,
  12764. const float w, const float h) throw();
  12765. /** Adds a rectangle with rounded corners to the path.
  12766. The rectangle is added as a new sub-path. (Any currently open paths will be
  12767. left open).
  12768. @see addRectangle, addTriangle
  12769. */
  12770. void addRoundedRectangle (const float x, const float y,
  12771. const float w, const float h,
  12772. float cornerSize) throw();
  12773. /** Adds a rectangle with rounded corners to the path.
  12774. The rectangle is added as a new sub-path. (Any currently open paths will be
  12775. left open).
  12776. @see addRectangle, addTriangle
  12777. */
  12778. void addRoundedRectangle (const float x, const float y,
  12779. const float w, const float h,
  12780. float cornerSizeX,
  12781. float cornerSizeY) throw();
  12782. /** Adds a triangle to the path.
  12783. The triangle is added as a new closed sub-path. (Any currently open paths will be
  12784. left open).
  12785. Note that whether the vertices are specified in clockwise or anticlockwise
  12786. order will affect how the triangle is filled when it overlaps other
  12787. shapes (the winding order setting will affect this of course).
  12788. */
  12789. void addTriangle (const float x1, const float y1,
  12790. const float x2, const float y2,
  12791. const float x3, const float y3) throw();
  12792. /** Adds a quadrilateral to the path.
  12793. The quad is added as a new closed sub-path. (Any currently open paths will be
  12794. left open).
  12795. Note that whether the vertices are specified in clockwise or anticlockwise
  12796. order will affect how the quad is filled when it overlaps other
  12797. shapes (the winding order setting will affect this of course).
  12798. */
  12799. void addQuadrilateral (const float x1, const float y1,
  12800. const float x2, const float y2,
  12801. const float x3, const float y3,
  12802. const float x4, const float y4) throw();
  12803. /** Adds an ellipse to the path.
  12804. The shape is added as a new sub-path. (Any currently open paths will be
  12805. left open).
  12806. @see addArc
  12807. */
  12808. void addEllipse (const float x, const float y,
  12809. const float width, const float height) throw();
  12810. /** Adds an elliptical arc to the current path.
  12811. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12812. or anti-clockwise according to whether the end angle is greater than the start. This means
  12813. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12814. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12815. @param y the top edge of the rectangle in which the elliptical outline fits
  12816. @param width the width of the rectangle in which the elliptical outline fits
  12817. @param height the height of the rectangle in which the elliptical outline fits
  12818. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12819. top-centre of the ellipse)
  12820. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12821. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12822. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12823. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12824. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12825. it will be added to the current sub-path, continuing from the current postition
  12826. @see addCentredArc, arcTo, addPieSegment, addEllipse
  12827. */
  12828. void addArc (const float x, const float y,
  12829. const float width, const float height,
  12830. const float fromRadians,
  12831. const float toRadians,
  12832. const bool startAsNewSubPath = false) throw();
  12833. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  12834. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12835. or anti-clockwise according to whether the end angle is greater than the start. This means
  12836. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12837. @param centreX the centre x of the ellipse
  12838. @param centreY the centre y of the ellipse
  12839. @param radiusX the horizontal radius of the ellipse
  12840. @param radiusY the vertical radius of the ellipse
  12841. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  12842. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12843. top-centre of the ellipse)
  12844. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12845. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  12846. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  12847. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  12848. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  12849. it will be added to the current sub-path, continuing from the current postition
  12850. @see addArc, arcTo
  12851. */
  12852. void addCentredArc (const float centreX, const float centreY,
  12853. const float radiusX, const float radiusY,
  12854. const float rotationOfEllipse,
  12855. const float fromRadians,
  12856. const float toRadians,
  12857. const bool startAsNewSubPath = false) throw();
  12858. /** Adds a "pie-chart" shape to the path.
  12859. The shape is added as a new sub-path. (Any currently open paths will be
  12860. left open).
  12861. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  12862. or anti-clockwise according to whether the end angle is greater than the start. This means
  12863. that sometimes you may need to use values greater than 2*Pi for the end angle.
  12864. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  12865. @param y the top edge of the rectangle in which the elliptical outline fits
  12866. @param width the width of the rectangle in which the elliptical outline fits
  12867. @param height the height of the rectangle in which the elliptical outline fits
  12868. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  12869. top-centre of the ellipse)
  12870. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  12871. top-centre of the ellipse)
  12872. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  12873. ellipse at its centre, where this value indicates the inner ellipse's size with
  12874. respect to the outer one.
  12875. @see addArc
  12876. */
  12877. void addPieSegment (const float x, const float y,
  12878. const float width, const float height,
  12879. const float fromRadians,
  12880. const float toRadians,
  12881. const float innerCircleProportionalSize);
  12882. /** Adds a line with a specified thickness.
  12883. The line is added as a new closed sub-path. (Any currently open paths will be
  12884. left open).
  12885. @see addArrow
  12886. */
  12887. void addLineSegment (const float startX, const float startY,
  12888. const float endX, const float endY,
  12889. float lineThickness) throw();
  12890. /** Adds a line with an arrowhead on the end.
  12891. The arrow is added as a new closed sub-path. (Any currently open paths will be
  12892. left open).
  12893. */
  12894. void addArrow (const float startX, const float startY,
  12895. const float endX, const float endY,
  12896. float lineThickness,
  12897. float arrowheadWidth,
  12898. float arrowheadLength) throw();
  12899. /** Adds a star shape to the path.
  12900. */
  12901. void addStar (const float centreX,
  12902. const float centreY,
  12903. const int numberOfPoints,
  12904. const float innerRadius,
  12905. const float outerRadius,
  12906. const float startAngle = 0.0f);
  12907. /** Adds a speech-bubble shape to the path.
  12908. @param bodyX the left of the main body area of the bubble
  12909. @param bodyY the top of the main body area of the bubble
  12910. @param bodyW the width of the main body area of the bubble
  12911. @param bodyH the height of the main body area of the bubble
  12912. @param cornerSize the amount by which to round off the corners of the main body rectangle
  12913. @param arrowTipX the x position that the tip of the arrow should connect to
  12914. @param arrowTipY the y position that the tip of the arrow should connect to
  12915. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  12916. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  12917. arrow's base should be - this is a proportional distance between 0 and 1.0
  12918. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  12919. */
  12920. void addBubble (float bodyX, float bodyY,
  12921. float bodyW, float bodyH,
  12922. float cornerSize,
  12923. float arrowTipX,
  12924. float arrowTipY,
  12925. int whichSide,
  12926. float arrowPositionAlongEdgeProportional,
  12927. float arrowWidth);
  12928. /** Adds another path to this one.
  12929. The new path is added as a new sub-path. (Any currently open paths in this
  12930. path will be left open).
  12931. @param pathToAppend the path to add
  12932. */
  12933. void addPath (const Path& pathToAppend) throw();
  12934. /** Adds another path to this one, transforming it on the way in.
  12935. The new path is added as a new sub-path, its points being transformed by the given
  12936. matrix before being added.
  12937. @param pathToAppend the path to add
  12938. @param transformToApply an optional transform to apply to the incoming vertices
  12939. */
  12940. void addPath (const Path& pathToAppend,
  12941. const AffineTransform& transformToApply) throw();
  12942. /** Swaps the contents of this path with another one.
  12943. The internal data of the two paths is swapped over, so this is much faster than
  12944. copying it to a temp variable and back.
  12945. */
  12946. void swapWithPath (Path& other);
  12947. /** Applies a 2D transform to all the vertices in the path.
  12948. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  12949. */
  12950. void applyTransform (const AffineTransform& transform) throw();
  12951. /** Rescales this path to make it fit neatly into a given space.
  12952. This is effectively a quick way of calling
  12953. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  12954. @param x the x position of the rectangle to fit the path inside
  12955. @param y the y position of the rectangle to fit the path inside
  12956. @param width the width of the rectangle to fit the path inside
  12957. @param height the height of the rectangle to fit the path inside
  12958. @param preserveProportions if true, it will fit the path into the space without altering its
  12959. horizontal/vertical scale ratio; if false, it will distort the
  12960. path to fill the specified ratio both horizontally and vertically
  12961. @see applyTransform, getTransformToScaleToFit
  12962. */
  12963. void scaleToFit (const float x, const float y,
  12964. const float width, const float height,
  12965. const bool preserveProportions) throw();
  12966. /** Returns a transform that can be used to rescale the path to fit into a given space.
  12967. @param x the x position of the rectangle to fit the path inside
  12968. @param y the y position of the rectangle to fit the path inside
  12969. @param width the width of the rectangle to fit the path inside
  12970. @param height the height of the rectangle to fit the path inside
  12971. @param preserveProportions if true, it will fit the path into the space without altering its
  12972. horizontal/vertical scale ratio; if false, it will distort the
  12973. path to fill the specified ratio both horizontally and vertically
  12974. @param justificationType if the proportions are preseved, the resultant path may be smaller
  12975. than the available rectangle, so this describes how it should be
  12976. positioned within the space.
  12977. @returns an appropriate transformation
  12978. @see applyTransform, scaleToFit
  12979. */
  12980. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  12981. const float width, const float height,
  12982. const bool preserveProportions,
  12983. const Justification& justificationType = Justification::centred) const throw();
  12984. /** Creates a version of this path where all sharp corners have been replaced by curves.
  12985. Wherever two lines meet at an angle, this will replace the corner with a curve
  12986. of the given radius.
  12987. */
  12988. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  12989. /** Changes the winding-rule to be used when filling the path.
  12990. If set to true (which is the default), then the path uses a non-zero-winding rule
  12991. to determine which points are inside the path. If set to false, it uses an
  12992. alternate-winding rule.
  12993. The winding-rule comes into play when areas of the shape overlap other
  12994. areas, and determines whether the overlapping regions are considered to be
  12995. inside or outside.
  12996. Changing this value just sets a flag - it doesn't affect the contents of the
  12997. path.
  12998. @see isUsingNonZeroWinding
  12999. */
  13000. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  13001. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  13002. The default for a new path is true.
  13003. @see setUsingNonZeroWinding
  13004. */
  13005. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  13006. /** Iterates the lines and curves that a path contains.
  13007. @see Path, PathFlatteningIterator
  13008. */
  13009. class JUCE_API Iterator
  13010. {
  13011. public:
  13012. Iterator (const Path& path);
  13013. ~Iterator();
  13014. /** Moves onto the next element in the path.
  13015. If this returns false, there are no more elements. If it returns true,
  13016. the elementType variable will be set to the type of the current element,
  13017. and some of the x and y variables will be filled in with values.
  13018. */
  13019. bool next();
  13020. enum PathElementType
  13021. {
  13022. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  13023. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  13024. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  13025. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  13026. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  13027. };
  13028. PathElementType elementType;
  13029. float x1, y1, x2, y2, x3, y3;
  13030. private:
  13031. const Path& path;
  13032. int index;
  13033. Iterator (const Iterator&);
  13034. const Iterator& operator= (const Iterator&);
  13035. };
  13036. /** Loads a stored path from a data stream.
  13037. The data in the stream must have been written using writePathToStream().
  13038. Note that this will append the stored path to whatever is currently in
  13039. this path, so you might need to call clear() beforehand.
  13040. @see loadPathFromData, writePathToStream
  13041. */
  13042. void loadPathFromStream (InputStream& source);
  13043. /** Loads a stored path from a block of data.
  13044. This is similar to loadPathFromStream(), but just reads from a block
  13045. of data. Useful if you're including stored shapes in your code as a
  13046. block of static data.
  13047. @see loadPathFromStream, writePathToStream
  13048. */
  13049. void loadPathFromData (const unsigned char* const data,
  13050. const int numberOfBytes) throw();
  13051. /** Stores the path by writing it out to a stream.
  13052. After writing out a path, you can reload it using loadPathFromStream().
  13053. @see loadPathFromStream, loadPathFromData
  13054. */
  13055. void writePathToStream (OutputStream& destination) const;
  13056. /** Creates a string containing a textual representation of this path.
  13057. @see restoreFromString
  13058. */
  13059. const String toString() const;
  13060. /** Restores this path from a string that was created with the toString() method.
  13061. @see toString()
  13062. */
  13063. void restoreFromString (const String& stringVersion);
  13064. juce_UseDebuggingNewOperator
  13065. private:
  13066. friend class PathFlatteningIterator;
  13067. friend class Path::Iterator;
  13068. int numElements;
  13069. float pathXMin, pathXMax, pathYMin, pathYMax;
  13070. bool useNonZeroWinding;
  13071. static const float lineMarker;
  13072. static const float moveMarker;
  13073. static const float quadMarker;
  13074. static const float cubicMarker;
  13075. static const float closeSubPathMarker;
  13076. };
  13077. #endif // __JUCE_PATH_JUCEHEADER__
  13078. /********* End of inlined file: juce_Path.h *********/
  13079. class Font;
  13080. class Typeface;
  13081. /**
  13082. Stores information about the shape and kerning of one of the glyphs in a Typeface.
  13083. @see Typeface, PositionedGlyph, GlyphArrangement
  13084. */
  13085. class JUCE_API TypefaceGlyphInfo
  13086. {
  13087. public:
  13088. /** Returns the path that describes the glyph's outline.
  13089. This is normalised to a height of 1.0, and its origin is the
  13090. left-hand edge of the glyph's baseline.
  13091. */
  13092. const Path& getPath() const throw() { return path; }
  13093. /** Returns the unicode character that this glyph represents. */
  13094. juce_wchar getCharacter() const throw() { return character; }
  13095. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  13096. /** Returns the distance to leave between this and a following character.
  13097. The value returned is expressed as a proportion of the font's height.
  13098. */
  13099. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw();
  13100. /** Returns the typeface that this glyph belongs to. */
  13101. Typeface* getTypeface() const throw() { return typeface; }
  13102. private:
  13103. friend class Typeface;
  13104. struct KerningPair
  13105. {
  13106. juce_wchar character2;
  13107. float kerningAmount;
  13108. };
  13109. const juce_wchar character;
  13110. const Path path;
  13111. float width;
  13112. MemoryBlock kerningPairs;
  13113. Typeface* const typeface;
  13114. TypefaceGlyphInfo (const juce_wchar character,
  13115. const Path& shape,
  13116. const float horizontalSeparation,
  13117. Typeface* const typeface) throw();
  13118. ~TypefaceGlyphInfo() throw();
  13119. KerningPair& getKerningPair (const int index) const throw();
  13120. int getNumKerningPairs() const throw();
  13121. void addKerningPair (const juce_wchar subsequentCharacter,
  13122. const float extraKerningAmount) throw();
  13123. const TypefaceGlyphInfo& operator= (const TypefaceGlyphInfo&);
  13124. };
  13125. /**
  13126. Represents a size-independent system font.
  13127. A Font object represents a particular Typeface along with a specific size,
  13128. style, kerning, scale, etc, wheras the Typeface is just a generalised description
  13129. of the shapes of the glyphs and their properties.
  13130. */
  13131. class JUCE_API Typeface : public ReferenceCountedObject
  13132. {
  13133. public:
  13134. /** Tries to load a named system font and to initialise all the glyphs
  13135. appropriately from it.
  13136. @param faceName the name of the typeface, e.g. "Times"
  13137. @param bold whether to try to find a bold version of the font (may not always be available)
  13138. @param italic whether to try to find an italicised version of the font (may not always be available)
  13139. */
  13140. Typeface (const String& faceName,
  13141. const bool bold,
  13142. const bool italic);
  13143. /** Creates a copy of another typeface */
  13144. Typeface (const Typeface& other);
  13145. /** Destructor. */
  13146. ~Typeface();
  13147. /** Copies another typeface over this one. */
  13148. const Typeface& operator= (const Typeface& other) throw();
  13149. /** Returns a unique ID for the typeface.
  13150. This is based on the name and style, so can be used to compare two Typeface objects.
  13151. */
  13152. int hashCode() const throw() { return hash; }
  13153. /** Returns the name of the typeface, e.g. "Times", "Verdana", etc */
  13154. const String& getName() const throw() { return typefaceName; }
  13155. /** Returns the font's ascent as a proportion of its height. */
  13156. float getAscent() const throw() { return ascent; }
  13157. /** Returns true if the font is flagged as being bold. */
  13158. bool isBold() const throw() { return bold; }
  13159. /** Returns true if the typeface's 'italic' flag is set. */
  13160. bool isItalic() const throw() { return italic; }
  13161. /** Finds the Path that describes the outline shape of a character.
  13162. The height of the path is normalised to 1.0 (i.e. a distance of 1.0 is the
  13163. height of the font).
  13164. This may return 0 if the typeface has no characters, but if the character
  13165. that is asked for is not found, it will first try to return a default
  13166. character instead.
  13167. */
  13168. const Path* getOutlineForGlyph (const juce_wchar character) throw();
  13169. /** Tries to find the information describing a glyph for this character.
  13170. If there isn't a glyph specifically for the character it will return
  13171. a default glyph instead; if the typeface is empty, it may return a null
  13172. pointer.
  13173. */
  13174. const TypefaceGlyphInfo* getGlyph (const juce_wchar character) throw();
  13175. /** Deletes all the glyphs and kerning data fom the typeface. */
  13176. void clear() throw();
  13177. /** Adds a glyph to the typeface.
  13178. This is typically only called by the platform-specific code that generates
  13179. the typeface from a system font.
  13180. */
  13181. void addGlyph (const juce_wchar character,
  13182. const Path& path,
  13183. const float horizontalSpacing) throw();
  13184. /** Adds a kerning distance to the typeface.
  13185. The extra amount passed in is expressed as a proportion of the font's
  13186. height, normalised to 1.0.
  13187. This is typically only called by the platform-specific code that generates
  13188. the typeface from a system font.
  13189. */
  13190. void addKerningPair (const juce_wchar firstChar,
  13191. const juce_wchar secondChar,
  13192. const float extraAmount) throw();
  13193. /** Sets the typeface's name.
  13194. This is typically only called by the platform-specific code that generates
  13195. the typeface from a system font. Calling this method won't actually affect
  13196. the underlying font being used.
  13197. */
  13198. void setName (const String& name) throw();
  13199. /** Sets the font's ascent value, as a proportion of the font height.
  13200. This is typically only called by the platform-specific code that generates
  13201. the typeface from a system font.
  13202. */
  13203. void setAscent (const float newAscent) throw();
  13204. /** Sets the typeface's 'bold' flag.
  13205. This is typically only called by the platform-specific code that generates
  13206. the typeface from a system font.
  13207. */
  13208. void setBold (const bool shouldBeBold) throw();
  13209. /** Sets the typeface's 'italic' flag.
  13210. This is typically only called by the platform-specific code that generates
  13211. the typeface from a system font.
  13212. */
  13213. void setItalic (const bool shouldBeItalic) throw();
  13214. /** Changes the character index to use as the default character.
  13215. This is the character that gets returned for characters which don't have a
  13216. glyph set for them.
  13217. */
  13218. void setDefaultCharacter (const juce_wchar newDefaultCharacter) throw();
  13219. /** Creates a typeface from data created using Typeface::serialise().
  13220. This will attempt to load a compressed typeface that was created using
  13221. the Typeface::serialise() method. This is handy if you want to store
  13222. a typeface in your application as a binary blob, and use it without
  13223. having to actually install it on the computer.
  13224. @see Typeface::serialise()
  13225. */
  13226. Typeface (InputStream& serialisedTypefaceStream);
  13227. /** Writes the typeface to a stream (using a proprietary format).
  13228. This lets you save a typeface and reload it using the
  13229. Typeface::Typeface (InputStream&) constructor. The data's saved in
  13230. a compressed format.
  13231. @see Typeface::Typeface (InputStream&)
  13232. */
  13233. void serialise (OutputStream& outputStream);
  13234. /** A name that represents the default sans-serif typeface name.
  13235. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13236. is a generic string that represents whatever that font is, such as "DefaultSans".
  13237. If you try to create a typeface with this name, the global default LookAndFeel
  13238. object will be asked to provide an appropriate typeface.
  13239. */
  13240. static const tchar* defaultTypefaceNameSans;
  13241. /** A name that represents the default serif typeface name.
  13242. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13243. is a generic string that represents it, such as "DefaultSans".
  13244. If you try to create a typeface with this name, the global default LookAndFeel
  13245. object will be asked to provide an appropriate typeface.
  13246. */
  13247. static const tchar* defaultTypefaceNameSerif;
  13248. /** A name that represents the default monospaced typeface name.
  13249. Note that this is NOT the platform-specific typeface name (e.g. "Times"), but
  13250. is a generic string that represents it, such as "DefaultSans".
  13251. If you try to create a typeface with this name, the global default LookAndFeel
  13252. object will be asked to provide an appropriate typeface.
  13253. */
  13254. static const tchar* defaultTypefaceNameMono;
  13255. /** A handy typedef to make it easy to use ref counted pointers to this class. */
  13256. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  13257. juce_UseDebuggingNewOperator
  13258. private:
  13259. VoidArray glyphs;
  13260. short lookupTable [128];
  13261. String typefaceName;
  13262. int hash;
  13263. float ascent; // as a proportion of the height
  13264. bool bold, italic, isFullyPopulated;
  13265. juce_wchar defaultCharacter; // the char to use if a matching glyph can't be found.
  13266. Typeface() throw();
  13267. void addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw();
  13268. friend class Font;
  13269. friend class TypefaceCache;
  13270. friend class FontGlyphAlphaMap;
  13271. static const Ptr getTypefaceFor (const Font& font) throw();
  13272. // this is a platform-dependent method that will look for the given typeface
  13273. // and set up its kerning tables, etc. accordingly.
  13274. // If addAllGlyphsToFont is true, it should also add all the glyphs in the font
  13275. // to the typeface immediately, rather than having to add them later on-demand.
  13276. void initialiseTypefaceCharacteristics (const String& fontName,
  13277. bool bold, bool italic,
  13278. bool addAllGlyphsToFont) throw();
  13279. // platform-specific routine to look up and add a glyph to this typeface
  13280. bool findAndAddSystemGlyph (juce_wchar character) throw();
  13281. void updateHashCode() throw();
  13282. friend class LookAndFeel;
  13283. static void getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  13284. };
  13285. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  13286. /********* End of inlined file: juce_Typeface.h *********/
  13287. /**
  13288. Represents a particular font, including its size, style, etc.
  13289. Apart from the typeface to be used, a Font object also dictates whether
  13290. the font is bold, italic, underlined, how big it is, and its kerning and
  13291. horizontal scale factor.
  13292. @see Typeface
  13293. */
  13294. class JUCE_API Font
  13295. {
  13296. public:
  13297. /** A combination of these values is used by the constructor to specify the
  13298. style of font to use.
  13299. */
  13300. enum FontStyleFlags
  13301. {
  13302. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  13303. bold = 1, /**< boldens the font. @see setStyleFlags */
  13304. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  13305. underlined = 4 /**< underlines the font. @see setStyleFlags */
  13306. };
  13307. /** Creates a sans-serif font in a given size.
  13308. @param fontHeight the height in pixels (can be fractional)
  13309. @param styleFlags the style to use - this can be a combination of the
  13310. Font::bold, Font::italic and Font::underlined, or
  13311. just Font::plain for the normal style.
  13312. @see FontStyleFlags, getDefaultSansSerifFontName
  13313. */
  13314. Font (const float fontHeight,
  13315. const int styleFlags = plain) throw();
  13316. /** Creates a font with a given typeface and parameters.
  13317. @param typefaceName the name of the typeface to use
  13318. @param fontHeight the height in pixels (can be fractional)
  13319. @param styleFlags the style to use - this can be a combination of the
  13320. Font::bold, Font::italic and Font::underlined, or
  13321. just Font::plain for the normal style.
  13322. @see FontStyleFlags, getDefaultSansSerifFontName
  13323. */
  13324. Font (const String& typefaceName,
  13325. const float fontHeight,
  13326. const int styleFlags) throw();
  13327. /** Creates a copy of another Font object. */
  13328. Font (const Font& other) throw();
  13329. /** Creates a font based on a typeface.
  13330. The font object stores its own internal copy of the typeface, so you can safely
  13331. delete the one passed in after calling this.
  13332. */
  13333. Font (const Typeface& typeface) throw();
  13334. /** Creates a basic sans-serif font at a default height.
  13335. You should use one of the other constructors for creating a font that you're planning
  13336. on drawing with - this constructor is here to help initialise objects before changing
  13337. the font's settings later.
  13338. */
  13339. Font() throw();
  13340. /** Copies this font from another one. */
  13341. const Font& operator= (const Font& other) throw();
  13342. bool operator== (const Font& other) const throw();
  13343. bool operator!= (const Font& other) const throw();
  13344. /** Destructor. */
  13345. ~Font() throw();
  13346. /** Changes the name of the typeface family.
  13347. e.g. "Arial", "Courier", etc.
  13348. This may also be set to Typeface::defaultTypefaceNameSans, Typeface::defaultTypefaceNameSerif,
  13349. or Typeface::defaultTypefaceNameMono, which are not actual platform-specific font names, but
  13350. are generic names that are used to represent the various default fonts.
  13351. If a suitable font isn't found on the machine, it'll just use a default instead.
  13352. */
  13353. void setTypefaceName (const String& faceName) throw();
  13354. /** Returns the name of the typeface family that this font uses.
  13355. e.g. "Arial", "Courier", etc.
  13356. Note that this may also be one of the values: Typeface::defaultTypefaceNameSans,
  13357. Typeface::defaultTypefaceNameSerif, or Typeface::defaultTypefaceNameMono, which are not actual
  13358. platform-specific font names, but are generic names that are used to represent the various
  13359. default fonts. If you need to know the exact typeface name being used, you can call
  13360. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  13361. */
  13362. const String& getTypefaceName() const throw() { return typefaceName; }
  13363. /** Returns a typeface name that represents the default sans-serif font.
  13364. This is also the typeface that will be used when a font is created without
  13365. specifying any typeface details.
  13366. Note that this method just returns the same value as Typeface::defaultTypefaceNameSans,
  13367. which is a generic placeholder string, and not a platform-specific font name.
  13368. @see Typeface::defaultTypefaceNameSans, setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName,
  13369. */
  13370. static const String getDefaultSansSerifFontName() throw() { return Typeface::defaultTypefaceNameSans; }
  13371. /** Returns a typeface name that represents the default sans-serif font.
  13372. Note that this method just returns the same value as Typeface::defaultTypefaceNameSerif,
  13373. which is a generic placeholder string, and not a platform-specific font name.
  13374. @see Typeface::defaultTypefaceNameSerif, setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  13375. */
  13376. static const String getDefaultSerifFontName() throw() { return Typeface::defaultTypefaceNameSerif; }
  13377. /** Returns a typeface name that represents the default sans-serif font.
  13378. Note that this method just returns the same value as Typeface::defaultTypefaceNameMono,
  13379. which is a generic placeholder string, and not a platform-specific font name.
  13380. @see Typeface::defaultTypefaceNameMono, setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  13381. */
  13382. static const String getDefaultMonospacedFontName() throw() { return Typeface::defaultTypefaceNameMono; }
  13383. /** Returns the total height of this font.
  13384. This is the maximum height, from the top of the ascent to the bottom of the
  13385. descenders.
  13386. @see setHeight, setHeightWithoutChangingWidth, getAscent
  13387. */
  13388. float getHeight() const throw() { return height; }
  13389. /** Changes the font's height.
  13390. @see getHeight, setHeightWithoutChangingWidth
  13391. */
  13392. void setHeight (float newHeight) throw();
  13393. /** Changes the font's height without changing its width.
  13394. This alters the horizontal scale to compensate for the change in height.
  13395. */
  13396. void setHeightWithoutChangingWidth (float newHeight) throw();
  13397. /** Returns the height of the font above its baseline.
  13398. This is the maximum height from the baseline to the top.
  13399. @see getHeight, getDescent
  13400. */
  13401. float getAscent() const throw();
  13402. /** Returns the amount that the font descends below its baseline.
  13403. This is calculated as (getHeight() - getAscent()).
  13404. @see getAscent, getHeight
  13405. */
  13406. float getDescent() const throw();
  13407. /** Returns the font's style flags.
  13408. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  13409. enum, to describe whether the font is bold, italic, etc.
  13410. @see FontStyleFlags
  13411. */
  13412. int getStyleFlags() const throw() { return styleFlags; }
  13413. /** Changes the font's style.
  13414. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  13415. enum, to set the font's properties
  13416. @see FontStyleFlags
  13417. */
  13418. void setStyleFlags (const int newFlags) throw();
  13419. /** Makes the font bold or non-bold. */
  13420. void setBold (const bool shouldBeBold) throw();
  13421. /** Returns true if the font is bold. */
  13422. bool isBold() const throw();
  13423. /** Makes the font italic or non-italic. */
  13424. void setItalic (const bool shouldBeItalic) throw();
  13425. /** Returns true if the font is italic. */
  13426. bool isItalic() const throw();
  13427. /** Makes the font underlined or non-underlined. */
  13428. void setUnderline (const bool shouldBeUnderlined) throw();
  13429. /** Returns true if the font is underlined. */
  13430. bool isUnderlined() const throw();
  13431. /** Changes the font's horizontal scale factor.
  13432. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  13433. narrower, greater than 1.0 will be stretched out.
  13434. */
  13435. void setHorizontalScale (const float scaleFactor) throw();
  13436. /** Returns the font's horizontal scale.
  13437. A value of 1.0 is the normal scale, less than this will be narrower, greater
  13438. than 1.0 will be stretched out.
  13439. @see setHorizontalScale
  13440. */
  13441. float getHorizontalScale() const throw() { return horizontalScale; }
  13442. /** Changes the font's kerning.
  13443. @param extraKerning a multiple of the font's height that will be added
  13444. to space between the characters. So a value of zero is
  13445. normal spacing, positive values spread the letters out,
  13446. negative values make them closer together.
  13447. */
  13448. void setExtraKerningFactor (const float extraKerning) throw();
  13449. /** Returns the font's kerning.
  13450. This is the extra space added between adjacent characters, as a proportion
  13451. of the font's height.
  13452. A value of zero is normal spacing, positive values will spread the letters
  13453. out more, and negative values make them closer together.
  13454. */
  13455. float getExtraKerningFactor() const throw() { return kerning; }
  13456. /** Changes all the font's characteristics with one call. */
  13457. void setSizeAndStyle (const float newHeight,
  13458. const int newStyleFlags,
  13459. const float newHorizontalScale,
  13460. const float newKerningAmount) throw();
  13461. /** Resets this font's characteristics.
  13462. This is basically like saying "myFont = Font();", because it resets the
  13463. typeface, size, style, etc to a default state. Not very useful to most
  13464. people, its raison d'etre is to help the Graphics class be more efficient.
  13465. */
  13466. void resetToDefaultState() throw();
  13467. /** Returns the total width of a string as it would be drawn using this font.
  13468. For a more accurate floating-point result, use getStringWidthFloat().
  13469. */
  13470. int getStringWidth (const String& text) const throw();
  13471. /** Returns the total width of a string as it would be drawn using this font.
  13472. @see getStringWidth
  13473. */
  13474. float getStringWidthFloat (const String& text) const throw();
  13475. /** Returns the typeface used by this font.
  13476. Note that the object returned may go out of scope if this font is deleted
  13477. or has its style changed.
  13478. */
  13479. Typeface* getTypeface() const throw();
  13480. /** Creates an array of Font objects to represent all the fonts on the system.
  13481. If you just need the names of the typefaces, you can also use
  13482. findAllTypefaceNames() instead.
  13483. @param results the array to which new Font objects will be added.
  13484. */
  13485. static void findFonts (OwnedArray<Font>& results) throw();
  13486. /** Returns a list of all the available typeface names.
  13487. The names returned can be passed into setTypefaceName().
  13488. You can use this instead of findFonts() if you only need their names, and not
  13489. font objects.
  13490. */
  13491. static const StringArray findAllTypefaceNames() throw();
  13492. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  13493. in the requested typeface.
  13494. */
  13495. static const String getFallbackFontName() throw();
  13496. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  13497. available in whatever font you're trying to use.
  13498. */
  13499. static void setFallbackFontName (const String& name) throw();
  13500. juce_UseDebuggingNewOperator
  13501. private:
  13502. friend class FontGlyphAlphaMap;
  13503. friend class TypefaceCache;
  13504. String typefaceName;
  13505. float height, horizontalScale, kerning;
  13506. mutable float ascent;
  13507. int styleFlags;
  13508. mutable Typeface::Ptr typeface;
  13509. };
  13510. #endif // __JUCE_FONT_JUCEHEADER__
  13511. /********* End of inlined file: juce_Font.h *********/
  13512. /********* Start of inlined file: juce_Rectangle.h *********/
  13513. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13514. #define __JUCE_RECTANGLE_JUCEHEADER__
  13515. /**
  13516. A rectangle, specified using integer co-ordinates.
  13517. @see RectangleList, Path, Line, Point
  13518. */
  13519. class JUCE_API Rectangle
  13520. {
  13521. public:
  13522. /** Creates a rectangle of zero size.
  13523. The default co-ordinates will be (0, 0, 0, 0).
  13524. */
  13525. Rectangle() throw();
  13526. /** Creates a copy of another rectangle. */
  13527. Rectangle (const Rectangle& other) throw();
  13528. /** Creates a rectangle with a given position and size. */
  13529. Rectangle (const int x, const int y,
  13530. const int width, const int height) throw();
  13531. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13532. Rectangle (const int width, const int height) throw();
  13533. /** Destructor. */
  13534. ~Rectangle() throw();
  13535. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13536. inline int getX() const throw() { return x; }
  13537. /** Returns the y co-ordinate of the rectangle's top edge. */
  13538. inline int getY() const throw() { return y; }
  13539. /** Returns the width of the rectangle. */
  13540. inline int getWidth() const throw() { return w; }
  13541. /** Returns the height of the rectangle. */
  13542. inline int getHeight() const throw() { return h; }
  13543. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13544. inline int getRight() const throw() { return x + w; }
  13545. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13546. inline int getBottom() const throw() { return y + h; }
  13547. /** Returns the x co-ordinate of the rectangle's centre. */
  13548. inline int getCentreX() const throw() { return x + (w >> 1); }
  13549. /** Returns the y co-ordinate of the rectangle's centre. */
  13550. inline int getCentreY() const throw() { return y + (h >> 1); }
  13551. /** Returns true if the rectangle's width and height are both zero or less */
  13552. bool isEmpty() const throw();
  13553. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13554. void setPosition (const int x, const int y) throw();
  13555. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13556. void setSize (const int w, const int h) throw();
  13557. /** Changes all the rectangle's co-ordinates. */
  13558. void setBounds (const int newX, const int newY,
  13559. const int newWidth, const int newHeight) throw();
  13560. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  13561. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  13562. */
  13563. void setLeft (const int newLeft) throw();
  13564. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  13565. If the y is moved to be below the current bottom edge, the height will be set to zero.
  13566. */
  13567. void setTop (const int newTop) throw();
  13568. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  13569. If the new right is below the current X value, the X will be pushed down to match it.
  13570. @see getRight
  13571. */
  13572. void setRight (const int newRight) throw();
  13573. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  13574. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  13575. @see getBottom
  13576. */
  13577. void setBottom (const int newBottom) throw();
  13578. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13579. void translate (const int deltaX,
  13580. const int deltaY) throw();
  13581. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13582. const Rectangle translated (const int deltaX,
  13583. const int deltaY) const throw();
  13584. /** Expands the rectangle by a given amount.
  13585. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13586. @see expanded, reduce, reduced
  13587. */
  13588. void expand (const int deltaX,
  13589. const int deltaY) throw();
  13590. /** Returns a rectangle that is larger than this one by a given amount.
  13591. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13592. @see expand, reduce, reduced
  13593. */
  13594. const Rectangle expanded (const int deltaX,
  13595. const int deltaY) const throw();
  13596. /** Shrinks the rectangle by a given amount.
  13597. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13598. @see reduced, expand, expanded
  13599. */
  13600. void reduce (const int deltaX,
  13601. const int deltaY) throw();
  13602. /** Returns a rectangle that is smaller than this one by a given amount.
  13603. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13604. @see reduce, expand, expanded
  13605. */
  13606. const Rectangle reduced (const int deltaX,
  13607. const int deltaY) const throw();
  13608. /** Returns true if the two rectangles are identical. */
  13609. bool operator== (const Rectangle& other) const throw();
  13610. /** Returns true if the two rectangles are not identical. */
  13611. bool operator!= (const Rectangle& other) const throw();
  13612. /** Returns true if this co-ordinate is inside the rectangle. */
  13613. bool contains (const int x, const int y) const throw();
  13614. /** Returns true if this other rectangle is completely inside this one. */
  13615. bool contains (const Rectangle& other) const throw();
  13616. /** Returns true if any part of another rectangle overlaps this one. */
  13617. bool intersects (const Rectangle& other) const throw();
  13618. /** Returns the region that is the overlap between this and another rectangle.
  13619. If the two rectangles don't overlap, the rectangle returned will be empty.
  13620. */
  13621. const Rectangle getIntersection (const Rectangle& other) const throw();
  13622. /** Clips a rectangle so that it lies only within this one.
  13623. This is a non-static version of intersectRectangles().
  13624. Returns false if the two regions didn't overlap.
  13625. */
  13626. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13627. /** Returns the smallest rectangle that contains both this one and the one
  13628. passed-in.
  13629. */
  13630. const Rectangle getUnion (const Rectangle& other) const throw();
  13631. /** If this rectangle merged with another one results in a simple rectangle, this
  13632. will set this rectangle to the result, and return true.
  13633. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13634. or if they form a complex region.
  13635. */
  13636. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13637. /** If after removing another rectangle from this one the result is a simple rectangle,
  13638. this will set this object's bounds to be the result, and return true.
  13639. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13640. or if removing the other one would form a complex region.
  13641. */
  13642. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13643. /** Static utility to intersect two sets of rectangular co-ordinates.
  13644. Returns false if the two regions didn't overlap.
  13645. @see intersectRectangle
  13646. */
  13647. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13648. int x2, int y2, int w2, int h2) throw();
  13649. /** Creates a string describing this rectangle.
  13650. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13651. Coupled with the fromString() method, this is very handy for things like
  13652. storing rectangles (particularly component positions) in XML attributes.
  13653. @see fromString
  13654. */
  13655. const String toString() const throw();
  13656. /** Parses a string containing a rectangle's details.
  13657. The string should contain 4 integer tokens, in the form "x y width height". They
  13658. can be comma or whitespace separated.
  13659. This method is intended to go with the toString() method, to form an easy way
  13660. of saving/loading rectangles as strings.
  13661. @see toString
  13662. */
  13663. static const Rectangle fromString (const String& stringVersion);
  13664. juce_UseDebuggingNewOperator
  13665. private:
  13666. friend class RectangleList;
  13667. int x, y, w, h;
  13668. };
  13669. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13670. /********* End of inlined file: juce_Rectangle.h *********/
  13671. /********* Start of inlined file: juce_PathStrokeType.h *********/
  13672. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13673. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13674. /**
  13675. Describes a type of stroke used to render a solid outline along a path.
  13676. A PathStrokeType object can be used directly to create the shape of an outline
  13677. around a path, and is used by Graphics::strokePath to specify the type of
  13678. stroke to draw.
  13679. @see Path, Graphics::strokePath
  13680. */
  13681. class JUCE_API PathStrokeType
  13682. {
  13683. public:
  13684. /** The type of shape to use for the corners between two adjacent line segments. */
  13685. enum JointStyle
  13686. {
  13687. mitered, /**< Indicates that corners should be drawn with sharp joints.
  13688. Note that for angles that curve back on themselves, drawing a
  13689. mitre could require extending the point too far away from the
  13690. path, so a mitre limit is imposed and any corners that exceed it
  13691. are drawn as bevelled instead. */
  13692. curved, /**< Indicates that corners should be drawn as rounded-off. */
  13693. beveled /**< Indicates that corners should be drawn with a line flattening their
  13694. outside edge. */
  13695. };
  13696. /** The type shape to use for the ends of lines. */
  13697. enum EndCapStyle
  13698. {
  13699. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  13700. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  13701. the thickness of the stroke. */
  13702. rounded /**< Ends of lines are rounded-off with a circular shape. */
  13703. };
  13704. /** Creates a stroke type.
  13705. @param strokeThickness the width of the line to use
  13706. @param jointStyle the type of joints to use for corners
  13707. @param endStyle the type of end-caps to use for the ends of open paths.
  13708. */
  13709. PathStrokeType (const float strokeThickness,
  13710. const JointStyle jointStyle = mitered,
  13711. const EndCapStyle endStyle = butt) throw();
  13712. /** Createes a copy of another stroke type. */
  13713. PathStrokeType (const PathStrokeType& other) throw();
  13714. /** Copies another stroke onto this one. */
  13715. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  13716. /** Destructor. */
  13717. ~PathStrokeType() throw();
  13718. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  13719. @param destPath the resultant stroked outline shape will be copied into this path.
  13720. Note that it's ok for the source and destination Paths to be
  13721. the same object, so you can easily turn a path into a stroked version
  13722. of itself.
  13723. @param sourcePath the path to use as the source
  13724. @param transform an optional transform to apply to the points from the source path
  13725. as they are being used
  13726. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13727. a higher resolution, which improved the quality if you'll later want
  13728. to enlarge the stroked path
  13729. @see createDashedStroke
  13730. */
  13731. void createStrokedPath (Path& destPath,
  13732. const Path& sourcePath,
  13733. const AffineTransform& transform = AffineTransform::identity,
  13734. const float extraAccuracy = 1.0f) const throw();
  13735. /** Applies this stroke type to a path, creating a dashed line.
  13736. This is similar to createStrokedPath, but uses the array passed in to
  13737. break the stroke up into a series of dashes.
  13738. @param destPath the resultant stroked outline shape will be copied into this path.
  13739. Note that it's ok for the source and destination Paths to be
  13740. the same object, so you can easily turn a path into a stroked version
  13741. of itself.
  13742. @param sourcePath the path to use as the source
  13743. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  13744. a line of length 2, then skip a length of 3, then add a line of length 4,
  13745. skip 5, and keep repeating this pattern.
  13746. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  13747. an even number, otherwise the pattern will get out of step as it
  13748. repeats.
  13749. @param transform an optional transform to apply to the points from the source path
  13750. as they are being used
  13751. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  13752. a higher resolution, which improved the quality if you'll later want
  13753. to enlarge the stroked path
  13754. */
  13755. void createDashedStroke (Path& destPath,
  13756. const Path& sourcePath,
  13757. const float* dashLengths,
  13758. int numDashLengths,
  13759. const AffineTransform& transform = AffineTransform::identity,
  13760. const float extraAccuracy = 1.0f) const throw();
  13761. /** Returns the stroke thickness. */
  13762. float getStrokeThickness() const throw() { return thickness; }
  13763. /** Returns the joint style. */
  13764. JointStyle getJointStyle() const throw() { return jointStyle; }
  13765. /** Returns the end-cap style. */
  13766. EndCapStyle getEndStyle() const throw() { return endStyle; }
  13767. juce_UseDebuggingNewOperator
  13768. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13769. bool operator== (const PathStrokeType& other) const throw();
  13770. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  13771. bool operator!= (const PathStrokeType& other) const throw();
  13772. private:
  13773. float thickness;
  13774. JointStyle jointStyle;
  13775. EndCapStyle endStyle;
  13776. };
  13777. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  13778. /********* End of inlined file: juce_PathStrokeType.h *********/
  13779. /********* Start of inlined file: juce_Line.h *********/
  13780. #ifndef __JUCE_LINE_JUCEHEADER__
  13781. #define __JUCE_LINE_JUCEHEADER__
  13782. /**
  13783. Represents a line, using 32-bit float co-ordinates.
  13784. This class contains a bunch of useful methods for various geometric
  13785. tasks.
  13786. @see Point, Rectangle, Path, Graphics::drawLine
  13787. */
  13788. class JUCE_API Line
  13789. {
  13790. public:
  13791. /** Creates a line, using (0, 0) as its start and end points. */
  13792. Line() throw();
  13793. /** Creates a copy of another line. */
  13794. Line (const Line& other) throw();
  13795. /** Creates a line based on the co-ordinates of its start and end points. */
  13796. Line (const float startX,
  13797. const float startY,
  13798. const float endX,
  13799. const float endY) throw();
  13800. /** Creates a line from its start and end points. */
  13801. Line (const Point& start,
  13802. const Point& end) throw();
  13803. /** Copies a line from another one. */
  13804. const Line& operator= (const Line& other) throw();
  13805. /** Destructor. */
  13806. ~Line() throw();
  13807. /** Returns the x co-ordinate of the line's start point. */
  13808. inline float getStartX() const throw() { return startX; }
  13809. /** Returns the y co-ordinate of the line's start point. */
  13810. inline float getStartY() const throw() { return startY; }
  13811. /** Returns the x co-ordinate of the line's end point. */
  13812. inline float getEndX() const throw() { return endX; }
  13813. /** Returns the y co-ordinate of the line's end point. */
  13814. inline float getEndY() const throw() { return endY; }
  13815. /** Returns the line's start point. */
  13816. const Point getStart() const throw();
  13817. /** Returns the line's end point. */
  13818. const Point getEnd() const throw();
  13819. /** Changes this line's start point */
  13820. void setStart (const float newStartX,
  13821. const float newStartY) throw();
  13822. /** Changes this line's end point */
  13823. void setEnd (const float newEndX,
  13824. const float newEndY) throw();
  13825. /** Changes this line's start point */
  13826. void setStart (const Point& newStart) throw();
  13827. /** Changes this line's end point */
  13828. void setEnd (const Point& newEnd) throw();
  13829. /** Applies an affine transform to the line's start and end points. */
  13830. void applyTransform (const AffineTransform& transform) throw();
  13831. /** Returns the length of the line. */
  13832. float getLength() const throw();
  13833. /** Returns true if the line's start and end x co-ordinates are the same. */
  13834. bool isVertical() const throw();
  13835. /** Returns true if the line's start and end y co-ordinates are the same. */
  13836. bool isHorizontal() const throw();
  13837. /** Returns the line's angle.
  13838. This value is the number of radians clockwise from the 3 o'clock direction,
  13839. where the line's start point is considered to be at the centre.
  13840. */
  13841. float getAngle() const throw();
  13842. /** Compares two lines. */
  13843. bool operator== (const Line& other) const throw();
  13844. /** Compares two lines. */
  13845. bool operator!= (const Line& other) const throw();
  13846. /** Finds the intersection between two lines.
  13847. @param line the other line
  13848. @param intersectionX the x co-ordinate of the point where the lines meet (or
  13849. where they would meet if they were infinitely long)
  13850. the intersection (if the lines intersect). If the lines
  13851. are parallel, this will just be set to the position
  13852. of one of the line's endpoints.
  13853. @param intersectionY the y co-ordinate of the point where the lines meet
  13854. @returns true if the line segments intersect; false if they dont. Even if they
  13855. don't intersect, the intersection co-ordinates returned will still
  13856. be valid
  13857. */
  13858. bool intersects (const Line& line,
  13859. float& intersectionX,
  13860. float& intersectionY) const throw();
  13861. /** Returns the location of the point which is a given distance along this line.
  13862. @param distanceFromStart the distance to move along the line from its
  13863. start point. This value can be negative or longer
  13864. than the line itself
  13865. @see getPointAlongLineProportionally
  13866. */
  13867. const Point getPointAlongLine (const float distanceFromStart) const throw();
  13868. /** Returns a point which is a certain distance along and to the side of this line.
  13869. This effectively moves a given distance along the line, then another distance
  13870. perpendicularly to this, and returns the resulting position.
  13871. @param distanceFromStart the distance to move along the line from its
  13872. start point. This value can be negative or longer
  13873. than the line itself
  13874. @param perpendicularDistance how far to move sideways from the line. If you're
  13875. looking along the line from its start towards its
  13876. end, then a positive value here will move to the
  13877. right, negative value move to the left.
  13878. */
  13879. const Point getPointAlongLine (const float distanceFromStart,
  13880. const float perpendicularDistance) const throw();
  13881. /** Returns the location of the point which is a given distance along this line
  13882. proportional to the line's length.
  13883. @param proportionOfLength the distance to move along the line from its
  13884. start point, in multiples of the line's length.
  13885. So a value of 0.0 will return the line's start point
  13886. and a value of 1.0 will return its end point. (This value
  13887. can be negative or greater than 1.0).
  13888. @see getPointAlongLine
  13889. */
  13890. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  13891. /** Returns the smallest distance between this line segment and a given point.
  13892. So if the point is close to the line, this will return the perpendicular
  13893. distance from the line; if the point is a long way beyond one of the line's
  13894. end-point's, it'll return the straight-line distance to the nearest end-point.
  13895. @param x x position of the point to test
  13896. @param y y position of the point to test
  13897. @returns the point's distance from the line
  13898. @see getPositionAlongLineOfNearestPoint
  13899. */
  13900. float getDistanceFromLine (const float x,
  13901. const float y) const throw();
  13902. /** Finds the point on this line which is nearest to a given point, and
  13903. returns its position as a proportional position along the line.
  13904. @param x x position of the point to test
  13905. @param y y position of the point to test
  13906. @returns a value 0 to 1.0 which is the distance along this line from the
  13907. line's start to the point which is nearest to the point passed-in. To
  13908. turn this number into a position, use getPointAlongLineProportionally().
  13909. @see getDistanceFromLine, getPointAlongLineProportionally
  13910. */
  13911. float findNearestPointTo (const float x,
  13912. const float y) const throw();
  13913. /** Returns true if the given point lies above this line.
  13914. The return value is true if the point's y coordinate is less than the y
  13915. coordinate of this line at the given x (assuming the line extends infinitely
  13916. in both directions).
  13917. */
  13918. bool isPointAbove (const float x, const float y) const throw();
  13919. /** Returns a shortened copy of this line.
  13920. This will chop off part of the start of this line by a certain amount, (leaving the
  13921. end-point the same), and return the new line.
  13922. */
  13923. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  13924. /** Returns a shortened copy of this line.
  13925. This will chop off part of the end of this line by a certain amount, (leaving the
  13926. start-point the same), and return the new line.
  13927. */
  13928. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  13929. /** Cuts off parts of this line to keep the parts that are either inside or
  13930. outside a path.
  13931. Note that this isn't smart enough to cope with situations where the
  13932. line would need to be cut into multiple pieces to correctly clip against
  13933. a re-entrant shape.
  13934. @param path the path to clip against
  13935. @param keepSectionOutsidePath if true, it's the section outside the path
  13936. that will be kept; if false its the section inside
  13937. the path
  13938. @returns true if the line was changed.
  13939. */
  13940. bool clipToPath (const Path& path,
  13941. const bool keepSectionOutsidePath) throw();
  13942. juce_UseDebuggingNewOperator
  13943. private:
  13944. float startX, startY, endX, endY;
  13945. };
  13946. #endif // __JUCE_LINE_JUCEHEADER__
  13947. /********* End of inlined file: juce_Line.h *********/
  13948. /********* Start of inlined file: juce_Colours.h *********/
  13949. #ifndef __JUCE_COLOURS_JUCEHEADER__
  13950. #define __JUCE_COLOURS_JUCEHEADER__
  13951. /********* Start of inlined file: juce_Colour.h *********/
  13952. #ifndef __JUCE_COLOUR_JUCEHEADER__
  13953. #define __JUCE_COLOUR_JUCEHEADER__
  13954. /********* Start of inlined file: juce_PixelFormats.h *********/
  13955. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  13956. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  13957. #if JUCE_MSVC
  13958. #pragma pack (push, 1)
  13959. #define PACKED
  13960. #elif JUCE_GCC
  13961. #define PACKED __attribute__((packed))
  13962. #else
  13963. #define PACKED
  13964. #endif
  13965. /**
  13966. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  13967. operations with it.
  13968. This is used internally by the imaging classes.
  13969. @see PixelRGB
  13970. */
  13971. class JUCE_API PixelARGB
  13972. {
  13973. public:
  13974. /** Creates a pixel without defining its colour. */
  13975. PixelARGB() throw() {}
  13976. ~PixelARGB() throw() {}
  13977. /** Creates a pixel from a 32-bit argb value.
  13978. */
  13979. PixelARGB (const uint32 argb_) throw()
  13980. : argb (argb_)
  13981. {
  13982. }
  13983. forcedinline uint32 getARGB() const throw() { return argb; }
  13984. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  13985. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  13986. forcedinline uint8 getAlpha() const throw() { return components.a; }
  13987. forcedinline uint8 getRed() const throw() { return components.r; }
  13988. forcedinline uint8 getGreen() const throw() { return components.g; }
  13989. forcedinline uint8 getBlue() const throw() { return components.b; }
  13990. /** Blends another pixel onto this one.
  13991. This takes into account the opacity of the pixel being overlaid, and blends
  13992. it accordingly.
  13993. */
  13994. template <class Pixel>
  13995. forcedinline void blend (const Pixel& src) throw()
  13996. {
  13997. uint32 sargb = src.getARGB();
  13998. const uint32 alpha = 0x100 - (sargb >> 24);
  13999. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14000. sargb += 0xff00ff00 & (getAG() * alpha);
  14001. argb = sargb;
  14002. }
  14003. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  14004. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  14005. being used, so this can blend semi-transparently from a PixelRGB argument.
  14006. */
  14007. template <class Pixel>
  14008. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  14009. {
  14010. ++extraAlpha;
  14011. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  14012. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  14013. const uint32 alpha = 0x100 - (sargb >> 24);
  14014. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14015. sargb += 0xff00ff00 & (getAG() * alpha);
  14016. argb = sargb;
  14017. }
  14018. /** Blends another pixel with this one, creating a colour that is somewhere
  14019. between the two, as specified by the amount.
  14020. */
  14021. template <class Pixel>
  14022. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  14023. {
  14024. uint32 drb = getRB();
  14025. drb += (((src.getRB() - drb) * amount) >> 8);
  14026. drb &= 0x00ff00ff;
  14027. uint32 dag = getAG();
  14028. dag += (((src.getAG() - dag) * amount) >> 8);
  14029. dag &= 0x00ff00ff;
  14030. dag <<= 8;
  14031. dag |= drb;
  14032. argb = dag;
  14033. }
  14034. /** Copies another pixel colour over this one.
  14035. This doesn't blend it - this colour is simply replaced by the other one.
  14036. */
  14037. template <class Pixel>
  14038. forcedinline void set (const Pixel& src) throw()
  14039. {
  14040. argb = src.getARGB();
  14041. }
  14042. /** Replaces the colour's alpha value with another one. */
  14043. forcedinline void setAlpha (const uint8 newAlpha) throw()
  14044. {
  14045. components.a = newAlpha;
  14046. }
  14047. /** Multiplies the colour's alpha value with another one. */
  14048. forcedinline void multiplyAlpha (int multiplier) throw()
  14049. {
  14050. ++multiplier;
  14051. argb = ((multiplier * getAG()) & 0xff00ff00)
  14052. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  14053. }
  14054. forcedinline void multiplyAlpha (const float multiplier) throw()
  14055. {
  14056. multiplyAlpha ((int) (multiplier * 256.0f));
  14057. }
  14058. /** Sets the pixel's colour from individual components. */
  14059. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  14060. {
  14061. components.b = b;
  14062. components.g = g;
  14063. components.r = r;
  14064. components.a = a;
  14065. }
  14066. /** Premultiplies the pixel's RGB values by its alpha. */
  14067. forcedinline void premultiply() throw()
  14068. {
  14069. const uint32 alpha = components.a;
  14070. if (alpha < 0xff)
  14071. {
  14072. if (alpha == 0)
  14073. {
  14074. components.b = 0;
  14075. components.g = 0;
  14076. components.r = 0;
  14077. }
  14078. else
  14079. {
  14080. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  14081. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  14082. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  14083. }
  14084. }
  14085. }
  14086. /** Unpremultiplies the pixel's RGB values. */
  14087. forcedinline void unpremultiply() throw()
  14088. {
  14089. const uint32 alpha = components.a;
  14090. if (alpha < 0xff)
  14091. {
  14092. if (alpha == 0)
  14093. {
  14094. components.b = 0;
  14095. components.g = 0;
  14096. components.r = 0;
  14097. }
  14098. else
  14099. {
  14100. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  14101. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  14102. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  14103. }
  14104. }
  14105. }
  14106. forcedinline void desaturate() throw()
  14107. {
  14108. if (components.a < 0xff && components.a > 0)
  14109. {
  14110. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  14111. components.r = components.g = components.b
  14112. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  14113. }
  14114. else
  14115. {
  14116. components.r = components.g = components.b
  14117. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  14118. }
  14119. }
  14120. private:
  14121. union
  14122. {
  14123. uint32 argb;
  14124. struct
  14125. {
  14126. #if JUCE_BIG_ENDIAN
  14127. uint8 a : 8, r : 8, g : 8, b : 8;
  14128. #else
  14129. uint8 b, g, r, a;
  14130. #endif
  14131. } PACKED components;
  14132. };
  14133. } PACKED;
  14134. /**
  14135. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  14136. This is used internally by the imaging classes.
  14137. @see PixelARGB
  14138. */
  14139. class JUCE_API PixelRGB
  14140. {
  14141. public:
  14142. /** Creates a pixel without defining its colour. */
  14143. PixelRGB() throw() {}
  14144. ~PixelRGB() throw() {}
  14145. /** Creates a pixel from a 32-bit argb value.
  14146. (The argb format is that used by PixelARGB)
  14147. */
  14148. PixelRGB (const uint32 argb) throw()
  14149. {
  14150. r = (uint8) (argb >> 16);
  14151. g = (uint8) (argb >> 8);
  14152. b = (uint8) (argb);
  14153. }
  14154. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  14155. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  14156. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  14157. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  14158. forcedinline uint8 getRed() const throw() { return r; }
  14159. forcedinline uint8 getGreen() const throw() { return g; }
  14160. forcedinline uint8 getBlue() const throw() { return b; }
  14161. /** Blends another pixel onto this one.
  14162. This takes into account the opacity of the pixel being overlaid, and blends
  14163. it accordingly.
  14164. */
  14165. forcedinline void blend (const PixelARGB& src) throw()
  14166. {
  14167. uint32 sargb = src.getARGB();
  14168. const uint32 alpha = 0x100 - (sargb >> 24);
  14169. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14170. sargb += 0x0000ff00 & (g * alpha);
  14171. r = (uint8) (sargb >> 16);
  14172. g = (uint8) (sargb >> 8);
  14173. b = (uint8) sargb;
  14174. }
  14175. forcedinline void blend (const PixelRGB& src) throw()
  14176. {
  14177. set (src);
  14178. }
  14179. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  14180. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  14181. being used, so this can blend semi-transparently from a PixelRGB argument.
  14182. */
  14183. template <class Pixel>
  14184. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  14185. {
  14186. ++extraAlpha;
  14187. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  14188. const uint32 sag = extraAlpha * src.getAG();
  14189. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  14190. const uint32 alpha = 0x100 - (sargb >> 24);
  14191. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  14192. sargb += 0x0000ff00 & (g * alpha);
  14193. b = (uint8) sargb;
  14194. g = (uint8) (sargb >> 8);
  14195. r = (uint8) (sargb >> 16);
  14196. }
  14197. /** Blends another pixel with this one, creating a colour that is somewhere
  14198. between the two, as specified by the amount.
  14199. */
  14200. template <class Pixel>
  14201. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  14202. {
  14203. uint32 drb = getRB();
  14204. drb += (((src.getRB() - drb) * amount) >> 8);
  14205. uint32 dag = getAG();
  14206. dag += (((src.getAG() - dag) * amount) >> 8);
  14207. b = (uint8) drb;
  14208. g = (uint8) dag;
  14209. r = (uint8) (drb >> 16);
  14210. }
  14211. /** Copies another pixel colour over this one.
  14212. This doesn't blend it - this colour is simply replaced by the other one.
  14213. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  14214. is thrown away.
  14215. */
  14216. template <class Pixel>
  14217. forcedinline void set (const Pixel& src) throw()
  14218. {
  14219. b = src.getBlue();
  14220. g = src.getGreen();
  14221. r = src.getRed();
  14222. }
  14223. /** This method is included for compatibility with the PixelARGB class. */
  14224. forcedinline void setAlpha (const uint8) throw() {}
  14225. /** Multiplies the colour's alpha value with another one. */
  14226. forcedinline void multiplyAlpha (int) throw() {}
  14227. /** Sets the pixel's colour from individual components. */
  14228. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  14229. {
  14230. r = r_;
  14231. g = g_;
  14232. b = b_;
  14233. }
  14234. /** Premultiplies the pixel's RGB values by its alpha. */
  14235. forcedinline void premultiply() throw() {}
  14236. /** Unpremultiplies the pixel's RGB values. */
  14237. forcedinline void unpremultiply() throw() {}
  14238. forcedinline void desaturate() throw()
  14239. {
  14240. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  14241. }
  14242. private:
  14243. #if JUCE_MAC
  14244. uint8 r, g, b;
  14245. #else
  14246. uint8 b, g, r;
  14247. #endif
  14248. } PACKED;
  14249. #if JUCE_MSVC
  14250. #pragma pack (pop)
  14251. #endif
  14252. #undef PACKED
  14253. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  14254. /********* End of inlined file: juce_PixelFormats.h *********/
  14255. /**
  14256. Represents a colour, also including a transparency value.
  14257. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  14258. */
  14259. class JUCE_API Colour
  14260. {
  14261. public:
  14262. /** Creates a transparent black colour. */
  14263. Colour() throw();
  14264. /** Creates a copy of another Colour object. */
  14265. Colour (const Colour& other) throw();
  14266. /** Creates a colour from a 32-bit ARGB value.
  14267. The format of this number is:
  14268. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  14269. All components in the range 0x00 to 0xff.
  14270. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14271. @see getPixelARGB
  14272. */
  14273. explicit Colour (const uint32 argb) throw();
  14274. /** Creates an opaque colour using 8-bit red, green and blue values */
  14275. Colour (const uint8 red,
  14276. const uint8 green,
  14277. const uint8 blue) throw();
  14278. /** Creates an opaque colour using 8-bit red, green and blue values */
  14279. static const Colour fromRGB (const uint8 red,
  14280. const uint8 green,
  14281. const uint8 blue) throw();
  14282. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  14283. Colour (const uint8 red,
  14284. const uint8 green,
  14285. const uint8 blue,
  14286. const uint8 alpha) throw();
  14287. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  14288. static const Colour fromRGBA (const uint8 red,
  14289. const uint8 green,
  14290. const uint8 blue,
  14291. const uint8 alpha) throw();
  14292. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  14293. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  14294. Values outside the valid range will be clipped.
  14295. */
  14296. Colour (const uint8 red,
  14297. const uint8 green,
  14298. const uint8 blue,
  14299. const float alpha) throw();
  14300. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  14301. static const Colour fromRGBAFloat (const uint8 red,
  14302. const uint8 green,
  14303. const uint8 blue,
  14304. const float alpha) throw();
  14305. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14306. The floating point values must be between 0.0 and 1.0.
  14307. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14308. Values outside the valid range will be clipped.
  14309. */
  14310. Colour (const float hue,
  14311. const float saturation,
  14312. const float brightness,
  14313. const uint8 alpha) throw();
  14314. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  14315. All values must be between 0.0 and 1.0.
  14316. Numbers outside the valid range will be clipped.
  14317. */
  14318. Colour (const float hue,
  14319. const float saturation,
  14320. const float brightness,
  14321. const float alpha) throw();
  14322. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  14323. The floating point values must be between 0.0 and 1.0.
  14324. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  14325. Values outside the valid range will be clipped.
  14326. */
  14327. static const Colour fromHSV (const float hue,
  14328. const float saturation,
  14329. const float brightness,
  14330. const float alpha) throw();
  14331. /** Destructor. */
  14332. ~Colour() throw();
  14333. /** Copies another Colour object. */
  14334. const Colour& operator= (const Colour& other) throw();
  14335. /** Compares two colours. */
  14336. bool operator== (const Colour& other) const throw();
  14337. /** Compares two colours. */
  14338. bool operator!= (const Colour& other) const throw();
  14339. /** Returns the red component of this colour.
  14340. @returns a value between 0x00 and 0xff.
  14341. */
  14342. uint8 getRed() const throw() { return argb.getRed(); }
  14343. /** Returns the green component of this colour.
  14344. @returns a value between 0x00 and 0xff.
  14345. */
  14346. uint8 getGreen() const throw() { return argb.getGreen(); }
  14347. /** Returns the blue component of this colour.
  14348. @returns a value between 0x00 and 0xff.
  14349. */
  14350. uint8 getBlue() const throw() { return argb.getBlue(); }
  14351. /** Returns the red component of this colour as a floating point value.
  14352. @returns a value between 0.0 and 1.0
  14353. */
  14354. float getFloatRed() const throw();
  14355. /** Returns the green component of this colour as a floating point value.
  14356. @returns a value between 0.0 and 1.0
  14357. */
  14358. float getFloatGreen() const throw();
  14359. /** Returns the blue component of this colour as a floating point value.
  14360. @returns a value between 0.0 and 1.0
  14361. */
  14362. float getFloatBlue() const throw();
  14363. /** Returns a premultiplied ARGB pixel object that represents this colour.
  14364. */
  14365. const PixelARGB getPixelARGB() const throw();
  14366. /** Returns a 32-bit integer that represents this colour.
  14367. The format of this number is:
  14368. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  14369. */
  14370. uint32 getARGB() const throw();
  14371. /** Returns the colour's alpha (opacity).
  14372. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  14373. */
  14374. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  14375. /** Returns the colour's alpha (opacity) as a floating point value.
  14376. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  14377. */
  14378. float getFloatAlpha() const throw();
  14379. /** Returns true if this colour is completely opaque.
  14380. Equivalent to (getAlpha() == 0xff).
  14381. */
  14382. bool isOpaque() const throw();
  14383. /** Returns true if this colour is completely transparent.
  14384. Equivalent to (getAlpha() == 0x00).
  14385. */
  14386. bool isTransparent() const throw();
  14387. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14388. const Colour withAlpha (const uint8 newAlpha) const throw();
  14389. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  14390. const Colour withAlpha (const float newAlpha) const throw();
  14391. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  14392. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  14393. */
  14394. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  14395. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  14396. If the foreground colour is semi-transparent, it is blended onto this colour
  14397. accordingly.
  14398. */
  14399. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  14400. /** Returns the colour's hue component.
  14401. The value returned is in the range 0.0 to 1.0
  14402. */
  14403. float getHue() const throw();
  14404. /** Returns the colour's saturation component.
  14405. The value returned is in the range 0.0 to 1.0
  14406. */
  14407. float getSaturation() const throw();
  14408. /** Returns the colour's brightness component.
  14409. The value returned is in the range 0.0 to 1.0
  14410. */
  14411. float getBrightness() const throw();
  14412. /** Returns the colour's hue, saturation and brightness components all at once.
  14413. The values returned are in the range 0.0 to 1.0
  14414. */
  14415. void getHSB (float& hue,
  14416. float& saturation,
  14417. float& brightness) const throw();
  14418. /** Returns a copy of this colour with a different hue. */
  14419. const Colour withHue (const float newHue) const throw();
  14420. /** Returns a copy of this colour with a different saturation. */
  14421. const Colour withSaturation (const float newSaturation) const throw();
  14422. /** Returns a copy of this colour with a different brightness.
  14423. @see brighter, darker, withMultipliedBrightness
  14424. */
  14425. const Colour withBrightness (const float newBrightness) const throw();
  14426. /** Returns a copy of this colour with it hue rotated.
  14427. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  14428. @see brighter, darker, withMultipliedBrightness
  14429. */
  14430. const Colour withRotatedHue (const float amountToRotate) const throw();
  14431. /** Returns a copy of this colour with its saturation multiplied by the given value.
  14432. The new colour's saturation is (this->getSaturation() * multiplier)
  14433. (the result is clipped to legal limits).
  14434. */
  14435. const Colour withMultipliedSaturation (const float multiplier) const throw();
  14436. /** Returns a copy of this colour with its brightness multiplied by the given value.
  14437. The new colour's saturation is (this->getBrightness() * multiplier)
  14438. (the result is clipped to legal limits).
  14439. */
  14440. const Colour withMultipliedBrightness (const float amount) const throw();
  14441. /** Returns a brighter version of this colour.
  14442. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  14443. unchanged, and higher values make it brighter
  14444. @see withMultipliedBrightness
  14445. */
  14446. const Colour brighter (float amountBrighter = 0.4f) const throw();
  14447. /** Returns a darker version of this colour.
  14448. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  14449. unchanged, and higher values make it darker
  14450. @see withMultipliedBrightness
  14451. */
  14452. const Colour darker (float amountDarker = 0.4f) const throw();
  14453. /** Returns a colour that will be clearly visible against this colour.
  14454. The amount parameter indicates how contrasting the new colour should
  14455. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  14456. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  14457. return white; Colours::white.contrasting (1.0f) will return black, etc.
  14458. */
  14459. const Colour contrasting (const float amount = 1.0f) const throw();
  14460. /** Returns a colour that contrasts against two colours.
  14461. Looks for a colour that contrasts with both of the colours passed-in.
  14462. Handy for things like choosing a highlight colour in text editors, etc.
  14463. */
  14464. static const Colour contrasting (const Colour& colour1,
  14465. const Colour& colour2) throw();
  14466. /** Returns an opaque shade of grey.
  14467. @param brightness the level of grey to return - 0 is black, 1.0 is white
  14468. */
  14469. static const Colour greyLevel (const float brightness) throw();
  14470. /** Returns a stringified version of this colour.
  14471. The string can be turned back into a colour using the fromString() method.
  14472. */
  14473. const String toString() const throw();
  14474. /** Reads the colour from a string that was created with toString().
  14475. */
  14476. static const Colour fromString (const String& encodedColourString);
  14477. juce_UseDebuggingNewOperator
  14478. private:
  14479. PixelARGB argb;
  14480. };
  14481. #endif // __JUCE_COLOUR_JUCEHEADER__
  14482. /********* End of inlined file: juce_Colour.h *********/
  14483. /**
  14484. Contains a set of predefined named colours (mostly standard HTML colours)
  14485. @see Colour, Colours::greyLevel
  14486. */
  14487. class Colours
  14488. {
  14489. public:
  14490. static JUCE_API const Colour
  14491. transparentBlack, /**< ARGB = 0x00000000 */
  14492. transparentWhite, /**< ARGB = 0x00ffffff */
  14493. black, /**< ARGB = 0xff000000 */
  14494. white, /**< ARGB = 0xffffffff */
  14495. blue, /**< ARGB = 0xff0000ff */
  14496. grey, /**< ARGB = 0xff808080 */
  14497. green, /**< ARGB = 0xff008000 */
  14498. red, /**< ARGB = 0xffff0000 */
  14499. yellow, /**< ARGB = 0xffffff00 */
  14500. aliceblue, antiquewhite, aqua, aquamarine,
  14501. azure, beige, bisque, blanchedalmond,
  14502. blueviolet, brown, burlywood, cadetblue,
  14503. chartreuse, chocolate, coral, cornflowerblue,
  14504. cornsilk, crimson, cyan, darkblue,
  14505. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  14506. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  14507. darkorchid, darkred, darksalmon, darkseagreen,
  14508. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  14509. deeppink, deepskyblue, dimgrey, dodgerblue,
  14510. firebrick, floralwhite, forestgreen, fuchsia,
  14511. gainsboro, gold, goldenrod, greenyellow,
  14512. honeydew, hotpink, indianred, indigo,
  14513. ivory, khaki, lavender, lavenderblush,
  14514. lemonchiffon, lightblue, lightcoral, lightcyan,
  14515. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  14516. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  14517. lightsteelblue, lightyellow, lime, limegreen,
  14518. linen, magenta, maroon, mediumaquamarine,
  14519. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  14520. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  14521. midnightblue, mintcream, mistyrose, navajowhite,
  14522. navy, oldlace, olive, olivedrab,
  14523. orange, orangered, orchid, palegoldenrod,
  14524. palegreen, paleturquoise, palevioletred, papayawhip,
  14525. peachpuff, peru, pink, plum,
  14526. powderblue, purple, rosybrown, royalblue,
  14527. saddlebrown, salmon, sandybrown, seagreen,
  14528. seashell, sienna, silver, skyblue,
  14529. slateblue, slategrey, snow, springgreen,
  14530. steelblue, tan, teal, thistle,
  14531. tomato, turquoise, violet, wheat,
  14532. whitesmoke, yellowgreen;
  14533. /** Attempts to look up a string in the list of known colour names, and return
  14534. the appropriate colour.
  14535. A non-case-sensitive search is made of the list of predefined colours, and
  14536. if a match is found, that colour is returned. If no match is found, the
  14537. colour passed in as the defaultColour parameter is returned.
  14538. */
  14539. static JUCE_API const Colour findColourForName (const String& colourName,
  14540. const Colour& defaultColour);
  14541. private:
  14542. // this isn't a class you should ever instantiate - it's just here for the
  14543. // static values in it.
  14544. Colours();
  14545. };
  14546. #endif // __JUCE_COLOURS_JUCEHEADER__
  14547. /********* End of inlined file: juce_Colours.h *********/
  14548. /********* Start of inlined file: juce_SolidColourBrush.h *********/
  14549. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14550. #define __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14551. /********* Start of inlined file: juce_Brush.h *********/
  14552. #ifndef __JUCE_BRUSH_JUCEHEADER__
  14553. #define __JUCE_BRUSH_JUCEHEADER__
  14554. class Path;
  14555. class AffineTransform;
  14556. class LowLevelGraphicsContext;
  14557. class Image;
  14558. class Graphics;
  14559. /**
  14560. A brush is used to fill areas with colours, patterns, or images.
  14561. The Graphics class has an idea of a current brush which it uses to render
  14562. shapes, rectangles, lines, text, etc.
  14563. This is the base class - there are subclasses for useful types of fill pattern,
  14564. and applications can define their own brushes too.
  14565. @see Graphics::setBrush, SolidColourBrush, GradientBrush, ImageBrush
  14566. */
  14567. class JUCE_API Brush
  14568. {
  14569. protected:
  14570. /** Creates a Brush.
  14571. (Nothing much happens in the base class).
  14572. */
  14573. Brush() throw();
  14574. public:
  14575. /** Destructor. */
  14576. virtual ~Brush() throw();
  14577. /** Creates a copy of whatever class of Brush this is. */
  14578. virtual Brush* createCopy() const throw() = 0;
  14579. /** Does whatever is relevent to transform the geometry of this brush. */
  14580. virtual void applyTransform (const AffineTransform& transform) throw() = 0;
  14581. /** Does whatever is relevent to change the opacity of this brush. */
  14582. virtual void multiplyOpacity (const float multiple) throw() = 0;
  14583. /** Must return true if this brush won't draw any pixels. */
  14584. virtual bool isInvisible() const throw() = 0;
  14585. virtual void paintPath (LowLevelGraphicsContext& context,
  14586. const Path& path, const AffineTransform& transform) throw() = 0;
  14587. virtual void paintRectangle (LowLevelGraphicsContext& context,
  14588. int x, int y, int w, int h) throw() = 0;
  14589. virtual void paintAlphaChannel (LowLevelGraphicsContext& context,
  14590. const Image& alphaChannelImage, int imageX, int imageY,
  14591. int x, int y, int w, int h) throw() = 0;
  14592. virtual void paintVerticalLine (LowLevelGraphicsContext& context,
  14593. int x, float y1, float y2) throw();
  14594. virtual void paintHorizontalLine (LowLevelGraphicsContext& context,
  14595. int y, float x1, float x2) throw();
  14596. virtual void paintLine (LowLevelGraphicsContext& context,
  14597. float x1, float y1, float x2, float y2) throw();
  14598. private:
  14599. Brush (const Brush&);
  14600. const Brush& operator= (const Brush&);
  14601. };
  14602. #endif // __JUCE_BRUSH_JUCEHEADER__
  14603. /********* End of inlined file: juce_Brush.h *********/
  14604. /**
  14605. A Brush that fills its area with a solid (or semi-transparent) colour.
  14606. An application won't normally need to use this class directly, as drawing
  14607. with solid colours is taken care of automatically by the Graphics class
  14608. (it actually uses one of these brushes internally when you set the colour
  14609. with the Graphics::setColour() method).
  14610. @see Brush, Graphics::setBrush, GradientBrush, ImageBrush
  14611. */
  14612. class JUCE_API SolidColourBrush : public Brush
  14613. {
  14614. public:
  14615. /** Creates a SolidColourBrush to draw with the given colour.
  14616. The colour can be changed later with the setColour() method.
  14617. */
  14618. SolidColourBrush (const Colour& colour) throw();
  14619. /** Creates a SolidColourBrush set to black.
  14620. The colour can be changed later with the setColour() method.
  14621. */
  14622. SolidColourBrush() throw();
  14623. /** Destructor. */
  14624. ~SolidColourBrush() throw();
  14625. /** Returns the colour currently being used. */
  14626. const Colour& getColour() const throw() { return colour; }
  14627. /** Sets the colour to use for drawing. */
  14628. void setColour (const Colour& newColour) throw() { colour = newColour; }
  14629. Brush* createCopy() const throw();
  14630. void applyTransform (const AffineTransform& transform) throw();
  14631. bool isInvisible() const throw();
  14632. void multiplyOpacity (const float multiple) throw();
  14633. void paintPath (LowLevelGraphicsContext& context,
  14634. const Path& path, const AffineTransform& transform) throw();
  14635. void paintRectangle (LowLevelGraphicsContext& context,
  14636. int x, int y, int w, int h) throw();
  14637. void paintAlphaChannel (LowLevelGraphicsContext& context,
  14638. const Image& alphaChannelImage, int imageX, int imageY,
  14639. int x, int y, int w, int h) throw();
  14640. void paintVerticalLine (LowLevelGraphicsContext& context,
  14641. int x, float y1, float y2) throw();
  14642. void paintHorizontalLine (LowLevelGraphicsContext& context,
  14643. int y, float x1, float x2) throw();
  14644. void paintLine (LowLevelGraphicsContext& context,
  14645. float x1, float y1, float x2, float y2) throw();
  14646. juce_UseDebuggingNewOperator
  14647. private:
  14648. Colour colour;
  14649. SolidColourBrush (const SolidColourBrush&);
  14650. const SolidColourBrush& operator= (const SolidColourBrush&);
  14651. };
  14652. #endif // __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  14653. /********* End of inlined file: juce_SolidColourBrush.h *********/
  14654. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  14655. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14656. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14657. /**
  14658. Defines the method used to postion some kind of rectangular object within
  14659. a rectangular viewport.
  14660. Although similar to Justification, this is more specific, and has some extra
  14661. options.
  14662. */
  14663. class JUCE_API RectanglePlacement
  14664. {
  14665. public:
  14666. /** Creates a RectanglePlacement object using a combination of flags. */
  14667. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  14668. /** Creates a copy of another Justification object. */
  14669. RectanglePlacement (const RectanglePlacement& other) throw();
  14670. /** Copies another Justification object. */
  14671. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  14672. /** Flag values that can be combined and used in the constructor. */
  14673. enum
  14674. {
  14675. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  14676. xLeft = 1,
  14677. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  14678. xRight = 2,
  14679. /** Indicates that the source should be placed in the centre between the left and right
  14680. sides of the available space. */
  14681. xMid = 4,
  14682. /** Indicates that the source's top edge should be aligned with the top edge of the
  14683. destination rectangle. */
  14684. yTop = 8,
  14685. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  14686. destination rectangle. */
  14687. yBottom = 16,
  14688. /** Indicates that the source should be placed in the centre between the top and bottom
  14689. sides of the available space. */
  14690. yMid = 32,
  14691. /** If this flag is set, then the source rectangle will be resized to completely fill
  14692. the destination rectangle, and all other flags are ignored.
  14693. */
  14694. stretchToFit = 64,
  14695. /** If this flag is set, then the source rectangle will be resized so that it is the
  14696. minimum size to completely fill the destination rectangle, without changing its
  14697. aspect ratio. This means that some of the source rectangle may fall outside
  14698. the destination.
  14699. If this flag is not set, the source will be given the maximum size at which none
  14700. of it falls outside the destination rectangle.
  14701. */
  14702. fillDestination = 128,
  14703. /** Indicates that the source rectangle can be reduced in size if required, but should
  14704. never be made larger than its original size.
  14705. */
  14706. onlyReduceInSize = 256,
  14707. /** Indicates that the source rectangle can be enlarged if required, but should
  14708. never be made smaller than its original size.
  14709. */
  14710. onlyIncreaseInSize = 512,
  14711. /** Indicates that the source rectangle's size should be left unchanged.
  14712. */
  14713. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  14714. /** A shorthand value that is equivalent to (xMid | yMid). */
  14715. centred = 4 + 32
  14716. };
  14717. /** Returns the raw flags that are set for this object. */
  14718. inline int getFlags() const throw() { return flags; }
  14719. /** Tests a set of flags for this object.
  14720. @returns true if any of the flags passed in are set on this object.
  14721. */
  14722. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14723. /** Adjusts the position and size of a rectangle to fit it into a space.
  14724. The source rectangle co-ordinates will be adjusted so that they fit into
  14725. the destination rectangle based on this object's flags.
  14726. */
  14727. void applyTo (double& sourceX,
  14728. double& sourceY,
  14729. double& sourceW,
  14730. double& sourceH,
  14731. const double destinationX,
  14732. const double destinationY,
  14733. const double destinationW,
  14734. const double destinationH) const throw();
  14735. /** Returns the transform that should be applied to these source co-ordinates to fit them
  14736. into the destination rectangle using the current flags.
  14737. */
  14738. const AffineTransform getTransformToFit (float sourceX,
  14739. float sourceY,
  14740. float sourceW,
  14741. float sourceH,
  14742. const float destinationX,
  14743. const float destinationY,
  14744. const float destinationW,
  14745. const float destinationH) const throw();
  14746. private:
  14747. int flags;
  14748. };
  14749. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  14750. /********* End of inlined file: juce_RectanglePlacement.h *********/
  14751. class LowLevelGraphicsContext;
  14752. class Image;
  14753. class RectangleList;
  14754. /**
  14755. A graphics context, used for drawing a component or image.
  14756. When a Component needs painting, a Graphics context is passed to its
  14757. Component::paint() method, and this you then call methods within this
  14758. object to actually draw the component's content.
  14759. A Graphics can also be created from an image, to allow drawing directly onto
  14760. that image.
  14761. @see Component::paint
  14762. */
  14763. class JUCE_API Graphics
  14764. {
  14765. public:
  14766. /** Creates a Graphics object to draw directly onto the given image.
  14767. The graphics object that is created will be set up to draw onto the image,
  14768. with the context's clipping area being the entire size of the image, and its
  14769. origin being the image's origin. To draw into a subsection of an image, use the
  14770. reduceClipRegion() and setOrigin() methods.
  14771. Obviously you shouldn't delete the image before this context is deleted.
  14772. */
  14773. Graphics (Image& imageToDrawOnto) throw();
  14774. /** Destructor. */
  14775. ~Graphics() throw();
  14776. /** Changes the current drawing colour.
  14777. This sets the colour that will now be used for drawing operations - it also
  14778. sets the opacity to that of the colour passed-in.
  14779. If a brush is being used when this method is called, the brush will be deselected,
  14780. and any subsequent drawing will be done with a solid colour brush instead.
  14781. @see setOpacity, setBrush, getColour
  14782. */
  14783. void setColour (const Colour& newColour) throw();
  14784. /** Returns the colour that's currently being used.
  14785. This will return the last colour set by setColour(), even if the colour's not
  14786. currently being used for drawing because a brush has been selected instead.
  14787. @see setColour
  14788. */
  14789. const Colour& getCurrentColour() const throw();
  14790. /** Changes the opacity to use with the current colour.
  14791. If a solid colour is being used for drawing, this changes its opacity (and this
  14792. will be reflected by calls to the getColour() method).
  14793. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  14794. */
  14795. void setOpacity (const float newOpacity) throw();
  14796. /** Changes the current brush to use for drawing.
  14797. If a null pointer is passed in, the context will revert to using a solid
  14798. colour for drawing (using the last colour set by setColour()).
  14799. If a brush is passed in, a copy of it will be used for subsequent drawing
  14800. operations until setColour() or setBrush() is called.
  14801. @see SolidColourBrush, GradientBrush, ImageBrush, Brush
  14802. */
  14803. void setBrush (const Brush* const newBrush) throw();
  14804. /** Changes the font to use for subsequent text-drawing functions.
  14805. Note there's also a setFont (float, int) method to quickly change the size and
  14806. style of the current font.
  14807. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  14808. */
  14809. void setFont (const Font& newFont) throw();
  14810. /** Changes the size and style of the currently-selected font.
  14811. This is a convenient shortcut that changes the context's current font to a
  14812. different size or style. The typeface won't be changed.
  14813. @see Font
  14814. */
  14815. void setFont (const float newFontHeight,
  14816. const int fontStyleFlags = Font::plain) throw();
  14817. /** Returns the font that's currently being used for text operations.
  14818. @see setFont
  14819. */
  14820. const Font& getCurrentFont() const throw();
  14821. /** Draws a one-line text string.
  14822. This will use the current colour (or brush) to fill the text. The font is the last
  14823. one specified by setFont().
  14824. @param text the string to draw
  14825. @param startX the position to draw the left-hand edge of the text
  14826. @param baselineY the position of the text's baseline
  14827. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  14828. */
  14829. void drawSingleLineText (const String& text,
  14830. const int startX,
  14831. const int baselineY) const throw();
  14832. /** Draws text across multiple lines.
  14833. This will break the text onto a new line where there's a new-line or
  14834. carriage-return character, or at a word-boundary when the text becomes wider
  14835. than the size specified by the maximumLineWidth parameter.
  14836. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  14837. */
  14838. void drawMultiLineText (const String& text,
  14839. const int startX,
  14840. const int baselineY,
  14841. const int maximumLineWidth) const throw();
  14842. /** Renders a string of text as a vector path.
  14843. This allows a string to be transformed with an arbitrary AffineTransform and
  14844. rendered using the current colour/brush. It's much slower than the normal text methods
  14845. but more accurate.
  14846. @see setFont
  14847. */
  14848. void drawTextAsPath (const String& text,
  14849. const AffineTransform& transform) const throw();
  14850. /** Draws a line of text within a specified rectangle.
  14851. The text will be positioned within the rectangle based on the justification
  14852. flags passed-in. If the string is too long to fit inside the rectangle, it will
  14853. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  14854. flag is true).
  14855. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  14856. */
  14857. void drawText (const String& text,
  14858. const int x,
  14859. const int y,
  14860. const int width,
  14861. const int height,
  14862. const Justification& justificationType,
  14863. const bool useEllipsesIfTooBig) const throw();
  14864. /** Tries to draw a text string inside a given space.
  14865. This does its best to make the given text readable within the specified rectangle,
  14866. so it useful for labelling things.
  14867. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  14868. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  14869. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  14870. it's been truncated.
  14871. A Justification parameter lets you specify how the text is laid out within the rectangle,
  14872. both horizontally and vertically.
  14873. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  14874. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  14875. can set this value to 1.0f.
  14876. @see GlyphArrangement::addFittedText
  14877. */
  14878. void drawFittedText (const String& text,
  14879. const int x,
  14880. const int y,
  14881. const int width,
  14882. const int height,
  14883. const Justification& justificationFlags,
  14884. const int maximumNumberOfLines,
  14885. const float minimumHorizontalScale = 0.7f) const throw();
  14886. /** Fills the context's entire clip region with the current colour or brush.
  14887. (See also the fillAll (const Colour&) method which is a quick way of filling
  14888. it with a given colour).
  14889. */
  14890. void fillAll() const throw();
  14891. /** Fills the context's entire clip region with a given colour.
  14892. This leaves the context's current colour and brush unchanged, it just
  14893. uses the specified colour temporarily.
  14894. */
  14895. void fillAll (const Colour& colourToUse) const throw();
  14896. /** Fills a rectangle with the current colour or brush.
  14897. @see drawRect, fillRoundedRectangle
  14898. */
  14899. void fillRect (int x,
  14900. int y,
  14901. int width,
  14902. int height) const throw();
  14903. /** Fills a rectangle with the current colour or brush. */
  14904. void fillRect (const Rectangle& rectangle) const throw();
  14905. /** Fills a rectangle with the current colour or brush.
  14906. This uses sub-pixel positioning so is slower than the fillRect method which
  14907. takes integer co-ordinates.
  14908. */
  14909. void fillRect (const float x,
  14910. const float y,
  14911. const float width,
  14912. const float height) const throw();
  14913. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14914. @see drawRoundedRectangle, Path::addRoundedRectangle
  14915. */
  14916. void fillRoundedRectangle (const float x,
  14917. const float y,
  14918. const float width,
  14919. const float height,
  14920. const float cornerSize) const throw();
  14921. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  14922. @see drawRoundedRectangle, Path::addRoundedRectangle
  14923. */
  14924. void fillRoundedRectangle (const Rectangle& rectangle,
  14925. const float cornerSize) const throw();
  14926. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  14927. */
  14928. void fillCheckerBoard (int x, int y,
  14929. int width, int height,
  14930. const int checkWidth,
  14931. const int checkHeight,
  14932. const Colour& colour1,
  14933. const Colour& colour2) const throw();
  14934. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14935. The lines are drawn inside the given rectangle, and greater line thicknesses
  14936. extend inwards.
  14937. @see fillRect
  14938. */
  14939. void drawRect (const int x,
  14940. const int y,
  14941. const int width,
  14942. const int height,
  14943. const int lineThickness = 1) const throw();
  14944. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14945. The lines are drawn inside the given rectangle, and greater line thicknesses
  14946. extend inwards.
  14947. @see fillRect
  14948. */
  14949. void drawRect (const float x,
  14950. const float y,
  14951. const float width,
  14952. const float height,
  14953. const float lineThickness = 1.0f) const throw();
  14954. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  14955. The lines are drawn inside the given rectangle, and greater line thicknesses
  14956. extend inwards.
  14957. @see fillRect
  14958. */
  14959. void drawRect (const Rectangle& rectangle,
  14960. const int lineThickness = 1) const throw();
  14961. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14962. @see fillRoundedRectangle, Path::addRoundedRectangle
  14963. */
  14964. void drawRoundedRectangle (const float x,
  14965. const float y,
  14966. const float width,
  14967. const float height,
  14968. const float cornerSize,
  14969. const float lineThickness) const throw();
  14970. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  14971. @see fillRoundedRectangle, Path::addRoundedRectangle
  14972. */
  14973. void drawRoundedRectangle (const Rectangle& rectangle,
  14974. const float cornerSize,
  14975. const float lineThickness) const throw();
  14976. /** Draws a 3D raised (or indented) bevel using two colours.
  14977. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  14978. extend inwards.
  14979. The top-left colour is used for the top- and left-hand edges of the
  14980. bevel; the bottom-right colour is used for the bottom- and right-hand
  14981. edges.
  14982. If useGradient is true, then the bevel fades out to make it look more curved
  14983. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  14984. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  14985. the centre edges are sharp and it fades towards the outside.
  14986. */
  14987. void drawBevel (const int x,
  14988. const int y,
  14989. const int width,
  14990. const int height,
  14991. const int bevelThickness,
  14992. const Colour& topLeftColour = Colours::white,
  14993. const Colour& bottomRightColour = Colours::black,
  14994. const bool useGradient = true,
  14995. const bool sharpEdgeOnOutside = true) const throw();
  14996. /** Draws a pixel using the current colour or brush.
  14997. */
  14998. void setPixel (int x, int y) const throw();
  14999. /** Fills an ellipse with the current colour or brush.
  15000. The ellipse is drawn to fit inside the given rectangle.
  15001. @see drawEllipse, Path::addEllipse
  15002. */
  15003. void fillEllipse (const float x,
  15004. const float y,
  15005. const float width,
  15006. const float height) const throw();
  15007. /** Draws an elliptical stroke using the current colour or brush.
  15008. @see fillEllipse, Path::addEllipse
  15009. */
  15010. void drawEllipse (const float x,
  15011. const float y,
  15012. const float width,
  15013. const float height,
  15014. const float lineThickness) const throw();
  15015. /** Draws a line between two points.
  15016. The line is 1 pixel wide and drawn with the current colour or brush.
  15017. */
  15018. void drawLine (float startX,
  15019. float startY,
  15020. float endX,
  15021. float endY) const throw();
  15022. /** Draws a line between two points with a given thickness.
  15023. @see Path::addLineSegment
  15024. */
  15025. void drawLine (const float startX,
  15026. const float startY,
  15027. const float endX,
  15028. const float endY,
  15029. const float lineThickness) const throw();
  15030. /** Draws a line between two points.
  15031. The line is 1 pixel wide and drawn with the current colour or brush.
  15032. */
  15033. void drawLine (const Line& line) const throw();
  15034. /** Draws a line between two points with a given thickness.
  15035. @see Path::addLineSegment
  15036. */
  15037. void drawLine (const Line& line,
  15038. const float lineThickness) const throw();
  15039. /** Draws a dashed line using a custom set of dash-lengths.
  15040. @param startX the line's start x co-ordinate
  15041. @param startY the line's start y co-ordinate
  15042. @param endX the line's end x co-ordinate
  15043. @param endY the line's end y co-ordinate
  15044. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  15045. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  15046. draw 6 pixels, skip 7 pixels, and then repeat.
  15047. @param numDashLengths the number of elements in the array (this must be an even number).
  15048. @param lineThickness the thickness of the line to draw
  15049. @see PathStrokeType::createDashedStroke
  15050. */
  15051. void drawDashedLine (const float startX,
  15052. const float startY,
  15053. const float endX,
  15054. const float endY,
  15055. const float* const dashLengths,
  15056. const int numDashLengths,
  15057. const float lineThickness = 1.0f) const throw();
  15058. /** Draws a vertical line of pixels at a given x position.
  15059. The x position is an integer, but the top and bottom of the line can be sub-pixel
  15060. positions, and these will be anti-aliased if necessary.
  15061. */
  15062. void drawVerticalLine (const int x, float top, float bottom) const throw();
  15063. /** Draws a horizontal line of pixels at a given y position.
  15064. The y position is an integer, but the left and right ends of the line can be sub-pixel
  15065. positions, and these will be anti-aliased if necessary.
  15066. */
  15067. void drawHorizontalLine (const int y, float left, float right) const throw();
  15068. /** Fills a path using the currently selected colour or brush.
  15069. */
  15070. void fillPath (const Path& path,
  15071. const AffineTransform& transform = AffineTransform::identity) const throw();
  15072. /** Draws a path's outline using the currently selected colour or brush.
  15073. */
  15074. void strokePath (const Path& path,
  15075. const PathStrokeType& strokeType,
  15076. const AffineTransform& transform = AffineTransform::identity) const throw();
  15077. /** Draws a line with an arrowhead.
  15078. @param startX the line's start x co-ordinate
  15079. @param startY the line's start y co-ordinate
  15080. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  15081. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  15082. @param lineThickness the thickness of the line
  15083. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  15084. @param arrowheadLength the length of the arrow head (along the length of the line)
  15085. */
  15086. void drawArrow (const float startX,
  15087. const float startY,
  15088. const float endX,
  15089. const float endY,
  15090. const float lineThickness,
  15091. const float arrowheadWidth,
  15092. const float arrowheadLength) const throw();
  15093. /** Types of rendering quality that can be specified when drawing images.
  15094. @see blendImage, Graphics::setImageResamplingQuality
  15095. */
  15096. enum ResamplingQuality
  15097. {
  15098. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  15099. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  15100. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  15101. };
  15102. /** Changes the quality that will be used when resampling images.
  15103. By default a Graphics object will be set to mediumRenderingQuality.
  15104. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  15105. */
  15106. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  15107. /** Draws an image.
  15108. This will draw the whole of an image, positioning its top-left corner at the
  15109. given co-ordinates, and keeping its size the same. This is the simplest image
  15110. drawing method - the others give more control over the scaling and clipping
  15111. of the images.
  15112. Images are composited using the context's current opacity, so if you
  15113. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  15114. (or setColour() with an opaque colour) before drawing images.
  15115. */
  15116. void drawImageAt (const Image* const imageToDraw,
  15117. const int topLeftX,
  15118. const int topLeftY,
  15119. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  15120. /** Draws part of an image, rescaling it to fit in a given target region.
  15121. The specified area of the source image is rescaled and drawn to fill the
  15122. specifed destination rectangle.
  15123. Images are composited using the context's current opacity, so if you
  15124. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  15125. (or setColour() with an opaque colour) before drawing images.
  15126. @param imageToDraw the image to overlay
  15127. @param destX the left of the destination rectangle
  15128. @param destY the top of the destination rectangle
  15129. @param destWidth the width of the destination rectangle
  15130. @param destHeight the height of the destination rectangle
  15131. @param sourceX the left of the rectangle to copy from the source image
  15132. @param sourceY the top of the rectangle to copy from the source image
  15133. @param sourceWidth the width of the rectangle to copy from the source image
  15134. @param sourceHeight the height of the rectangle to copy from the source image
  15135. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  15136. the source image's alpha channel is used as a mask with
  15137. which to fill the destination using the current colour
  15138. or brush. (If the source is has no alpha channel, then
  15139. it will just fill the target with a solid rectangle)
  15140. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  15141. */
  15142. void drawImage (const Image* const imageToDraw,
  15143. int destX,
  15144. int destY,
  15145. int destWidth,
  15146. int destHeight,
  15147. int sourceX,
  15148. int sourceY,
  15149. int sourceWidth,
  15150. int sourceHeight,
  15151. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  15152. /** Draws part of an image, having applied an affine transform to it.
  15153. This lets you throw the image around in some wacky ways, rotate it, shear,
  15154. scale it, etc.
  15155. A clipping subregion is specified within the source image and no pixels
  15156. outside this region will be used.
  15157. Images are composited using the context's current opacity, so if you
  15158. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  15159. (or setColour() with an opaque colour) before drawing images.
  15160. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  15161. are ignored and it is filled with the current brush, masked by its alpha channel.
  15162. @see setImageResamplingQuality, drawImage
  15163. */
  15164. void drawImageTransformed (const Image* const imageToDraw,
  15165. int sourceClipX,
  15166. int sourceClipY,
  15167. int sourceClipWidth,
  15168. int sourceClipHeight,
  15169. const AffineTransform& transform,
  15170. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  15171. /** Draws an image to fit within a designated rectangle.
  15172. If the image is too big or too small for the space, it will be rescaled
  15173. to fit as nicely as it can do without affecting its aspect ratio. It will
  15174. then be placed within the target rectangle according to the justification flags
  15175. specified.
  15176. @param imageToDraw the source image to draw
  15177. @param destX top-left of the target rectangle to fit it into
  15178. @param destY top-left of the target rectangle to fit it into
  15179. @param destWidth size of the target rectangle to fit the image into
  15180. @param destHeight size of the target rectangle to fit the image into
  15181. @param placementWithinTarget this specifies how the image should be positioned
  15182. within the target rectangle - see the RectanglePlacement
  15183. class for more details about this.
  15184. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  15185. alpha channel will be used as a mask with which to
  15186. draw with the current brush or colour. This is
  15187. similar to fillAlphaMap(), and see also drawImage()
  15188. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  15189. */
  15190. void drawImageWithin (const Image* const imageToDraw,
  15191. const int destX,
  15192. const int destY,
  15193. const int destWidth,
  15194. const int destHeight,
  15195. const RectanglePlacement& placementWithinTarget,
  15196. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  15197. /** Returns the position of the bounding box for the current clipping region.
  15198. @see getClipRegion, clipRegionIntersects
  15199. */
  15200. const Rectangle getClipBounds() const throw();
  15201. /** Checks whether a rectangle overlaps the context's clipping region.
  15202. If this returns false, no part of the given area can be drawn onto, so this
  15203. method can be used to optimise a component's paint() method, by letting it
  15204. avoid drawing complex objects that aren't within the region being repainted.
  15205. */
  15206. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  15207. /** Intersects the current clipping region with another region.
  15208. @returns true if the resulting clipping region is non-zero in size
  15209. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  15210. */
  15211. bool reduceClipRegion (const int x, const int y,
  15212. const int width, const int height) throw();
  15213. /** Intersects the current clipping region with a rectangle list region.
  15214. @returns true if the resulting clipping region is non-zero in size
  15215. @see setOrigin, clipRegionIntersects, getClipLeft, getClipRight, getClipWidth, getClipHeight
  15216. */
  15217. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  15218. /** Excludes a rectangle to stop it being drawn into. */
  15219. void excludeClipRegion (const int x, const int y,
  15220. const int width, const int height) throw();
  15221. /** Returns true if no drawing can be done because the clip region is zero. */
  15222. bool isClipEmpty() const throw();
  15223. /** Saves the current graphics state on an internal stack.
  15224. To restore the state, use restoreState().
  15225. */
  15226. void saveState() throw();
  15227. /** Restores a graphics state that was previously saved with saveState().
  15228. */
  15229. void restoreState() throw();
  15230. /** Moves the position of the context's origin.
  15231. This changes the position that the context considers to be (0, 0) to
  15232. the specified position.
  15233. So if you call setOrigin (100, 100), then the position that was previously
  15234. referred to as (100, 100) will subsequently be considered to be (0, 0).
  15235. @see reduceClipRegion
  15236. */
  15237. void setOrigin (const int newOriginX,
  15238. const int newOriginY) throw();
  15239. /** Resets the current colour, brush, and font to default settings. */
  15240. void resetToDefaultState() throw();
  15241. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  15242. bool isVectorDevice() const throw();
  15243. juce_UseDebuggingNewOperator
  15244. /** Create a graphics that uses a given low-level renderer.
  15245. For internal use only.
  15246. NB. The context will NOT be deleted by this object when it is deleted.
  15247. */
  15248. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  15249. /** @internal */
  15250. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  15251. private:
  15252. LowLevelGraphicsContext* const context;
  15253. const bool ownsContext;
  15254. struct GraphicsState
  15255. {
  15256. GraphicsState() throw();
  15257. GraphicsState (const GraphicsState&) throw();
  15258. ~GraphicsState() throw();
  15259. Colour colour;
  15260. Brush* brush;
  15261. Font font;
  15262. ResamplingQuality quality;
  15263. };
  15264. GraphicsState* state;
  15265. OwnedArray <GraphicsState> stateStack;
  15266. bool saveStatePending;
  15267. void saveStateIfPending() throw();
  15268. const Graphics& operator= (const Graphics& other);
  15269. Graphics (const Graphics&);
  15270. };
  15271. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  15272. /********* End of inlined file: juce_Graphics.h *********/
  15273. /**
  15274. A graphical effect filter that can be applied to components.
  15275. An ImageEffectFilter can be applied to the image that a component
  15276. paints before it hits the screen.
  15277. This is used for adding effects like shadows, blurs, etc.
  15278. @see Component::setComponentEffect
  15279. */
  15280. class JUCE_API ImageEffectFilter
  15281. {
  15282. public:
  15283. /** Overridden to render the effect.
  15284. The implementation of this method must use the image that is passed in
  15285. as its source, and should render its output to the graphics context passed in.
  15286. @param sourceImage the image that the source component has just rendered with
  15287. its paint() method. The image may or may not have an alpha
  15288. channel, depending on whether the component is opaque.
  15289. @param destContext the graphics context to use to draw the resultant image.
  15290. */
  15291. virtual void applyEffect (Image& sourceImage,
  15292. Graphics& destContext) = 0;
  15293. /** Destructor. */
  15294. virtual ~ImageEffectFilter() {}
  15295. };
  15296. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15297. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  15298. /********* Start of inlined file: juce_RectangleList.h *********/
  15299. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  15300. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  15301. /**
  15302. Maintains a set of rectangles as a complex region.
  15303. This class allows a set of rectangles to be treated as a solid shape, and can
  15304. add and remove rectangular sections of it, and simplify overlapping or
  15305. adjacent rectangles.
  15306. @see Rectangle
  15307. */
  15308. class JUCE_API RectangleList
  15309. {
  15310. public:
  15311. /** Creates an empty RectangleList */
  15312. RectangleList() throw();
  15313. /** Creates a copy of another list */
  15314. RectangleList (const RectangleList& other) throw();
  15315. /** Creates a list containing just one rectangle. */
  15316. RectangleList (const Rectangle& rect) throw();
  15317. /** Copies this list from another one. */
  15318. const RectangleList& operator= (const RectangleList& other) throw();
  15319. /** Destructor. */
  15320. ~RectangleList() throw();
  15321. /** Returns true if the region is empty. */
  15322. bool isEmpty() const throw();
  15323. /** Returns the number of rectangles in the list. */
  15324. int getNumRectangles() const throw() { return rects.size(); }
  15325. /** Returns one of the rectangles at a particular index.
  15326. @returns the rectangle at the index, or an empty rectangle if the
  15327. index is out-of-range.
  15328. */
  15329. const Rectangle getRectangle (const int index) const throw();
  15330. /** Removes all rectangles to leave an empty region. */
  15331. void clear() throw();
  15332. /** Merges a new rectangle into the list.
  15333. The rectangle being added will first be clipped to remove any parts of it
  15334. that overlap existing rectangles in the list.
  15335. */
  15336. void add (const int x, const int y,
  15337. const int w, const int h) throw();
  15338. /** Merges a new rectangle into the list.
  15339. The rectangle being added will first be clipped to remove any parts of it
  15340. that overlap existing rectangles in the list, and adjacent rectangles will be
  15341. merged into it.
  15342. */
  15343. void add (const Rectangle& rect) throw();
  15344. /** Dumbly adds a rectangle to the list without checking for overlaps.
  15345. This simply adds the rectangle to the end, it doesn't merge it or remove
  15346. any overlapping bits.
  15347. */
  15348. void addWithoutMerging (const Rectangle& rect) throw();
  15349. /** Merges another rectangle list into this one.
  15350. Any overlaps between the two lists will be clipped, so that the result is
  15351. the union of both lists.
  15352. */
  15353. void add (const RectangleList& other) throw();
  15354. /** Removes a rectangular region from the list.
  15355. Any rectangles in the list which overlap this will be clipped and subdivided
  15356. if necessary.
  15357. */
  15358. void subtract (const Rectangle& rect) throw();
  15359. /** Removes all areas in another RectangleList from this one.
  15360. Any rectangles in the list which overlap this will be clipped and subdivided
  15361. if necessary.
  15362. */
  15363. void subtract (const RectangleList& otherList) throw();
  15364. /** Removes any areas of the region that lie outside a given rectangle.
  15365. Any rectangles in the list which overlap this will be clipped and subdivided
  15366. if necessary.
  15367. Returns true if the resulting region is not empty, false if it is empty.
  15368. @see getIntersectionWith
  15369. */
  15370. bool clipTo (const Rectangle& rect) throw();
  15371. /** Removes any areas of the region that lie outside a given rectangle list.
  15372. Any rectangles in this object which overlap the specified list will be clipped
  15373. and subdivided if necessary.
  15374. Returns true if the resulting region is not empty, false if it is empty.
  15375. @see getIntersectionWith
  15376. */
  15377. bool clipTo (const RectangleList& other) throw();
  15378. /** Creates a region which is the result of clipping this one to a given rectangle.
  15379. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  15380. resulting region into the list whose reference is passed-in.
  15381. Returns true if the resulting region is not empty, false if it is empty.
  15382. @see clipTo
  15383. */
  15384. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  15385. /** Swaps the contents of this and another list.
  15386. This swaps their internal pointers, so is hugely faster than using copy-by-value
  15387. to swap them.
  15388. */
  15389. void swapWith (RectangleList& otherList) throw();
  15390. /** Checks whether the region contains a given point.
  15391. @returns true if the point lies within one of the rectangles in the list
  15392. */
  15393. bool containsPoint (const int x, const int y) const throw();
  15394. /** Checks whether the region contains the whole of a given rectangle.
  15395. @returns true all parts of the rectangle passed in lie within the region
  15396. defined by this object
  15397. @see intersectsRectangle, containsPoint
  15398. */
  15399. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  15400. /** Checks whether the region contains any part of a given rectangle.
  15401. @returns true if any part of the rectangle passed in lies within the region
  15402. defined by this object
  15403. @see containsRectangle
  15404. */
  15405. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  15406. /** Checks whether this region intersects any part of another one.
  15407. @see intersectsRectangle
  15408. */
  15409. bool intersects (const RectangleList& other) const throw();
  15410. /** Returns the smallest rectangle that can enclose the whole of this region. */
  15411. const Rectangle getBounds() const throw();
  15412. /** Optimises the list into a minimum number of constituent rectangles.
  15413. This will try to combine any adjacent rectangles into larger ones where
  15414. possible, to simplify lists that might have been fragmented by repeated
  15415. add/subtract calls.
  15416. */
  15417. void consolidate() throw();
  15418. /** Adds an x and y value to all the co-ordinates. */
  15419. void offsetAll (const int dx, const int dy) throw();
  15420. /** Creates a Path object to represent this region. */
  15421. const Path toPath() const throw();
  15422. /** An iterator for accessing all the rectangles in a RectangleList. */
  15423. class Iterator
  15424. {
  15425. public:
  15426. Iterator (const RectangleList& list) throw();
  15427. ~Iterator() throw();
  15428. /** Advances to the next rectangle, and returns true if it's not finished.
  15429. Call this before using getRectangle() to find the rectangle that was returned.
  15430. */
  15431. bool next() throw();
  15432. /** Returns the current rectangle. */
  15433. const Rectangle* getRectangle() const throw() { return current; }
  15434. juce_UseDebuggingNewOperator
  15435. private:
  15436. const Rectangle* current;
  15437. const RectangleList& owner;
  15438. int index;
  15439. Iterator (const Iterator&);
  15440. const Iterator& operator= (const Iterator&);
  15441. };
  15442. juce_UseDebuggingNewOperator
  15443. private:
  15444. friend class Iterator;
  15445. Array <Rectangle> rects;
  15446. };
  15447. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  15448. /********* End of inlined file: juce_RectangleList.h *********/
  15449. /********* Start of inlined file: juce_BorderSize.h *********/
  15450. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  15451. #define __JUCE_BORDERSIZE_JUCEHEADER__
  15452. /**
  15453. Specifies a set of gaps to be left around the sides of a rectangle.
  15454. This is basically the size of the spaces at the top, bottom, left and right of
  15455. a rectangle. It's used by various component classes to specify borders.
  15456. @see Rectangle
  15457. */
  15458. class JUCE_API BorderSize
  15459. {
  15460. public:
  15461. /** Creates a null border.
  15462. All sizes are left as 0.
  15463. */
  15464. BorderSize() throw();
  15465. /** Creates a copy of another border. */
  15466. BorderSize (const BorderSize& other) throw();
  15467. /** Creates a border with the given gaps. */
  15468. BorderSize (const int topGap,
  15469. const int leftGap,
  15470. const int bottomGap,
  15471. const int rightGap) throw();
  15472. /** Creates a border with the given gap on all sides. */
  15473. BorderSize (const int allGaps) throw();
  15474. /** Destructor. */
  15475. ~BorderSize() throw();
  15476. /** Returns the gap that should be left at the top of the region. */
  15477. int getTop() const throw() { return top; }
  15478. /** Returns the gap that should be left at the top of the region. */
  15479. int getLeft() const throw() { return left; }
  15480. /** Returns the gap that should be left at the top of the region. */
  15481. int getBottom() const throw() { return bottom; }
  15482. /** Returns the gap that should be left at the top of the region. */
  15483. int getRight() const throw() { return right; }
  15484. /** Returns the sum of the top and bottom gaps. */
  15485. int getTopAndBottom() const throw() { return top + bottom; }
  15486. /** Returns the sum of the left and right gaps. */
  15487. int getLeftAndRight() const throw() { return left + right; }
  15488. /** Changes the top gap. */
  15489. void setTop (const int newTopGap) throw();
  15490. /** Changes the left gap. */
  15491. void setLeft (const int newLeftGap) throw();
  15492. /** Changes the bottom gap. */
  15493. void setBottom (const int newBottomGap) throw();
  15494. /** Changes the right gap. */
  15495. void setRight (const int newRightGap) throw();
  15496. /** Returns a rectangle with these borders removed from it. */
  15497. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  15498. /** Removes this border from a given rectangle. */
  15499. void subtractFrom (Rectangle& rectangle) const throw();
  15500. /** Returns a rectangle with these borders added around it. */
  15501. const Rectangle addedTo (const Rectangle& original) const throw();
  15502. /** Adds this border around a given rectangle. */
  15503. void addTo (Rectangle& original) const throw();
  15504. bool operator== (const BorderSize& other) const throw();
  15505. bool operator!= (const BorderSize& other) const throw();
  15506. juce_UseDebuggingNewOperator
  15507. private:
  15508. int top, left, bottom, right;
  15509. };
  15510. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  15511. /********* End of inlined file: juce_BorderSize.h *********/
  15512. /********* Start of inlined file: juce_ComponentPeer.h *********/
  15513. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  15514. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  15515. class Component;
  15516. class Graphics;
  15517. /********* Start of inlined file: juce_MessageListener.h *********/
  15518. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  15519. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  15520. /********* Start of inlined file: juce_Message.h *********/
  15521. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  15522. #define __JUCE_MESSAGE_JUCEHEADER__
  15523. class MessageListener;
  15524. class MessageManager;
  15525. /** The base class for objects that can be delivered to a MessageListener.
  15526. The simplest Message object contains a few integer and pointer parameters
  15527. that the user can set, and this is enough for a lot of purposes. For passing more
  15528. complex data, subclasses of Message can also be used.
  15529. @see MessageListener, MessageManager, ActionListener, ChangeListener
  15530. */
  15531. class JUCE_API Message
  15532. {
  15533. public:
  15534. /** Creates an uninitialised message.
  15535. The class's variables will also be left uninitialised.
  15536. */
  15537. Message() throw();
  15538. /** Creates a message object, filling in the member variables.
  15539. The corresponding public member variables will be set from the parameters
  15540. passed in.
  15541. */
  15542. Message (const int intParameter1,
  15543. const int intParameter2,
  15544. const int intParameter3,
  15545. void* const pointerParameter) throw();
  15546. /** Destructor. */
  15547. virtual ~Message() throw();
  15548. // These values can be used for carrying simple data that the application needs to
  15549. // pass around. For more complex messages, just create a subclass.
  15550. int intParameter1; /**< user-defined integer value. */
  15551. int intParameter2; /**< user-defined integer value. */
  15552. int intParameter3; /**< user-defined integer value. */
  15553. void* pointerParameter; /**< user-defined pointer value. */
  15554. juce_UseDebuggingNewOperator
  15555. private:
  15556. friend class MessageListener;
  15557. friend class MessageManager;
  15558. MessageListener* messageRecipient;
  15559. Message (const Message&);
  15560. const Message& operator= (const Message&);
  15561. };
  15562. #endif // __JUCE_MESSAGE_JUCEHEADER__
  15563. /********* End of inlined file: juce_Message.h *********/
  15564. /**
  15565. MessageListener subclasses can post and receive Message objects.
  15566. @see Message, MessageManager, ActionListener, ChangeListener
  15567. */
  15568. class JUCE_API MessageListener
  15569. {
  15570. protected:
  15571. /** Creates a MessageListener. */
  15572. MessageListener() throw();
  15573. public:
  15574. /** Destructor.
  15575. When a MessageListener is deleted, it removes itself from a global list
  15576. of registered listeners, so that the isValidMessageListener() method
  15577. will no longer return true.
  15578. */
  15579. virtual ~MessageListener();
  15580. /** This is the callback method that receives incoming messages.
  15581. This is called by the MessageManager from its dispatch loop.
  15582. @see postMessage
  15583. */
  15584. virtual void handleMessage (const Message& message) = 0;
  15585. /** Sends a message to the message queue, for asynchronous delivery to this listener
  15586. later on.
  15587. This method can be called safely by any thread.
  15588. @param message the message object to send - this will be deleted
  15589. automatically by the message queue, so don't keep any
  15590. references to it after calling this method.
  15591. @see handleMessage
  15592. */
  15593. void postMessage (Message* const message) const throw();
  15594. /** Checks whether this MessageListener has been deleted.
  15595. Although not foolproof, this method is safe to call on dangling or null
  15596. pointers. A list of active MessageListeners is kept internally, so this
  15597. checks whether the object is on this list or not.
  15598. Note that it's possible to get a false-positive here, if an object is
  15599. deleted and another is subsequently created that happens to be at the
  15600. exact same memory location, but I can't think of a good way of avoiding
  15601. this.
  15602. */
  15603. bool isValidMessageListener() const throw();
  15604. };
  15605. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  15606. /********* End of inlined file: juce_MessageListener.h *********/
  15607. class ComponentBoundsConstrainer;
  15608. class ComponentDeletionWatcher;
  15609. /**
  15610. The base class for window objects that wrap a component as a real operating
  15611. system object.
  15612. This is an abstract base class - the platform specific code contains default
  15613. implementations of it that create and manage windows.
  15614. @see Component::createNewPeer
  15615. */
  15616. class JUCE_API ComponentPeer : public MessageListener
  15617. {
  15618. public:
  15619. /** A combination of these flags is passed to the ComponentPeer constructor. */
  15620. enum StyleFlags
  15621. {
  15622. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  15623. entry on the taskbar (ignored on MacOSX) */
  15624. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  15625. tooltip, etc. */
  15626. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  15627. through it (may not be possible on some platforms). */
  15628. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  15629. title bar and frame\. if not specified, the window will be
  15630. borderless. */
  15631. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  15632. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  15633. minimise button on it. */
  15634. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  15635. maximise button on it. */
  15636. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  15637. close button on it. */
  15638. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  15639. not be possible on all platforms). */
  15640. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  15641. do its own repainting, but only to repaint when the
  15642. performAnyPendingRepaintsNow() method is called. */
  15643. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  15644. be used for things like plugin windows, to stop them interfering
  15645. with the host's shortcut keys */
  15646. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  15647. };
  15648. /** Creates a peer.
  15649. The component is the one that we intend to represent, and the style flags are
  15650. a combination of the values in the StyleFlags enum
  15651. */
  15652. ComponentPeer (Component* const component,
  15653. const int styleFlags) throw();
  15654. /** Destructor. */
  15655. virtual ~ComponentPeer();
  15656. /** Returns the component being represented by this peer. */
  15657. Component* getComponent() const throw() { return component; }
  15658. /** Returns the set of style flags that were set when the window was created.
  15659. @see Component::addToDesktop
  15660. */
  15661. int getStyleFlags() const throw() { return styleFlags; }
  15662. /** Returns the raw handle to whatever kind of window is being used.
  15663. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  15664. but rememeber there's no guarantees what you'll get back.
  15665. */
  15666. virtual void* getNativeHandle() const = 0;
  15667. /** Shows or hides the window. */
  15668. virtual void setVisible (bool shouldBeVisible) = 0;
  15669. /** Changes the title of the window. */
  15670. virtual void setTitle (const String& title) = 0;
  15671. /** Moves the window without changing its size.
  15672. If the native window is contained in another window, then the co-ordinates are
  15673. relative to the parent window's origin, not the screen origin.
  15674. This should result in a callback to handleMovedOrResized().
  15675. */
  15676. virtual void setPosition (int x, int y) = 0;
  15677. /** Resizes the window without changing its position.
  15678. This should result in a callback to handleMovedOrResized().
  15679. */
  15680. virtual void setSize (int w, int h) = 0;
  15681. /** Moves and resizes the window.
  15682. If the native window is contained in another window, then the co-ordinates are
  15683. relative to the parent window's origin, not the screen origin.
  15684. This should result in a callback to handleMovedOrResized().
  15685. */
  15686. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  15687. /** Returns the current position and size of the window.
  15688. If the native window is contained in another window, then the co-ordinates are
  15689. relative to the parent window's origin, not the screen origin.
  15690. */
  15691. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  15692. /** Returns the x-position of this window, relative to the screen's origin. */
  15693. virtual int getScreenX() const = 0;
  15694. /** Returns the y-position of this window, relative to the screen's origin. */
  15695. virtual int getScreenY() const = 0;
  15696. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  15697. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  15698. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  15699. virtual void globalPositionToRelative (int& x, int& y) = 0;
  15700. /** Minimises the window. */
  15701. virtual void setMinimised (bool shouldBeMinimised) = 0;
  15702. /** True if the window is currently minimised. */
  15703. virtual bool isMinimised() const = 0;
  15704. /** Enable/disable fullscreen mode for the window. */
  15705. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  15706. /** True if the window is currently full-screen. */
  15707. virtual bool isFullScreen() const = 0;
  15708. /** Sets the size to restore to if fullscreen mode is turned off. */
  15709. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  15710. /** Returns the size to restore to if fullscreen mode is turned off. */
  15711. const Rectangle& getNonFullScreenBounds() const throw();
  15712. /** Attempts to change the icon associated with this window.
  15713. */
  15714. virtual void setIcon (const Image& newIcon) = 0;
  15715. /** Sets a constrainer to use if the peer can resize itself.
  15716. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  15717. */
  15718. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  15719. /** Returns the current constrainer, if one has been set. */
  15720. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  15721. /** Checks if a point is in the window.
  15722. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  15723. is false, then this returns false if the point is actually inside a child of this
  15724. window.
  15725. */
  15726. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  15727. /** Returns the size of the window frame that's around this window.
  15728. Whether or not the window has a normal window frame depends on the flags
  15729. that were set when the window was created by Component::addToDesktop()
  15730. */
  15731. virtual const BorderSize getFrameSize() const = 0;
  15732. /** This is called when the window's bounds change.
  15733. A peer implementation must call this when the window is moved and resized, so that
  15734. this method can pass the message on to the component.
  15735. */
  15736. void handleMovedOrResized();
  15737. /** This is called if the screen resolution changes.
  15738. A peer implementation must call this if the monitor arrangement changes or the available
  15739. screen size changes.
  15740. */
  15741. void handleScreenSizeChange();
  15742. /** This is called to repaint the component into the given context. */
  15743. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  15744. /** Sets this window to either be always-on-top or normal.
  15745. Some kinds of window might not be able to do this, so should return false.
  15746. */
  15747. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  15748. /** Brings the window to the top, optionally also giving it focus. */
  15749. virtual void toFront (bool makeActive) = 0;
  15750. /** Moves the window to be just behind another one. */
  15751. virtual void toBehind (ComponentPeer* other) = 0;
  15752. /** Called when the window is brought to the front, either by the OS or by a call
  15753. to toFront().
  15754. */
  15755. void handleBroughtToFront();
  15756. /** True if the window has the keyboard focus. */
  15757. virtual bool isFocused() const = 0;
  15758. /** Tries to give the window keyboard focus. */
  15759. virtual void grabFocus() = 0;
  15760. /** Tells the window that text input may be required at the given position.
  15761. This may cause things like a virtual on-screen keyboard to appear, depending
  15762. on the OS.
  15763. */
  15764. virtual void textInputRequired (int x, int y) = 0;
  15765. /** Called when the window gains keyboard focus. */
  15766. void handleFocusGain();
  15767. /** Called when the window loses keyboard focus. */
  15768. void handleFocusLoss();
  15769. Component* getLastFocusedSubcomponent() const throw();
  15770. /** Called when a key is pressed.
  15771. For keycode info, see the KeyPress class.
  15772. Returns true if the keystroke was used.
  15773. */
  15774. bool handleKeyPress (const int keyCode,
  15775. const juce_wchar textCharacter);
  15776. /** Called whenever a key is pressed or released.
  15777. Returns true if the keystroke was used.
  15778. */
  15779. bool handleKeyUpOrDown (const bool isKeyDown);
  15780. /** Called whenever a modifier key is pressed or released. */
  15781. void handleModifierKeysChange();
  15782. /** Invalidates a region of the window to be repainted asynchronously. */
  15783. virtual void repaint (int x, int y, int w, int h) = 0;
  15784. /** This can be called (from the message thread) to cause the immediate redrawing
  15785. of any areas of this window that need repainting.
  15786. You shouldn't ever really need to use this, it's mainly for special purposes
  15787. like supporting audio plugins where the host's event loop is out of our control.
  15788. */
  15789. virtual void performAnyPendingRepaintsNow() = 0;
  15790. void handleMouseEnter (int x, int y, const int64 time);
  15791. void handleMouseMove (int x, int y, const int64 time);
  15792. void handleMouseDown (int x, int y, const int64 time);
  15793. void handleMouseDrag (int x, int y, const int64 time);
  15794. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  15795. void handleMouseExit (int x, int y, const int64 time);
  15796. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  15797. /** Causes a mouse-move callback to be made asynchronously. */
  15798. void sendFakeMouseMove() throw();
  15799. void handleUserClosingWindow();
  15800. void handleFileDragMove (const StringArray& files, int x, int y);
  15801. void handleFileDragExit (const StringArray& files);
  15802. void handleFileDragDrop (const StringArray& files, int x, int y);
  15803. /** Resets the masking region.
  15804. The subclass should call this every time it's about to call the handlePaint
  15805. method.
  15806. @see addMaskedRegion
  15807. */
  15808. void clearMaskedRegion() throw();
  15809. /** Adds a rectangle to the set of areas not to paint over.
  15810. A component can call this on its peer during its paint() method, to signal
  15811. that the painting code should ignore a given region. The reason
  15812. for this is to stop embedded windows (such as OpenGL) getting painted over.
  15813. The masked region is cleared each time before a paint happens, so a component
  15814. will have to make sure it calls this every time it's painted.
  15815. */
  15816. void addMaskedRegion (int x, int y, int w, int h) throw();
  15817. /** Returns the number of currently-active peers.
  15818. @see getPeer
  15819. */
  15820. static int getNumPeers() throw();
  15821. /** Returns one of the currently-active peers.
  15822. @see getNumPeers
  15823. */
  15824. static ComponentPeer* getPeer (const int index) throw();
  15825. /** Checks if this peer object is valid.
  15826. @see getNumPeers
  15827. */
  15828. static bool isValidPeer (const ComponentPeer* const peer) throw();
  15829. static void bringModalComponentToFront();
  15830. juce_UseDebuggingNewOperator
  15831. protected:
  15832. Component* const component;
  15833. const int styleFlags;
  15834. RectangleList maskedRegion;
  15835. Rectangle lastNonFullscreenBounds;
  15836. uint32 lastPaintTime;
  15837. ComponentBoundsConstrainer* constrainer;
  15838. static void updateCurrentModifiers() throw();
  15839. /** @internal */
  15840. void handleMessage (const Message& message);
  15841. private:
  15842. Component* lastFocusedComponent;
  15843. ComponentDeletionWatcher* dragAndDropTargetComponent;
  15844. Component* lastDragAndDropCompUnderMouse;
  15845. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  15846. friend class Component;
  15847. static ComponentPeer* getPeerFor (const Component* const component) throw();
  15848. void setLastDragDropTarget (Component* comp);
  15849. ComponentPeer (const ComponentPeer&);
  15850. const ComponentPeer& operator= (const ComponentPeer&);
  15851. };
  15852. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  15853. /********* End of inlined file: juce_ComponentPeer.h *********/
  15854. class LookAndFeel;
  15855. /**
  15856. The base class for all JUCE user-interface objects.
  15857. */
  15858. class JUCE_API Component : public MouseListener,
  15859. protected MessageListener
  15860. {
  15861. public:
  15862. /** Creates a component.
  15863. To get it to actually appear, you'll also need to:
  15864. - Either add it to a parent component or use the addToDesktop() method to
  15865. make it a desktop window
  15866. - Set its size and position to something sensible
  15867. - Use setVisible() to make it visible
  15868. And for it to serve any useful purpose, you'll need to write a
  15869. subclass of Component or use one of the other types of component from
  15870. the library.
  15871. */
  15872. Component() throw();
  15873. /** Destructor.
  15874. Note that when a component is deleted, any child components it might
  15875. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  15876. */
  15877. virtual ~Component();
  15878. /** Creates a component, setting its name at the same time.
  15879. @see getName, setName
  15880. */
  15881. Component (const String& componentName) throw();
  15882. /** Returns the name of this component.
  15883. @see setName
  15884. */
  15885. const String& getName() const throw() { return componentName_; }
  15886. /** Sets the name of this component.
  15887. When the name changes, all registered ComponentListeners will receive a
  15888. ComponentListener::componentNameChanged() callback.
  15889. @see getName
  15890. */
  15891. virtual void setName (const String& newName);
  15892. /** Checks whether this Component object has been deleted.
  15893. This will check whether this object is still a valid component, or whether
  15894. it's been deleted.
  15895. It's safe to call this on null or dangling pointers, but note that there is a
  15896. small risk if another new (but different) component has been created at the
  15897. same memory address which this one occupied, this methods can return a
  15898. false positive.
  15899. */
  15900. bool isValidComponent() const throw();
  15901. /** Makes the component visible or invisible.
  15902. This method will show or hide the component.
  15903. Note that components default to being non-visible when first created.
  15904. Also note that visible components won't be seen unless all their parent components
  15905. are also visible.
  15906. This method will call visibilityChanged() and also componentVisibilityChanged()
  15907. for any component listeners that are interested in this component.
  15908. @param shouldBeVisible whether to show or hide the component
  15909. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  15910. */
  15911. virtual void setVisible (bool shouldBeVisible);
  15912. /** Tests whether the component is visible or not.
  15913. this doesn't necessarily tell you whether this comp is actually on the screen
  15914. because this depends on whether all the parent components are also visible - use
  15915. isShowing() to find this out.
  15916. @see isShowing, setVisible
  15917. */
  15918. bool isVisible() const throw() { return flags.visibleFlag; }
  15919. /** Called when this component's visiblility changes.
  15920. @see setVisible, isVisible
  15921. */
  15922. virtual void visibilityChanged();
  15923. /** Tests whether this component and all its parents are visible.
  15924. @returns true only if this component and all its parents are visible.
  15925. @see isVisible
  15926. */
  15927. bool isShowing() const throw();
  15928. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  15929. To do this, this function will cunningly:
  15930. - take a snapshot of the component as it currently looks
  15931. - call setVisible(false) on the component
  15932. - replace it with a special component that will continue drawing the
  15933. snapshot, animating it and gradually making it more transparent
  15934. - when it's gone, the special component will also be deleted
  15935. As soon as this method returns, the component can be safely removed and deleted
  15936. leaving the proxy to do the fade-out, so it's even ok to call this in a
  15937. component's destructor.
  15938. Passing non-zero x and y values will cause the ghostly component image to
  15939. also whizz off by this distance while fading out. If the scale factor is
  15940. not 1.0, it will also zoom from the component's current size to this new size.
  15941. One thing to be careful about is that the parent component must be able to cope
  15942. with this unknown component type being added to it.
  15943. */
  15944. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  15945. const int deltaXToMove = 0,
  15946. const int deltaYToMove = 0,
  15947. const float scaleFactorAtEnd = 1.0f);
  15948. /** Makes this component appear as a window on the desktop.
  15949. Note that before calling this, you should make sure that the component's opacity is
  15950. set correctly using setOpaque(). If the component is non-opaque, the windowing
  15951. system will try to create a special transparent window for it, which will generally take
  15952. a lot more CPU to operate (and might not even be possible on some platforms).
  15953. If the component is inside a parent component at the time this method is called, it
  15954. will be first be removed from that parent. Likewise if a component on the desktop
  15955. is subsequently added to another component, it'll be removed from the desktop.
  15956. @param windowStyleFlags a combination of the flags specified in the
  15957. ComponentPeer::StyleFlags enum, which define the
  15958. window's characteristics.
  15959. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  15960. in which the juce component should place itself. On Windows,
  15961. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  15962. supported on all platforms, and best left as 0 unless you know
  15963. what you're doing
  15964. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  15965. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  15966. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  15967. */
  15968. virtual void addToDesktop (int windowStyleFlags,
  15969. void* nativeWindowToAttachTo = 0);
  15970. /** If the component is currently showing on the desktop, this will hide it.
  15971. You can also use setVisible() to hide a desktop window temporarily, but
  15972. removeFromDesktop() will free any system resources that are being used up.
  15973. @see addToDesktop, isOnDesktop
  15974. */
  15975. void removeFromDesktop();
  15976. /** Returns true if this component is currently showing on the desktop.
  15977. @see addToDesktop, removeFromDesktop
  15978. */
  15979. bool isOnDesktop() const throw();
  15980. /** Returns the heavyweight window that contains this component.
  15981. If this component is itself on the desktop, this will return the window
  15982. object that it is using. Otherwise, it will return the window of
  15983. its top-level parent component.
  15984. This may return 0 if there isn't a desktop component.
  15985. @see addToDesktop, isOnDesktop
  15986. */
  15987. ComponentPeer* getPeer() const throw();
  15988. /** For components on the desktop, this is called if the system wants to close the window.
  15989. This is a signal that either the user or the system wants the window to close. The
  15990. default implementation of this method will trigger an assertion to warn you that your
  15991. component should do something about it, but you can override this to ignore the event
  15992. if you want.
  15993. */
  15994. virtual void userTriedToCloseWindow();
  15995. /** Called for a desktop component which has just been minimised or un-minimised.
  15996. This will only be called for components on the desktop.
  15997. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  15998. */
  15999. virtual void minimisationStateChanged (bool isNowMinimised);
  16000. /** Brings the component to the front of its siblings.
  16001. If some of the component's siblings have had their 'always-on-top' flag set,
  16002. then they will still be kept in front of this one (unless of course this
  16003. one is also 'always-on-top').
  16004. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  16005. to the component (see grabKeyboardFocus() for more details)
  16006. @see toBack, toBehind, setAlwaysOnTop
  16007. */
  16008. void toFront (const bool shouldAlsoGainFocus);
  16009. /** Changes this component's z-order to be at the back of all its siblings.
  16010. If the component is set to be 'always-on-top', it will only be moved to the
  16011. back of the other other 'always-on-top' components.
  16012. @see toFront, toBehind, setAlwaysOnTop
  16013. */
  16014. void toBack();
  16015. /** Changes this component's z-order so that it's just behind another component.
  16016. @see toFront, toBack
  16017. */
  16018. void toBehind (Component* const other);
  16019. /** Sets whether the component should always be kept at the front of its siblings.
  16020. @see isAlwaysOnTop
  16021. */
  16022. void setAlwaysOnTop (const bool shouldStayOnTop);
  16023. /** Returns true if this component is set to always stay in front of its siblings.
  16024. @see setAlwaysOnTop
  16025. */
  16026. bool isAlwaysOnTop() const throw();
  16027. /** Returns the x co-ordinate of the component's left edge.
  16028. This is a distance in pixels from the left edge of the component's parent.
  16029. @see getScreenX
  16030. */
  16031. inline int getX() const throw() { return bounds_.getX(); }
  16032. /** Returns the y co-ordinate of the top of this component.
  16033. This is a distance in pixels from the top edge of the component's parent.
  16034. @see getScreenY
  16035. */
  16036. inline int getY() const throw() { return bounds_.getY(); }
  16037. /** Returns the component's width in pixels. */
  16038. inline int getWidth() const throw() { return bounds_.getWidth(); }
  16039. /** Returns the component's height in pixels. */
  16040. inline int getHeight() const throw() { return bounds_.getHeight(); }
  16041. /** Returns the x co-ordinate of the component's right-hand edge.
  16042. This is a distance in pixels from the left edge of the component's parent.
  16043. */
  16044. int getRight() const throw() { return bounds_.getRight(); }
  16045. /** Returns the y co-ordinate of the bottom edge of this component.
  16046. This is a distance in pixels from the top edge of the component's parent.
  16047. */
  16048. int getBottom() const throw() { return bounds_.getBottom(); }
  16049. /** Returns this component's bounding box.
  16050. The rectangle returned is relative to the top-left of the component's parent.
  16051. */
  16052. const Rectangle& getBounds() const throw() { return bounds_; }
  16053. /** Returns the region of this component that's not obscured by other, opaque components.
  16054. The RectangleList that is returned represents the area of this component
  16055. which isn't covered by opaque child components.
  16056. If includeSiblings is true, it will also take into account any siblings
  16057. that may be overlapping the component.
  16058. */
  16059. void getVisibleArea (RectangleList& result,
  16060. const bool includeSiblings) const;
  16061. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  16062. @see getX, relativePositionToGlobal
  16063. */
  16064. int getScreenX() const throw();
  16065. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  16066. @see getY, relativePositionToGlobal
  16067. */
  16068. int getScreenY() const throw();
  16069. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  16070. @see globalPositionToRelative, relativePositionToOtherComponent
  16071. */
  16072. void relativePositionToGlobal (int& x, int& y) const throw();
  16073. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  16074. @see relativePositionToGlobal, relativePositionToOtherComponent
  16075. */
  16076. void globalPositionToRelative (int& x, int& y) const throw();
  16077. /** Converts a position relative to this component's top-left into a position
  16078. relative to another component's top-left.
  16079. @see relativePositionToGlobal, globalPositionToRelative
  16080. */
  16081. void relativePositionToOtherComponent (const Component* const targetComponent,
  16082. int& x, int& y) const throw();
  16083. /** Moves the component to a new position.
  16084. Changes the component's top-left position (without changing its size).
  16085. The position is relative to the top-left of the component's parent.
  16086. If the component actually moves, this method will make a synchronous call to moved().
  16087. @see setBounds, ComponentListener::componentMovedOrResized
  16088. */
  16089. void setTopLeftPosition (const int x, const int y);
  16090. /** Moves the component to a new position.
  16091. Changes the position of the component's top-right corner (keeping it the same size).
  16092. The position is relative to the top-left of the component's parent.
  16093. If the component actually moves, this method will make a synchronous call to moved().
  16094. */
  16095. void setTopRightPosition (const int x, const int y);
  16096. /** Changes the size of the component.
  16097. A synchronous call to resized() will be occur if the size actually changes.
  16098. */
  16099. void setSize (const int newWidth, const int newHeight);
  16100. /** Changes the component's position and size.
  16101. The co-ordinates are relative to the top-left of the component's parent, or relative
  16102. to the origin of the screen is the component is on the desktop.
  16103. If this method changes the component's top-left position, it will make a synchronous
  16104. call to moved(). If it changes the size, it will also make a call to resized().
  16105. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  16106. */
  16107. void setBounds (int x, int y, int width, int height);
  16108. /** Changes the component's position and size.
  16109. @see setBounds
  16110. */
  16111. void setBounds (const Rectangle& newBounds);
  16112. /** Changes the component's position and size in terms of fractions of its parent's size.
  16113. The values are factors of the parent's size, so for example
  16114. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  16115. width and height of the parent, with its top-left position 20% of
  16116. the way across and down the parent.
  16117. */
  16118. void setBoundsRelative (const float proportionalX, const float proportionalY,
  16119. const float proportionalWidth, const float proportionalHeight);
  16120. /** Changes the component's position and size based on the amount of space to leave around it.
  16121. This will position the component within its parent, leaving the specified number of
  16122. pixels around each edge.
  16123. */
  16124. void setBoundsInset (const BorderSize& borders);
  16125. /** Positions the component within a given rectangle, keeping its proportions
  16126. unchanged.
  16127. If onlyReduceInSize is false, the component will be resized to fill as much of the
  16128. rectangle as possible without changing its aspect ratio (the component's
  16129. current size is used to determine its aspect ratio, so a zero-size component
  16130. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  16131. too big to fit inside the rectangle.
  16132. It will then be positioned within the rectangle according to the justification flags
  16133. specified.
  16134. */
  16135. void setBoundsToFit (int x, int y, int width, int height,
  16136. const Justification& justification,
  16137. const bool onlyReduceInSize);
  16138. /** Changes the position of the component's centre.
  16139. Leaves the component's size unchanged, but sets the position of its centre
  16140. relative to its parent's top-left.
  16141. */
  16142. void setCentrePosition (const int x, const int y);
  16143. /** Changes the position of the component's centre.
  16144. Leaves the position unchanged, but positions its centre relative to its
  16145. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  16146. its parent.
  16147. */
  16148. void setCentreRelative (const float x, const float y);
  16149. /** Changes the component's size and centres it within its parent.
  16150. After changing the size, the component will be moved so that it's
  16151. centred within its parent.
  16152. */
  16153. void centreWithSize (const int width, const int height);
  16154. /** Returns a proportion of the component's width.
  16155. This is a handy equivalent of (getWidth() * proportion).
  16156. */
  16157. int proportionOfWidth (const float proportion) const throw();
  16158. /** Returns a proportion of the component's height.
  16159. This is a handy equivalent of (getHeight() * proportion).
  16160. */
  16161. int proportionOfHeight (const float proportion) const throw();
  16162. /** Returns the width of the component's parent.
  16163. If the component has no parent (i.e. if it's on the desktop), this will return
  16164. the width of the screen.
  16165. */
  16166. int getParentWidth() const throw();
  16167. /** Returns the height of the component's parent.
  16168. If the component has no parent (i.e. if it's on the desktop), this will return
  16169. the height of the screen.
  16170. */
  16171. int getParentHeight() const throw();
  16172. /** Returns the screen co-ordinates of the monitor that contains this component.
  16173. If there's only one monitor, this will return its size - if there are multiple
  16174. monitors, it will return the area of the monitor that contains the component's
  16175. centre.
  16176. */
  16177. const Rectangle getParentMonitorArea() const throw();
  16178. /** Returns the number of child components that this component contains.
  16179. @see getChildComponent, getIndexOfChildComponent
  16180. */
  16181. int getNumChildComponents() const throw();
  16182. /** Returns one of this component's child components, by it index.
  16183. The component with index 0 is at the back of the z-order, the one at the
  16184. front will have index (getNumChildComponents() - 1).
  16185. If the index is out-of-range, this will return a null pointer.
  16186. @see getNumChildComponents, getIndexOfChildComponent
  16187. */
  16188. Component* getChildComponent (const int index) const throw();
  16189. /** Returns the index of this component in the list of child components.
  16190. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  16191. values are further towards the front.
  16192. Returns -1 if the component passed-in is not a child of this component.
  16193. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  16194. */
  16195. int getIndexOfChildComponent (const Component* const child) const throw();
  16196. /** Adds a child component to this one.
  16197. @param child the new component to add. If the component passed-in is already
  16198. the child of another component, it'll first be removed from that.
  16199. @param zOrder The index in the child-list at which this component should be inserted.
  16200. A value of -1 will insert it in front of the others, 0 is the back.
  16201. @see removeChildComponent, addAndMakeVisible, getChild,
  16202. ComponentListener::componentChildrenChanged
  16203. */
  16204. void addChildComponent (Component* const child,
  16205. int zOrder = -1);
  16206. /** Adds a child component to this one, and also makes the child visible if it isn't.
  16207. Quite a useful function, this is just the same as calling addChildComponent()
  16208. followed by setVisible (true) on the child.
  16209. */
  16210. void addAndMakeVisible (Component* const child,
  16211. int zOrder = -1);
  16212. /** Removes one of this component's child-components.
  16213. If the child passed-in isn't actually a child of this component (either because
  16214. it's invalid or is the child of a different parent), then nothing is done.
  16215. Note that removing a child will not delete it!
  16216. @see addChildComponent, ComponentListener::componentChildrenChanged
  16217. */
  16218. void removeChildComponent (Component* const childToRemove);
  16219. /** Removes one of this component's child-components by index.
  16220. This will return a pointer to the component that was removed, or null if
  16221. the index was out-of-range.
  16222. Note that removing a child will not delete it!
  16223. @see addChildComponent, ComponentListener::componentChildrenChanged
  16224. */
  16225. Component* removeChildComponent (const int childIndexToRemove);
  16226. /** Removes all this component's children.
  16227. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  16228. */
  16229. void removeAllChildren();
  16230. /** Removes all this component's children, and deletes them.
  16231. @see removeAllChildren
  16232. */
  16233. void deleteAllChildren();
  16234. /** Returns the component which this component is inside.
  16235. If this is the highest-level component or hasn't yet been added to
  16236. a parent, this will return null.
  16237. */
  16238. Component* getParentComponent() const throw() { return parentComponent_; }
  16239. /** Searches the parent components for a component of a specified class.
  16240. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  16241. component that can be dynamically cast to a MyComp, or will return 0 if none
  16242. of the parents are suitable.
  16243. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  16244. */
  16245. template <class TargetClass>
  16246. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  16247. {
  16248. (void) dummyParameter;
  16249. Component* p = parentComponent_;
  16250. while (p != 0)
  16251. {
  16252. TargetClass* target = dynamic_cast <TargetClass*> (p);
  16253. if (target != 0)
  16254. return target;
  16255. p = p->parentComponent_;
  16256. }
  16257. return 0;
  16258. }
  16259. /** Returns the highest-level component which contains this one or its parents.
  16260. This will search upwards in the parent-hierarchy from this component, until it
  16261. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  16262. not yet added to a parent), and will return that.
  16263. */
  16264. Component* getTopLevelComponent() const throw();
  16265. /** Checks whether a component is anywhere inside this component or its children.
  16266. This will recursively check through this components children to see if the
  16267. given component is anywhere inside.
  16268. */
  16269. bool isParentOf (const Component* possibleChild) const throw();
  16270. /** Called to indicate that the component's parents have changed.
  16271. When a component is added or removed from its parent, this method will
  16272. be called on all of its children (recursively - so all children of its
  16273. children will also be called as well).
  16274. Subclasses can override this if they need to react to this in some way.
  16275. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  16276. */
  16277. virtual void parentHierarchyChanged();
  16278. /** Subclasses can use this callback to be told when children are added or removed.
  16279. @see parentHierarchyChanged
  16280. */
  16281. virtual void childrenChanged();
  16282. /** Tests whether a given point inside the component.
  16283. Overriding this method allows you to create components which only intercept
  16284. mouse-clicks within a user-defined area.
  16285. This is called to find out whether a particular x, y co-ordinate is
  16286. considered to be inside the component or not, and is used by methods such
  16287. as contains() and getComponentAt() to work out which component
  16288. the mouse is clicked on.
  16289. Components with custom shapes will probably want to override it to perform
  16290. some more complex hit-testing.
  16291. The default implementation of this method returns either true or false,
  16292. depending on the value that was set by calling setInterceptsMouseClicks() (true
  16293. is the default return value).
  16294. Note that the hit-test region is not related to the opacity with which
  16295. areas of a component are painted.
  16296. Applications should never call hitTest() directly - instead use the
  16297. contains() method, because this will also test for occlusion by the
  16298. component's parent.
  16299. Note that for components on the desktop, this method will be ignored, because it's
  16300. not always possible to implement this behaviour on all platforms.
  16301. @param x the x co-ordinate to test, relative to the left hand edge of this
  16302. component. This value is guaranteed to be greater than or equal to
  16303. zero, and less than the component's width
  16304. @param y the y co-ordinate to test, relative to the top edge of this
  16305. component. This value is guaranteed to be greater than or equal to
  16306. zero, and less than the component's height
  16307. @returns true if the click is considered to be inside the component
  16308. @see setInterceptsMouseClicks, contains
  16309. */
  16310. virtual bool hitTest (int x, int y);
  16311. /** Changes the default return value for the hitTest() method.
  16312. Setting this to false is an easy way to make a component pass its mouse-clicks
  16313. through to the components behind it.
  16314. When a component is created, the default setting for this is true.
  16315. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  16316. return false (or true for child components if allowClicksOnChildComponents
  16317. is true)
  16318. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  16319. components can be clicked on as normal but clicks on this component pass
  16320. straight through; if this is false and allowClicksOnThisComponent
  16321. is false, then neither this component nor any child components can
  16322. be clicked on
  16323. @see hitTest, getInterceptsMouseClicks
  16324. */
  16325. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  16326. const bool allowClicksOnChildComponents) throw();
  16327. /** Retrieves the current state of the mouse-click interception flags.
  16328. On return, the two parameters are set to the state used in the last call to
  16329. setInterceptsMouseClicks().
  16330. @see setInterceptsMouseClicks
  16331. */
  16332. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  16333. bool& allowsClicksOnChildComponents) const throw();
  16334. /** Returns true if a given point lies within this component or one of its children.
  16335. Never override this method! Use hitTest to create custom hit regions.
  16336. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16337. @param y the y co-ordinate to test, relative to this component's top edge.
  16338. @returns true if the point is within the component's hit-test area, but only if
  16339. that part of the component isn't clipped by its parent component. Note
  16340. that this won't take into account any overlapping sibling components
  16341. which might be in the way - for that, see reallyContains()
  16342. @see hitTest, reallyContains, getComponentAt
  16343. */
  16344. virtual bool contains (int x, int y);
  16345. /** Returns true if a given point lies in this component, taking any overlapping
  16346. siblings into account.
  16347. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16348. @param y the y co-ordinate to test, relative to this component's top edge.
  16349. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  16350. component, this determines the value that will
  16351. be returned.
  16352. @see contains, getComponentAt
  16353. */
  16354. bool reallyContains (int x, int y,
  16355. const bool returnTrueIfWithinAChild);
  16356. /** Returns the component at a certain point within this one.
  16357. @param x the x co-ordinate to test, relative to this component's left hand edge.
  16358. @param y the y co-ordinate to test, relative to this component's top edge.
  16359. @returns the component that is at this position - which may be 0, this component,
  16360. or one of its children. Note that overlapping siblings that might actually
  16361. be in the way are not taken into account by this method - to account for these,
  16362. instead call getComponentAt on the top-level parent of this component.
  16363. @see hitTest, contains, reallyContains
  16364. */
  16365. Component* getComponentAt (const int x, const int y);
  16366. /** Marks the whole component as needing to be redrawn.
  16367. Calling this will not do any repainting immediately, but will mark the component
  16368. as 'dirty'. At some point in the near future the operating system will send a paint
  16369. message, which will redraw all the dirty regions of all components.
  16370. There's no guarantee about how soon after calling repaint() the redraw will actually
  16371. happen, and other queued events may be delivered before a redraw is done.
  16372. If the setBufferedToImage() method has been used to cause this component
  16373. to use a buffer, the repaint() call will invalidate the component's buffer.
  16374. To redraw just a subsection of the component rather than the whole thing,
  16375. use the repaint (int, int, int, int) method.
  16376. @see paint
  16377. */
  16378. void repaint() throw();
  16379. /** Marks a subsection of this component as needing to be redrawn.
  16380. Calling this will not do any repainting immediately, but will mark the given region
  16381. of the component as 'dirty'. At some point in the near future the operating system
  16382. will send a paint message, which will redraw all the dirty regions of all components.
  16383. There's no guarantee about how soon after calling repaint() the redraw will actually
  16384. happen, and other queued events may be delivered before a redraw is done.
  16385. The region that is passed in will be clipped to keep it within the bounds of this
  16386. component.
  16387. @see repaint()
  16388. */
  16389. void repaint (const int x, const int y,
  16390. const int width, const int height) throw();
  16391. /** Makes the component use an internal buffer to optimise its redrawing.
  16392. Setting this flag to true will cause the component to allocate an
  16393. internal buffer into which it paints itself, so that when asked to
  16394. redraw itself, it can use this buffer rather than actually calling the
  16395. paint() method.
  16396. The buffer is kept until the repaint() method is called directly on
  16397. this component (or until it is resized), when the image is invalidated
  16398. and then redrawn the next time the component is painted.
  16399. Note that only the drawing that happens within the component's paint()
  16400. method is drawn into the buffer, it's child components are not buffered, and
  16401. nor is the paintOverChildren() method.
  16402. @see repaint, paint, createComponentSnapshot
  16403. */
  16404. void setBufferedToImage (const bool shouldBeBuffered) throw();
  16405. /** Generates a snapshot of part of this component.
  16406. This will return a new Image, the size of the rectangle specified,
  16407. containing a snapshot of the specified area of the component and all
  16408. its children.
  16409. The image may or may not have an alpha-channel, depending on whether the
  16410. image is opaque or not.
  16411. If the clipImageToComponentBounds parameter is true and the area is greater than
  16412. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  16413. then parts of the component beyond its bounds can be drawn.
  16414. The caller is responsible for deleting the image that is returned.
  16415. @see paintEntireComponent
  16416. */
  16417. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  16418. const bool clipImageToComponentBounds = true);
  16419. /** Draws this component and all its subcomponents onto the specified graphics
  16420. context.
  16421. You should very rarely have to use this method, it's simply there in case you need
  16422. to draw a component with a custom graphics context for some reason, e.g. for
  16423. creating a snapshot of the component.
  16424. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  16425. on its children in order to render the entire tree.
  16426. The graphics context may be left in an undefined state after this method returns,
  16427. so you may need to reset it if you're going to use it again.
  16428. */
  16429. void paintEntireComponent (Graphics& context);
  16430. /** Adds an effect filter to alter the component's appearance.
  16431. When a component has an effect filter set, then this is applied to the
  16432. results of its paint() method. There are a few preset effects, such as
  16433. a drop-shadow or glow, but they can be user-defined as well.
  16434. The effect that is passed in will not be deleted by the component - the
  16435. caller must take care of deleting it.
  16436. To remove an effect from a component, pass a null pointer in as the parameter.
  16437. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  16438. */
  16439. void setComponentEffect (ImageEffectFilter* const newEffect);
  16440. /** Returns the current component effect.
  16441. @see setComponentEffect
  16442. */
  16443. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  16444. /** Finds the appropriate look-and-feel to use for this component.
  16445. If the component hasn't had a look-and-feel explicitly set, this will
  16446. return the parent's look-and-feel, or just the default one if there's no
  16447. parent.
  16448. @see setLookAndFeel, lookAndFeelChanged
  16449. */
  16450. LookAndFeel& getLookAndFeel() const throw();
  16451. /** Sets the look and feel to use for this component.
  16452. This will also change the look and feel for any child components that haven't
  16453. had their look set explicitly.
  16454. The object passed in will not be deleted by the component, so it's the caller's
  16455. responsibility to manage it. It may be used at any time until this component
  16456. has been deleted.
  16457. Calling this method will also invoke the sendLookAndFeelChange() method.
  16458. @see getLookAndFeel, lookAndFeelChanged
  16459. */
  16460. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  16461. /** Called to let the component react to a change in the look-and-feel setting.
  16462. When the look-and-feel is changed for a component, this will be called in
  16463. all its child components, recursively.
  16464. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  16465. an application uses a LookAndFeel class that might have changed internally.
  16466. @see sendLookAndFeelChange, getLookAndFeel
  16467. */
  16468. virtual void lookAndFeelChanged();
  16469. /** Calls the lookAndFeelChanged() method in this component and all its children.
  16470. This will recurse through the children and their children, calling lookAndFeelChanged()
  16471. on them all.
  16472. @see lookAndFeelChanged
  16473. */
  16474. void sendLookAndFeelChange();
  16475. /** Indicates whether any parts of the component might be transparent.
  16476. Components that always paint all of their contents with solid colour and
  16477. thus completely cover any components behind them should use this method
  16478. to tell the repaint system that they are opaque.
  16479. This information is used to optimise drawing, because it means that
  16480. objects underneath opaque windows don't need to be painted.
  16481. By default, components are considered transparent, unless this is used to
  16482. make it otherwise.
  16483. @see isOpaque, getVisibleArea
  16484. */
  16485. void setOpaque (const bool shouldBeOpaque) throw();
  16486. /** Returns true if no parts of this component are transparent.
  16487. @returns the value that was set by setOpaque, (the default being false)
  16488. @see setOpaque
  16489. */
  16490. bool isOpaque() const throw();
  16491. /** Indicates whether the component should be brought to the front when clicked.
  16492. Setting this flag to true will cause the component to be brought to the front
  16493. when the mouse is clicked somewhere inside it or its child components.
  16494. Note that a top-level desktop window might still be brought to the front by the
  16495. operating system when it's clicked, depending on how the OS works.
  16496. By default this is set to false.
  16497. @see setMouseClickGrabsKeyboardFocus
  16498. */
  16499. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  16500. /** Indicates whether the component should be brought to the front when clicked-on.
  16501. @see setBroughtToFrontOnMouseClick
  16502. */
  16503. bool isBroughtToFrontOnMouseClick() const throw();
  16504. // Keyboard focus methods
  16505. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  16506. By default components aren't actually interested in gaining the
  16507. focus, but this method can be used to turn this on.
  16508. See the grabKeyboardFocus() method for details about the way a component
  16509. is chosen to receive the focus.
  16510. @see grabKeyboardFocus, getWantsKeyboardFocus
  16511. */
  16512. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  16513. /** Returns true if the component is interested in getting keyboard focus.
  16514. This returns the flag set by setWantsKeyboardFocus(). The default
  16515. setting is false.
  16516. @see setWantsKeyboardFocus
  16517. */
  16518. bool getWantsKeyboardFocus() const throw();
  16519. /** Chooses whether a click on this component automatically grabs the focus.
  16520. By default this is set to true, but you might want a component which can
  16521. be focused, but where you don't want the user to be able to affect it directly
  16522. by clicking.
  16523. */
  16524. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  16525. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  16526. See setMouseClickGrabsKeyboardFocus() for more info.
  16527. */
  16528. bool getMouseClickGrabsKeyboardFocus() const throw();
  16529. /** Tries to give keyboard focus to this component.
  16530. When the user clicks on a component or its grabKeyboardFocus()
  16531. method is called, the following procedure is used to work out which
  16532. component should get it:
  16533. - if the component that was clicked on actually wants focus (as indicated
  16534. by calling getWantsKeyboardFocus), it gets it.
  16535. - if the component itself doesn't want focus, it will try to pass it
  16536. on to whichever of its children is the default component, as determined by
  16537. KeyboardFocusTraverser::getDefaultComponent()
  16538. - if none of its children want focus at all, it will pass it up to its
  16539. parent instead, unless it's a top-level component without a parent,
  16540. in which case it just takes the focus itself.
  16541. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  16542. getCurrentlyFocusedComponent, focusGained, focusLost,
  16543. keyPressed, keyStateChanged
  16544. */
  16545. void grabKeyboardFocus();
  16546. /** Returns true if this component currently has the keyboard focus.
  16547. @param trueIfChildIsFocused if this is true, then the method returns true if
  16548. either this component or any of its children (recursively)
  16549. have the focus. If false, the method only returns true if
  16550. this component has the focus.
  16551. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  16552. focusGained, focusLost
  16553. */
  16554. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  16555. /** Returns the component that currently has the keyboard focus.
  16556. @returns the focused component, or null if nothing is focused.
  16557. */
  16558. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  16559. /** Tries to move the keyboard focus to one of this component's siblings.
  16560. This will try to move focus to either the next or previous component. (This
  16561. is the method that is used when shifting focus by pressing the tab key).
  16562. Components for which getWantsKeyboardFocus() returns false are not looked at.
  16563. @param moveToNext if true, the focus will move forwards; if false, it will
  16564. move backwards
  16565. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  16566. */
  16567. void moveKeyboardFocusToSibling (const bool moveToNext);
  16568. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  16569. which focus should be passed from this component.
  16570. The default implementation of this method will return a default
  16571. KeyboardFocusTraverser if this component is a focus container (as determined
  16572. by the setFocusContainer() method). If the component isn't a focus
  16573. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  16574. If you overrride this to return a custom KeyboardFocusTraverser, then
  16575. this component and all its sub-components will use the new object to
  16576. make their focusing decisions.
  16577. The method should return a new object, which the caller is required to
  16578. delete when no longer needed.
  16579. */
  16580. virtual KeyboardFocusTraverser* createFocusTraverser();
  16581. /** Returns the focus order of this component, if one has been specified.
  16582. By default components don't have a focus order - in that case, this
  16583. will return 0. Lower numbers indicate that the component will be
  16584. earlier in the focus traversal order.
  16585. To change the order, call setExplicitFocusOrder().
  16586. The focus order may be used by the KeyboardFocusTraverser class as part of
  16587. its algorithm for deciding the order in which components should be traversed.
  16588. See the KeyboardFocusTraverser class for more details on this.
  16589. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  16590. */
  16591. int getExplicitFocusOrder() const throw();
  16592. /** Sets the index used in determining the order in which focusable components
  16593. should be traversed.
  16594. A value of 0 or less is taken to mean that no explicit order is wanted, and
  16595. that traversal should use other factors, like the component's position.
  16596. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  16597. */
  16598. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  16599. /** Indicates whether this component is a parent for components that can have
  16600. their focus traversed.
  16601. This flag is used by the default implementation of the createFocusTraverser()
  16602. method, which uses the flag to find the first parent component (of the currently
  16603. focused one) which wants to be a focus container.
  16604. So using this method to set the flag to 'true' causes this component to
  16605. act as the top level within which focus is passed around.
  16606. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  16607. */
  16608. void setFocusContainer (const bool isFocusContainer) throw();
  16609. /** Returns true if this component has been marked as a focus container.
  16610. See setFocusContainer() for more details.
  16611. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  16612. */
  16613. bool isFocusContainer() const throw();
  16614. /** Returns true if the component (and all its parents) are enabled.
  16615. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  16616. what difference this makes to the component depends on the type. E.g. buttons
  16617. and sliders will choose to draw themselves differently, etc.
  16618. Note that if one of this component's parents is disabled, this will always
  16619. return false, even if this component itself is enabled.
  16620. @see setEnabled, enablementChanged
  16621. */
  16622. bool isEnabled() const throw();
  16623. /** Enables or disables this component.
  16624. Disabling a component will also cause all of its child components to become
  16625. disabled.
  16626. Similarly, enabling a component which is inside a disabled parent
  16627. component won't make any difference until the parent is re-enabled.
  16628. @see isEnabled, enablementChanged
  16629. */
  16630. void setEnabled (const bool shouldBeEnabled);
  16631. /** Callback to indicate that this component has been enabled or disabled.
  16632. This can be triggered by one of the component's parent components
  16633. being enabled or disabled, as well as changes to the component itself.
  16634. The default implementation of this method does nothing; your class may
  16635. wish to repaint itself or something when this happens.
  16636. @see setEnabled, isEnabled
  16637. */
  16638. virtual void enablementChanged();
  16639. /** Changes the mouse cursor shape to use when the mouse is over this component.
  16640. Note that the cursor set by this method can be overridden by the getMouseCursor
  16641. method.
  16642. @see MouseCursor
  16643. */
  16644. void setMouseCursor (const MouseCursor& cursorType) throw();
  16645. /** Returns the mouse cursor shape to use when the mouse is over this component.
  16646. The default implementation will return the cursor that was set by setCursor()
  16647. but can be overridden for more specialised purposes, e.g. returning different
  16648. cursors depending on the mouse position.
  16649. @see MouseCursor
  16650. */
  16651. virtual const MouseCursor getMouseCursor();
  16652. /** Forces the current mouse cursor to be updated.
  16653. If you're overriding the getMouseCursor() method to control which cursor is
  16654. displayed, then this will only be checked each time the user moves the mouse. So
  16655. if you want to force the system to check that the cursor being displayed is
  16656. up-to-date (even if the mouse is just sitting there), call this method.
  16657. This isn't needed if you're only using setMouseCursor().
  16658. */
  16659. void updateMouseCursor() const throw();
  16660. /** Components can override this method to draw their content.
  16661. The paint() method gets called when a region of a component needs redrawing,
  16662. either because the component's repaint() method has been called, or because
  16663. something has happened on the screen that means a section of a window needs
  16664. to be redrawn.
  16665. Any child components will draw themselves over whatever this method draws. If
  16666. you need to paint over the top of your child components, you can also implement
  16667. the paintOverChildren() method to do this.
  16668. If you want to cause a component to redraw itself, this is done asynchronously -
  16669. calling the repaint() method marks a region of the component as "dirty", and the
  16670. paint() method will automatically be called sometime later, by the message thread,
  16671. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  16672. you never redraw something synchronously.
  16673. You should never need to call this method directly - to take a snapshot of the
  16674. component you could use createComponentSnapshot() or paintEntireComponent().
  16675. @param g the graphics context that must be used to do the drawing operations.
  16676. @see repaint, paintOverChildren, Graphics
  16677. */
  16678. virtual void paint (Graphics& g);
  16679. /** Components can override this method to draw over the top of their children.
  16680. For most drawing operations, it's better to use the normal paint() method,
  16681. but if you need to overlay something on top of the children, this can be
  16682. used.
  16683. @see paint, Graphics
  16684. */
  16685. virtual void paintOverChildren (Graphics& g);
  16686. /** Called when the mouse moves inside this component.
  16687. If the mouse button isn't pressed and the mouse moves over a component,
  16688. this will be called to let the component react to this.
  16689. A component will always get a mouseEnter callback before a mouseMove.
  16690. @param e details about the position and status of the mouse event
  16691. @see mouseEnter, mouseExit, mouseDrag, contains
  16692. */
  16693. virtual void mouseMove (const MouseEvent& e);
  16694. /** Called when the mouse first enters this component.
  16695. If the mouse button isn't pressed and the mouse moves into a component,
  16696. this will be called to let the component react to this.
  16697. When the mouse button is pressed and held down while being moved in
  16698. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  16699. mouseDrag messages are sent to the component that the mouse was originally
  16700. clicked on, until the button is released.
  16701. If you're writing a component that needs to repaint itself when the mouse
  16702. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16703. method.
  16704. @param e details about the position and status of the mouse event
  16705. @see mouseExit, mouseDrag, mouseMove, contains
  16706. */
  16707. virtual void mouseEnter (const MouseEvent& e);
  16708. /** Called when the mouse moves out of this component.
  16709. This will be called when the mouse moves off the edge of this
  16710. component.
  16711. If the mouse button was pressed, and it was then dragged off the
  16712. edge of the component and released, then this callback will happen
  16713. when the button is released, after the mouseUp callback.
  16714. If you're writing a component that needs to repaint itself when the mouse
  16715. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  16716. method.
  16717. @param e details about the position and status of the mouse event
  16718. @see mouseEnter, mouseDrag, mouseMove, contains
  16719. */
  16720. virtual void mouseExit (const MouseEvent& e);
  16721. /** Called when a mouse button is pressed while it's over this component.
  16722. The MouseEvent object passed in contains lots of methods for finding out
  16723. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16724. were held down at the time.
  16725. Once a button is held down, the mouseDrag method will be called when the
  16726. mouse moves, until the button is released.
  16727. @param e details about the position and status of the mouse event
  16728. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  16729. */
  16730. virtual void mouseDown (const MouseEvent& e);
  16731. /** Called when the mouse is moved while a button is held down.
  16732. When a mouse button is pressed inside a component, that component
  16733. receives mouseDrag callbacks each time the mouse moves, even if the
  16734. mouse strays outside the component's bounds.
  16735. If you want to be able to drag things off the edge of a component
  16736. and have the component scroll when you get to the edges, the
  16737. beginDragAutoRepeat() method might be useful.
  16738. @param e details about the position and status of the mouse event
  16739. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  16740. */
  16741. virtual void mouseDrag (const MouseEvent& e);
  16742. /** Called when a mouse button is released.
  16743. A mouseUp callback is sent to the component in which a button was pressed
  16744. even if the mouse is actually over a different component when the
  16745. button is released.
  16746. The MouseEvent object passed in contains lots of methods for finding out
  16747. which buttons were down just before they were released.
  16748. @param e details about the position and status of the mouse event
  16749. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  16750. */
  16751. virtual void mouseUp (const MouseEvent& e);
  16752. /** Called when a mouse button has been double-clicked in this component.
  16753. The MouseEvent object passed in contains lots of methods for finding out
  16754. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  16755. were held down at the time.
  16756. For altering the time limit used to detect double-clicks,
  16757. see MouseEvent::setDoubleClickTimeout.
  16758. @param e details about the position and status of the mouse event
  16759. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  16760. MouseEvent::getDoubleClickTimeout
  16761. */
  16762. virtual void mouseDoubleClick (const MouseEvent& e);
  16763. /** Called when the mouse-wheel is moved.
  16764. This callback is sent to the component that the mouse is over when the
  16765. wheel is moved.
  16766. If not overridden, the component will forward this message to its parent, so
  16767. that parent components can collect mouse-wheel messages that happen to
  16768. child components which aren't interested in them.
  16769. @param e details about the position and status of the mouse event
  16770. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  16771. value means the wheel has been pushed to the right, negative means it
  16772. was pushed to the left
  16773. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  16774. value means the wheel has been pushed upwards, negative means it
  16775. was pushed downwards
  16776. */
  16777. virtual void mouseWheelMove (const MouseEvent& e,
  16778. float wheelIncrementX,
  16779. float wheelIncrementY);
  16780. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  16781. next mouse-drag operation.
  16782. This allows you to make sure that mouseDrag() events sent continuously, even
  16783. when the mouse isn't moving. This can be useful for things like auto-scrolling
  16784. components when the mouse is near an edge.
  16785. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  16786. minimum interval between consecutive mouse drag callbacks. The callbacks
  16787. will continue until the mouse is released, and then the interval will be reset,
  16788. so you need to make sure it's called every time you begin a drag event. If it
  16789. is called when the mouse isn't actually being pressed, it will apply to the next
  16790. mouse-drag operation that happens.
  16791. Passing an interval of 0 or less will cancel the auto-repeat.
  16792. @see mouseDrag
  16793. */
  16794. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  16795. /** Causes automatic repaints when the mouse enters or exits this component.
  16796. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  16797. on the component, it will trigger a repaint.
  16798. This is handy for things like buttons that need to draw themselves differently when
  16799. the mouse moves over them, and it avoids having to override all the different mouse
  16800. callbacks and call repaint().
  16801. @see mouseEnter, mouseExit, mouseDown, mouseUp
  16802. */
  16803. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  16804. /** Registers a listener to be told when mouse events occur in this component.
  16805. If you need to get informed about mouse events in a component but can't or
  16806. don't want to override its methods, you can attach any number of listeners
  16807. to the component, and these will get told about the events in addition to
  16808. the component's own callbacks being called.
  16809. Note that a MouseListener can also be attached to more than one component.
  16810. @param newListener the listener to register
  16811. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  16812. for events that happen to any child component
  16813. within this component, including deeply-nested
  16814. child components. If false, it will only be
  16815. told about events that this component handles.
  16816. @see MouseListener, removeMouseListener
  16817. */
  16818. void addMouseListener (MouseListener* const newListener,
  16819. const bool wantsEventsForAllNestedChildComponents) throw();
  16820. /** Deregisters a mouse listener.
  16821. @see addMouseListener, MouseListener
  16822. */
  16823. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  16824. /** Adds a listener that wants to hear about keypresses that this component receives.
  16825. The listeners that are registered with a component are called by its keyPressed() or
  16826. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  16827. If you add an object as a key listener, be careful to remove it when the object
  16828. is deleted, or the component will be left with a dangling pointer.
  16829. @see keyPressed, keyStateChanged, removeKeyListener
  16830. */
  16831. void addKeyListener (KeyListener* const newListener) throw();
  16832. /** Removes a previously-registered key listener.
  16833. @see addKeyListener
  16834. */
  16835. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  16836. /** Called when a key is pressed.
  16837. When a key is pressed, the component that has the keyboard focus will have this
  16838. method called. Remember that a component will only be given the focus if its
  16839. setWantsKeyboardFocus() method has been used to enable this.
  16840. If your implementation returns true, the event will be consumed and not passed
  16841. on to any other listeners. If it returns false, the key will be passed to any
  16842. KeyListeners that have been registered with this component. As soon as one of these
  16843. returns true, the process will stop, but if they all return false, the event will
  16844. be passed upwards to this component's parent, and so on.
  16845. The default implementation of this method does nothing and returns false.
  16846. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  16847. */
  16848. virtual bool keyPressed (const KeyPress& key);
  16849. /** Called when a key is pressed or released.
  16850. Whenever a key on the keyboard is pressed or released (including modifier keys
  16851. like shift and ctrl), this method will be called on the component that currently
  16852. has the keyboard focus. Remember that a component will only be given the focus if
  16853. its setWantsKeyboardFocus() method has been used to enable this.
  16854. If your implementation returns true, the event will be consumed and not passed
  16855. on to any other listeners. If it returns false, then any KeyListeners that have
  16856. been registered with this component will have their keyStateChanged methods called.
  16857. As soon as one of these returns true, the process will stop, but if they all return
  16858. false, the event will be passed upwards to this component's parent, and so on.
  16859. The default implementation of this method does nothing and returns false.
  16860. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  16861. method.
  16862. @param isKeyDown true if a key has been pressed; false if it has been released
  16863. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  16864. */
  16865. virtual bool keyStateChanged (const bool isKeyDown);
  16866. /** Called when a modifier key is pressed or released.
  16867. Whenever the shift, control, alt or command keys are pressed or released,
  16868. this method will be called on the component that currently has the keyboard focus.
  16869. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  16870. method has been used to enable this.
  16871. The default implementation of this method actually calls its parent's modifierKeysChanged
  16872. method, so that focused components which aren't interested in this will give their
  16873. parents a chance to act on the event instead.
  16874. @see keyStateChanged, ModifierKeys
  16875. */
  16876. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  16877. /** Enumeration used by the focusChanged() and focusLost() methods. */
  16878. enum FocusChangeType
  16879. {
  16880. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  16881. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  16882. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  16883. };
  16884. /** Called to indicate that this component has just acquired the keyboard focus.
  16885. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16886. */
  16887. virtual void focusGained (FocusChangeType cause);
  16888. /** Called to indicate that this component has just lost the keyboard focus.
  16889. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16890. */
  16891. virtual void focusLost (FocusChangeType cause);
  16892. /** Called to indicate that one of this component's children has been focused or unfocused.
  16893. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  16894. changed. It happens when focus moves from one of this component's children (at any depth)
  16895. to a component that isn't contained in this one, (or vice-versa).
  16896. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  16897. */
  16898. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  16899. /** Returns true if the mouse is currently over this component.
  16900. If the mouse isn't over the component, this will return false, even if the
  16901. mouse is currently being dragged - so you can use this in your mouseDrag
  16902. method to find out whether it's really over the component or not.
  16903. Note that when the mouse button is being held down, then the only component
  16904. for which this method will return true is the one that was originally
  16905. clicked on.
  16906. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  16907. */
  16908. bool isMouseOver() const throw();
  16909. /** Returns true if the mouse button is currently held down in this component.
  16910. Note that this is a test to see whether the mouse is being pressed in this
  16911. component, so it'll return false if called on component A when the mouse
  16912. is actually being dragged in component B.
  16913. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  16914. */
  16915. bool isMouseButtonDown() const throw();
  16916. /** True if the mouse is over this component, or if it's being dragged in this component.
  16917. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  16918. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  16919. */
  16920. bool isMouseOverOrDragging() const throw();
  16921. /** Returns true if a mouse button is currently down.
  16922. Unlike isMouseButtonDown, this will test the current state of the
  16923. buttons without regard to which component (if any) it has been
  16924. pressed in.
  16925. @see isMouseButtonDown, ModifierKeys
  16926. */
  16927. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  16928. /** Returns the mouse's current position, relative to this component.
  16929. The co-ordinates are relative to the component's top-left corner.
  16930. */
  16931. void getMouseXYRelative (int& x, int& y) const throw();
  16932. /** Returns the component that's currently underneath the mouse.
  16933. @returns the component or 0 if there isn't one.
  16934. @see contains, getComponentAt
  16935. */
  16936. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  16937. /** Allows the mouse to move beyond the edges of the screen.
  16938. Calling this method when the mouse button is currently pressed inside this component
  16939. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  16940. the edges of the screen.
  16941. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  16942. can be used for things like custom slider controls or dragging objects around, where
  16943. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  16944. The unbounded mode is automatically turned off when the mouse button is released, or
  16945. it can be turned off explicitly by calling this method again.
  16946. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  16947. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  16948. hidden; if true, it will only be hidden when it
  16949. is moved beyond the edge of the screen
  16950. */
  16951. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  16952. bool keepCursorVisibleUntilOffscreen = false) throw();
  16953. /** Called when this component's size has been changed.
  16954. A component can implement this method to do things such as laying out its
  16955. child components when its width or height changes.
  16956. The method is called synchronously as a result of the setBounds or setSize
  16957. methods, so repeatedly changing a components size will repeatedly call its
  16958. resized method (unlike things like repainting, where multiple calls to repaint
  16959. are coalesced together).
  16960. If the component is a top-level window on the desktop, its size could also
  16961. be changed by operating-system factors beyond the application's control.
  16962. @see moved, setSize
  16963. */
  16964. virtual void resized();
  16965. /** Called when this component's position has been changed.
  16966. This is called when the position relative to its parent changes, not when
  16967. its absolute position on the screen changes (so it won't be called for
  16968. all child components when a parent component is moved).
  16969. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  16970. or any of the other repositioning methods, and like resized(), it will be
  16971. called each time those methods are called.
  16972. If the component is a top-level window on the desktop, its position could also
  16973. be changed by operating-system factors beyond the application's control.
  16974. @see resized, setBounds
  16975. */
  16976. virtual void moved();
  16977. /** Called when one of this component's children is moved or resized.
  16978. If the parent wants to know about changes to its immediate children (not
  16979. to children of its children), this is the method to override.
  16980. @see moved, resized, parentSizeChanged
  16981. */
  16982. virtual void childBoundsChanged (Component* child);
  16983. /** Called when this component's immediate parent has been resized.
  16984. If the component is a top-level window, this indicates that the screen size
  16985. has changed.
  16986. @see childBoundsChanged, moved, resized
  16987. */
  16988. virtual void parentSizeChanged();
  16989. /** Called when this component has been moved to the front of its siblings.
  16990. The component may have been brought to the front by the toFront() method, or
  16991. by the operating system if it's a top-level window.
  16992. @see toFront
  16993. */
  16994. virtual void broughtToFront();
  16995. /** Adds a listener to be told about changes to the component hierarchy or position.
  16996. Component listeners get called when this component's size, position or children
  16997. change - see the ComponentListener class for more details.
  16998. @param newListener the listener to register - if this is already registered, it
  16999. will be ignored.
  17000. @see ComponentListener, removeComponentListener
  17001. */
  17002. void addComponentListener (ComponentListener* const newListener) throw();
  17003. /** Removes a component listener.
  17004. @see addComponentListener
  17005. */
  17006. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  17007. /** Dispatches a numbered message to this component.
  17008. This is a quick and cheap way of allowing simple asynchronous messages to
  17009. be sent to components. It's also safe, because if the component that you
  17010. send the message to is a null or dangling pointer, this won't cause an error.
  17011. The command ID is later delivered to the component's handleCommandMessage() method by
  17012. the application's message queue.
  17013. @see handleCommandMessage
  17014. */
  17015. void postCommandMessage (const int commandId) throw();
  17016. /** Called to handle a command that was sent by postCommandMessage().
  17017. This is called by the message thread when a command message arrives, and
  17018. the component can override this method to process it in any way it needs to.
  17019. @see postCommandMessage
  17020. */
  17021. virtual void handleCommandMessage (int commandId);
  17022. /** Runs a component modally, waiting until the loop terminates.
  17023. This method first makes the component visible, brings it to the front and
  17024. gives it the keyboard focus.
  17025. It then runs a loop, dispatching messages from the system message queue, but
  17026. blocking all mouse or keyboard messages from reaching any components other
  17027. than this one and its children.
  17028. This loop continues until the component's exitModalState() method is called (or
  17029. the component is deleted), and then this method returns, returning the value
  17030. passed into exitModalState().
  17031. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  17032. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  17033. */
  17034. int runModalLoop();
  17035. /** Puts the component into a modal state.
  17036. This makes the component modal, so that messages are blocked from reaching
  17037. any components other than this one and its children, but unlike runModalLoop(),
  17038. this method returns immediately.
  17039. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  17040. get the focus, which is usually what you'll want it to do. If not, it will leave
  17041. the focus unchanged.
  17042. @see exitModalState, runModalLoop
  17043. */
  17044. void enterModalState (const bool takeKeyboardFocus = true);
  17045. /** Ends a component's modal state.
  17046. If this component is currently modal, this will turn of its modalness, and return
  17047. a value to the runModalLoop() method that might have be running its modal loop.
  17048. @see runModalLoop, enterModalState, isCurrentlyModal
  17049. */
  17050. void exitModalState (const int returnValue);
  17051. /** Returns true if this component is the modal one.
  17052. It's possible to have nested modal components, e.g. a pop-up dialog box
  17053. that launches another pop-up, but this will only return true for
  17054. the one at the top of the stack.
  17055. @see getCurrentlyModalComponent
  17056. */
  17057. bool isCurrentlyModal() const throw();
  17058. /** Returns the number of components that are currently in a modal state.
  17059. @see getCurrentlyModalComponent
  17060. */
  17061. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  17062. /** Returns one of the components that are currently modal.
  17063. The index specifies which of the possible modal components to return. The order
  17064. of the components in this list is the reverse of the order in which they became
  17065. modal - so the component at index 0 is always the active component, and the others
  17066. are progressively earlier ones that are themselves now blocked by later ones.
  17067. @returns the modal component, or null if no components are modal (or if the
  17068. index is out of range)
  17069. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  17070. */
  17071. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  17072. /** Checks whether there's a modal component somewhere that's stopping this one
  17073. from receiving messages.
  17074. If there is a modal component, its canModalEventBeSentToComponent() method
  17075. will be called to see if it will still allow this component to receive events.
  17076. @see runModalLoop, getCurrentlyModalComponent
  17077. */
  17078. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  17079. /** When a component is modal, this callback allows it to choose which other
  17080. components can still receive events.
  17081. When a modal component is active and the user clicks on a non-modal component,
  17082. this method is called on the modal component, and if it returns true, the
  17083. event is allowed to reach its target. If it returns false, the event is blocked
  17084. and the inputAttemptWhenModal() callback is made.
  17085. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  17086. implementation just returns false in all cases.
  17087. */
  17088. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  17089. /** Called when the user tries to click on a component that is blocked by another
  17090. modal component.
  17091. When a component is modal and the user clicks on one of the other components,
  17092. the modal component will receive this callback.
  17093. The default implementation of this method will play a beep, and bring the currently
  17094. modal component to the front, but it can be overridden to do other tasks.
  17095. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  17096. */
  17097. virtual void inputAttemptWhenModal();
  17098. /** Returns one of the component's properties as a string.
  17099. @param keyName the name of the property to retrieve
  17100. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17101. properties, then it will check whether the parent component has
  17102. the key.
  17103. @param defaultReturnValue a value to return if the named property doesn't actually exist
  17104. */
  17105. const String getComponentProperty (const String& keyName,
  17106. const bool useParentComponentIfNotFound,
  17107. const String& defaultReturnValue = String::empty) const throw();
  17108. /** Returns one of the properties as an integer.
  17109. @param keyName the name of the property to retrieve
  17110. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17111. properties, then it will check whether the parent component has
  17112. the key.
  17113. @param defaultReturnValue a value to return if the named property doesn't actually exist
  17114. */
  17115. int getComponentPropertyInt (const String& keyName,
  17116. const bool useParentComponentIfNotFound,
  17117. const int defaultReturnValue = 0) const throw();
  17118. /** Returns one of the properties as an double.
  17119. @param keyName the name of the property to retrieve
  17120. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17121. properties, then it will check whether the parent component has
  17122. the key.
  17123. @param defaultReturnValue a value to return if the named property doesn't actually exist
  17124. */
  17125. double getComponentPropertyDouble (const String& keyName,
  17126. const bool useParentComponentIfNotFound,
  17127. const double defaultReturnValue = 0.0) const throw();
  17128. /** Returns one of the properties as an boolean.
  17129. The result will be true if the string found for this key name can be parsed as a non-zero
  17130. integer.
  17131. @param keyName the name of the property to retrieve
  17132. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17133. properties, then it will check whether the parent component has
  17134. the key.
  17135. @param defaultReturnValue a value to return if the named property doesn't actually exist
  17136. */
  17137. bool getComponentPropertyBool (const String& keyName,
  17138. const bool useParentComponentIfNotFound,
  17139. const bool defaultReturnValue = false) const throw();
  17140. /** Returns one of the properties as an colour.
  17141. @param keyName the name of the property to retrieve
  17142. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  17143. properties, then it will check whether the parent component has
  17144. the key.
  17145. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  17146. */
  17147. const Colour getComponentPropertyColour (const String& keyName,
  17148. const bool useParentComponentIfNotFound,
  17149. const Colour& defaultReturnValue = Colours::black) const throw();
  17150. /** Sets a named property as a string.
  17151. @param keyName the name of the property to set. (This mustn't be an empty string)
  17152. @param value the new value to set it to
  17153. @see removeComponentProperty
  17154. */
  17155. void setComponentProperty (const String& keyName, const String& value) throw();
  17156. /** Sets a named property to an integer.
  17157. @param keyName the name of the property to set. (This mustn't be an empty string)
  17158. @param value the new value to set it to
  17159. @see removeComponentProperty
  17160. */
  17161. void setComponentProperty (const String& keyName, const int value) throw();
  17162. /** Sets a named property to a double.
  17163. @param keyName the name of the property to set. (This mustn't be an empty string)
  17164. @param value the new value to set it to
  17165. @see removeComponentProperty
  17166. */
  17167. void setComponentProperty (const String& keyName, const double value) throw();
  17168. /** Sets a named property to a boolean.
  17169. @param keyName the name of the property to set. (This mustn't be an empty string)
  17170. @param value the new value to set it to
  17171. @see removeComponentProperty
  17172. */
  17173. void setComponentProperty (const String& keyName, const bool value) throw();
  17174. /** Sets a named property to a colour.
  17175. @param keyName the name of the property to set. (This mustn't be an empty string)
  17176. @param newColour the new colour to set it to
  17177. @see removeComponentProperty
  17178. */
  17179. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  17180. /** Deletes a named component property.
  17181. @param keyName the name of the property to delete. (This mustn't be an empty string)
  17182. @see setComponentProperty, getComponentProperty
  17183. */
  17184. void removeComponentProperty (const String& keyName) throw();
  17185. /** Returns the complete set of properties that have been set for this component.
  17186. If no properties have been set, this will return a null pointer.
  17187. @see getComponentProperty, setComponentProperty
  17188. */
  17189. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  17190. /** Looks for a colour that has been registered with the given colour ID number.
  17191. If a colour has been set for this ID number using setColour(), then it is
  17192. returned. If none has been set, the method will try calling the component's
  17193. LookAndFeel class's findColour() method. If none has been registered with the
  17194. look-and-feel either, it will just return black.
  17195. The colour IDs for various purposes are stored as enums in the components that
  17196. they are relevent to - for an example, see Slider::ColourIds,
  17197. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  17198. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  17199. */
  17200. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  17201. /** Registers a colour to be used for a particular purpose.
  17202. Changing a colour will cause a synchronous callback to the colourChanged()
  17203. method, which your component can override if it needs to do something when
  17204. colours are altered.
  17205. For more details about colour IDs, see the comments for findColour().
  17206. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  17207. */
  17208. void setColour (const int colourId, const Colour& colour);
  17209. /** If a colour has been set with setColour(), this will remove it.
  17210. This allows you to make a colour revert to its default state.
  17211. */
  17212. void removeColour (const int colourId);
  17213. /** Returns true if the specified colour ID has been explicitly set for this
  17214. component using the setColour() method.
  17215. */
  17216. bool isColourSpecified (const int colourId) const throw();
  17217. /** This looks for any colours that have been specified for this component,
  17218. and copies them to the specified target component.
  17219. */
  17220. void copyAllExplicitColoursTo (Component& target) const throw();
  17221. /** This method is called when a colour is changed by the setColour() method.
  17222. @see setColour, findColour
  17223. */
  17224. virtual void colourChanged();
  17225. /** Returns the underlying native window handle for this component.
  17226. This is platform-dependent and strictly for power-users only!
  17227. */
  17228. void* getWindowHandle() const throw();
  17229. /** When created, each component is given a number to uniquely identify it.
  17230. The number is incremented each time a new component is created, so it's a more
  17231. unique way of identifying a component than using its memory location (which
  17232. may be reused after the component is deleted, of course).
  17233. */
  17234. uint32 getComponentUID() const throw() { return componentUID; }
  17235. juce_UseDebuggingNewOperator
  17236. private:
  17237. friend class ComponentPeer;
  17238. friend class InternalDragRepeater;
  17239. static Component* currentlyFocusedComponent;
  17240. static Component* componentUnderMouse;
  17241. String componentName_;
  17242. Component* parentComponent_;
  17243. uint32 componentUID;
  17244. Rectangle bounds_;
  17245. unsigned short numDeepMouseListeners;
  17246. Array <Component*> childComponentList_;
  17247. LookAndFeel* lookAndFeel_;
  17248. MouseCursor cursor_;
  17249. ImageEffectFilter* effect_;
  17250. Image* bufferedImage_;
  17251. VoidArray* mouseListeners_;
  17252. VoidArray* keyListeners_;
  17253. VoidArray* componentListeners_;
  17254. PropertySet* propertySet_;
  17255. struct ComponentFlags
  17256. {
  17257. bool hasHeavyweightPeerFlag : 1;
  17258. bool visibleFlag : 1;
  17259. bool opaqueFlag : 1;
  17260. bool ignoresMouseClicksFlag : 1;
  17261. bool allowChildMouseClicksFlag : 1;
  17262. bool wantsFocusFlag : 1;
  17263. bool isFocusContainerFlag : 1;
  17264. bool dontFocusOnMouseClickFlag : 1;
  17265. bool alwaysOnTopFlag : 1;
  17266. bool bufferToImageFlag : 1;
  17267. bool bringToFrontOnClickFlag : 1;
  17268. bool repaintOnMouseActivityFlag : 1;
  17269. bool draggingFlag : 1;
  17270. bool mouseOverFlag : 1;
  17271. bool mouseInsideFlag : 1;
  17272. bool currentlyModalFlag : 1;
  17273. bool isDisabledFlag : 1;
  17274. bool childCompFocusedFlag : 1;
  17275. #ifdef JUCE_DEBUG
  17276. bool isInsidePaintCall : 1;
  17277. #endif
  17278. };
  17279. union
  17280. {
  17281. uint32 componentFlags_;
  17282. ComponentFlags flags;
  17283. };
  17284. void internalMouseEnter (int x, int y, const int64 time);
  17285. void internalMouseExit (int x, int y, const int64 time);
  17286. void internalMouseDown (int x, int y);
  17287. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  17288. void internalMouseDrag (int x, int y, const int64 time);
  17289. void internalMouseMove (int x, int y, const int64 time);
  17290. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  17291. void internalBroughtToFront();
  17292. void internalFocusGain (const FocusChangeType cause);
  17293. void internalFocusLoss (const FocusChangeType cause);
  17294. void internalChildFocusChange (FocusChangeType cause);
  17295. void internalModalInputAttempt();
  17296. void internalModifierKeysChanged();
  17297. void internalChildrenChanged();
  17298. void internalHierarchyChanged();
  17299. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  17300. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  17301. void repaintParent() throw();
  17302. void sendFakeMouseMove() const;
  17303. void takeKeyboardFocus (const FocusChangeType cause);
  17304. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  17305. static void giveAwayFocus();
  17306. void sendEnablementChangeMessage();
  17307. static void* runModalLoopCallback (void*);
  17308. static void bringModalComponentToFront();
  17309. void subtractObscuredRegions (RectangleList& result,
  17310. const int deltaX, const int deltaY,
  17311. const Rectangle& clipRect,
  17312. const Component* const compToAvoid) const throw();
  17313. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  17314. const int deltaX, const int deltaY) const throw();
  17315. // how much of the component is not off the edges of its parents
  17316. const Rectangle getUnclippedArea() const;
  17317. void sendVisibilityChangeMessage();
  17318. // This is included here just to cause a compile error if your code is still handling
  17319. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  17320. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  17321. // implement its methods instead of this Component method).
  17322. virtual void filesDropped (const StringArray&, int, int) {}
  17323. // components aren't allowed to have copy constructors, as this would mess up parent
  17324. // hierarchies. You might need to give your subclasses a private dummy constructor like
  17325. // this one to avoid compiler warnings.
  17326. Component (const Component&);
  17327. const Component& operator= (const Component&);
  17328. // (dummy method to cause a deliberate compile error - if you hit this, you need to update your
  17329. // subclass to use the new parameters to keyStateChanged)
  17330. virtual void keyStateChanged() {};
  17331. protected:
  17332. /** @internal */
  17333. virtual void internalRepaint (int x, int y, int w, int h);
  17334. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  17335. /** Overridden from the MessageListener parent class.
  17336. You can override this if you really need to, but be sure to pass your unwanted messages up
  17337. to this base class implementation, as the Component class needs to send itself messages
  17338. to work properly.
  17339. */
  17340. void handleMessage (const Message&);
  17341. };
  17342. #endif // __JUCE_COMPONENT_JUCEHEADER__
  17343. /********* End of inlined file: juce_Component.h *********/
  17344. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  17345. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17346. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17347. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  17348. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17349. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17350. /** A type used to hold the unique ID for an application command.
  17351. This is a numeric type, so it can be stored as an integer.
  17352. @see ApplicationCommandInfo, ApplicationCommandManager,
  17353. ApplicationCommandTarget, KeyPressMappingSet
  17354. */
  17355. typedef int CommandID;
  17356. /** A set of general-purpose application command IDs.
  17357. Because these commands are likely to be used in most apps, they're defined
  17358. here to help different apps to use the same numeric values for them.
  17359. Of course you don't have to use these, but some of them are used internally by
  17360. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  17361. @see ApplicationCommandInfo, ApplicationCommandManager,
  17362. ApplicationCommandTarget, KeyPressMappingSet
  17363. */
  17364. namespace StandardApplicationCommandIDs
  17365. {
  17366. /** This command ID should be used to send a "Quit the App" command.
  17367. This command is recognised by the JUCEApplication class, so if it is invoked
  17368. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  17369. object will catch it and call JUCEApplication::systemRequestedQuit().
  17370. */
  17371. static const CommandID quit = 0x1001;
  17372. /** The command ID that should be used to send a "Delete" command. */
  17373. static const CommandID del = 0x1002;
  17374. /** The command ID that should be used to send a "Cut" command. */
  17375. static const CommandID cut = 0x1003;
  17376. /** The command ID that should be used to send a "Copy to clipboard" command. */
  17377. static const CommandID copy = 0x1004;
  17378. /** The command ID that should be used to send a "Paste from clipboard" command. */
  17379. static const CommandID paste = 0x1005;
  17380. /** The command ID that should be used to send a "Select all" command. */
  17381. static const CommandID selectAll = 0x1006;
  17382. /** The command ID that should be used to send a "Deselect all" command. */
  17383. static const CommandID deselectAll = 0x1007;
  17384. }
  17385. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17386. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  17387. /**
  17388. Holds information describing an application command.
  17389. This object is used to pass information about a particular command, such as its
  17390. name, description and other usage flags.
  17391. When an ApplicationCommandTarget is asked to provide information about the commands
  17392. it can perform, this is the structure gets filled-in to describe each one.
  17393. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  17394. ApplicationCommandManager
  17395. */
  17396. struct JUCE_API ApplicationCommandInfo
  17397. {
  17398. ApplicationCommandInfo (const CommandID commandID) throw();
  17399. /** Sets a number of the structures values at once.
  17400. The meanings of each of the parameters is described below, in the appropriate
  17401. member variable's description.
  17402. */
  17403. void setInfo (const String& shortName,
  17404. const String& description,
  17405. const String& categoryName,
  17406. const int flags) throw();
  17407. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  17408. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  17409. is false, the bit is set.
  17410. */
  17411. void setActive (const bool isActive) throw();
  17412. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  17413. */
  17414. void setTicked (const bool isTicked) throw();
  17415. /** Handy method for adding a keypress to the defaultKeypresses array.
  17416. This is just so you can write things like:
  17417. @code
  17418. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  17419. @endcode
  17420. instead of
  17421. @code
  17422. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  17423. @endcode
  17424. */
  17425. void addDefaultKeypress (const int keyCode,
  17426. const ModifierKeys& modifiers) throw();
  17427. /** The command's unique ID number.
  17428. */
  17429. CommandID commandID;
  17430. /** A short name to describe the command.
  17431. This should be suitable for use in menus, on buttons that trigger the command, etc.
  17432. You can use the setInfo() method to quickly set this and some of the command's
  17433. other properties.
  17434. */
  17435. String shortName;
  17436. /** A longer description of the command.
  17437. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  17438. pop-up tooltip describing what the command does.
  17439. You can use the setInfo() method to quickly set this and some of the command's
  17440. other properties.
  17441. */
  17442. String description;
  17443. /** A named category that the command fits into.
  17444. You can give your commands any category you like, and these will be displayed in
  17445. contexts such as the KeyMappingEditorComponent, where the category is used to group
  17446. commands together.
  17447. You can use the setInfo() method to quickly set this and some of the command's
  17448. other properties.
  17449. */
  17450. String categoryName;
  17451. /** A list of zero or more keypresses that should be used as the default keys for
  17452. this command.
  17453. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  17454. this list to initialise the default set of key-to-command mappings.
  17455. @see addDefaultKeypress
  17456. */
  17457. Array <KeyPress> defaultKeypresses;
  17458. /** Flags describing the ways in which this command should be used.
  17459. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  17460. variable.
  17461. */
  17462. enum CommandFlags
  17463. {
  17464. /** Indicates that the command can't currently be performed.
  17465. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  17466. not currently permissable to perform the command. If the flag is set, then
  17467. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  17468. command or show themselves as not being enabled.
  17469. @see ApplicationCommandInfo::setActive
  17470. */
  17471. isDisabled = 1 << 0,
  17472. /** Indicates that the command should have a tick next to it on a menu.
  17473. If your command is shown on a menu and this is set, it'll show a tick next to
  17474. it. Other components such as buttons may also use this flag to indicate that it
  17475. is a value that can be toggled, and is currently in the 'on' state.
  17476. @see ApplicationCommandInfo::setTicked
  17477. */
  17478. isTicked = 1 << 1,
  17479. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  17480. it will call the command twice, once on key-down and again on key-up.
  17481. @see ApplicationCommandTarget::InvocationInfo
  17482. */
  17483. wantsKeyUpDownCallbacks = 1 << 2,
  17484. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  17485. command in its list.
  17486. */
  17487. hiddenFromKeyEditor = 1 << 3,
  17488. /** If this flag is present, then a KeyMappingEditorComponent will display the
  17489. command in its list, but won't allow the assigned keypress to be changed.
  17490. */
  17491. readOnlyInKeyEditor = 1 << 4,
  17492. /** If this flag is present and the command is invoked from a keypress, then any
  17493. buttons or menus that are also connected to the command will not flash to
  17494. indicate that they've been triggered.
  17495. */
  17496. dontTriggerVisualFeedback = 1 << 5
  17497. };
  17498. /** A bitwise-OR of the values specified in the CommandFlags enum.
  17499. You can use the setInfo() method to quickly set this and some of the command's
  17500. other properties.
  17501. */
  17502. int flags;
  17503. };
  17504. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17505. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  17506. /**
  17507. A command target publishes a list of command IDs that it can perform.
  17508. An ApplicationCommandManager despatches commands to targets, which must be
  17509. able to provide information about what commands they can handle.
  17510. To create a target, you'll need to inherit from this class, implementing all of
  17511. its pure virtual methods.
  17512. For info about how a target is chosen to receive a command, see
  17513. ApplicationCommandManager::getFirstCommandTarget().
  17514. @see ApplicationCommandManager, ApplicationCommandInfo
  17515. */
  17516. class JUCE_API ApplicationCommandTarget
  17517. {
  17518. public:
  17519. /** Creates a command target. */
  17520. ApplicationCommandTarget();
  17521. /** Destructor. */
  17522. virtual ~ApplicationCommandTarget();
  17523. /**
  17524. */
  17525. struct JUCE_API InvocationInfo
  17526. {
  17527. InvocationInfo (const CommandID commandID) throw();
  17528. /** The UID of the command that should be performed. */
  17529. CommandID commandID;
  17530. /** The command's flags.
  17531. See ApplicationCommandInfo for a description of these flag values.
  17532. */
  17533. int commandFlags;
  17534. /** The types of context in which the command might be called. */
  17535. enum InvocationMethod
  17536. {
  17537. direct = 0, /**< The command is being invoked directly by a piece of code. */
  17538. fromKeyPress, /**< The command is being invoked by a key-press. */
  17539. fromMenu, /**< The command is being invoked by a menu selection. */
  17540. fromButton /**< The command is being invoked by a button click. */
  17541. };
  17542. /** The type of event that triggered this command. */
  17543. InvocationMethod invocationMethod;
  17544. /** If triggered by a keypress or menu, this will be the component that had the
  17545. keyboard focus at the time.
  17546. If triggered by a button, it may be set to that component, or it may be null.
  17547. */
  17548. Component* originatingComponent;
  17549. /** The keypress that was used to invoke it.
  17550. Note that this will be an invalid keypress if the command was invoked
  17551. by some other means than a keyboard shortcut.
  17552. */
  17553. KeyPress keyPress;
  17554. /** True if the callback is being invoked when the key is pressed,
  17555. false if the key is being released.
  17556. @see KeyPressMappingSet::addCommand()
  17557. */
  17558. bool isKeyDown;
  17559. /** If the key is being released, this indicates how long it had been held
  17560. down for.
  17561. (Only relevant if isKeyDown is false.)
  17562. */
  17563. int millisecsSinceKeyPressed;
  17564. };
  17565. /** This must return the next target to try after this one.
  17566. When a command is being sent, and the first target can't handle
  17567. that command, this method is used to determine the next target that should
  17568. be tried.
  17569. It may return 0 if it doesn't know of another target.
  17570. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  17571. method to return a parent component that might want to handle it.
  17572. @see invoke
  17573. */
  17574. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  17575. /** This must return a complete list of commands that this target can handle.
  17576. Your target should add all the command IDs that it handles to the array that is
  17577. passed-in.
  17578. */
  17579. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  17580. /** This must provide details about one of the commands that this target can perform.
  17581. This will be called with one of the command IDs that the target provided in its
  17582. getAllCommands() methods.
  17583. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  17584. suitable information about the command. (The commandID field will already have been filled-in
  17585. by the caller).
  17586. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  17587. set all the fields at once.
  17588. If the command is currently inactive for some reason, this method must use
  17589. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  17590. bit of the ApplicationCommandInfo::flags field).
  17591. Any default key-presses for the command should be appended to the
  17592. ApplicationCommandInfo::defaultKeypresses field.
  17593. Note that if you change something that affects the status of the commands
  17594. that would be returned by this method (e.g. something that makes some commands
  17595. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  17596. to cause the manager to refresh its status.
  17597. */
  17598. virtual void getCommandInfo (const CommandID commandID,
  17599. ApplicationCommandInfo& result) = 0;
  17600. /** This must actually perform the specified command.
  17601. If this target is able to perform the command specified by the commandID field of the
  17602. InvocationInfo structure, then it should do so, and must return true.
  17603. If it can't handle this command, it should return false, which tells the caller to pass
  17604. the command on to the next target in line.
  17605. @see invoke, ApplicationCommandManager::invoke
  17606. */
  17607. virtual bool perform (const InvocationInfo& info) = 0;
  17608. /** Makes this target invoke a command.
  17609. Your code can call this method to invoke a command on this target, but normally
  17610. you'd call it indirectly via ApplicationCommandManager::invoke() or
  17611. ApplicationCommandManager::invokeDirectly().
  17612. If this target can perform the given command, it will call its perform() method to
  17613. do so. If not, then getNextCommandTarget() will be used to determine the next target
  17614. to try, and the command will be passed along to it.
  17615. @param invocationInfo this must be correctly filled-in, describing the context for
  17616. the invocation.
  17617. @param asynchronously if false, the command will be performed before this method returns.
  17618. If true, a message will be posted so that the command will be performed
  17619. later on the message thread, and this method will return immediately.
  17620. @see perform, ApplicationCommandManager::invoke
  17621. */
  17622. bool invoke (const InvocationInfo& invocationInfo,
  17623. const bool asynchronously);
  17624. /** Invokes a given command directly on this target.
  17625. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  17626. structure.
  17627. */
  17628. bool invokeDirectly (const CommandID commandID,
  17629. const bool asynchronously);
  17630. /** Searches this target and all subsequent ones for the first one that can handle
  17631. the specified command.
  17632. This will use getNextCommandTarget() to determine the chain of targets to try
  17633. after this one.
  17634. */
  17635. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  17636. /** Checks whether this command can currently be performed by this target.
  17637. This will return true only if a call to getCommandInfo() doesn't set the
  17638. isDisabled flag to indicate that the command is inactive.
  17639. */
  17640. bool isCommandActive (const CommandID commandID);
  17641. /** If this object is a Component, this method will seach upwards in its current
  17642. UI hierarchy for the next parent component that implements the
  17643. ApplicationCommandTarget class.
  17644. If your target is a Component, this is a very handy method to use in your
  17645. getNextCommandTarget() implementation.
  17646. */
  17647. ApplicationCommandTarget* findFirstTargetParentComponent();
  17648. juce_UseDebuggingNewOperator
  17649. private:
  17650. // (for async invocation of commands)
  17651. class CommandTargetMessageInvoker : public MessageListener
  17652. {
  17653. public:
  17654. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  17655. ~CommandTargetMessageInvoker();
  17656. void handleMessage (const Message& message);
  17657. private:
  17658. ApplicationCommandTarget* const owner;
  17659. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  17660. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  17661. };
  17662. CommandTargetMessageInvoker* messageInvoker;
  17663. friend class CommandTargetMessageInvoker;
  17664. bool tryToInvoke (const InvocationInfo& info, const bool async);
  17665. };
  17666. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  17667. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  17668. /********* Start of inlined file: juce_ActionListener.h *********/
  17669. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  17670. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  17671. /**
  17672. Receives callbacks to indicate that some kind of event has occurred.
  17673. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  17674. about something that's happened.
  17675. @see ActionListenerList, ActionBroadcaster, ChangeListener
  17676. */
  17677. class JUCE_API ActionListener
  17678. {
  17679. public:
  17680. /** Destructor. */
  17681. virtual ~ActionListener() {}
  17682. /** Overridden by your subclass to receive the callback.
  17683. @param message the string that was specified when the event was triggered
  17684. by a call to ActionListenerList::sendActionMessage()
  17685. */
  17686. virtual void actionListenerCallback (const String& message) = 0;
  17687. };
  17688. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  17689. /********* End of inlined file: juce_ActionListener.h *********/
  17690. /**
  17691. An instance of this class is used to specify initialisation and shutdown
  17692. code for the application.
  17693. An application that wants to run in the JUCE framework needs to declare a
  17694. subclass of JUCEApplication and implement its various pure virtual methods.
  17695. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  17696. to declare an instance of this class and generate a suitable platform-specific
  17697. main() function.
  17698. e.g. @code
  17699. class MyJUCEApp : public JUCEApplication
  17700. {
  17701. // NEVER put objects inside a JUCEApplication class - only use pointers to
  17702. // objects, which you must create in the initialise() method.
  17703. MyApplicationWindow* myMainWindow;
  17704. public:
  17705. MyJUCEApp()
  17706. : myMainWindow (0)
  17707. {
  17708. // never create any Juce objects in the constructor - do all your initialisation
  17709. // in the initialise() method.
  17710. }
  17711. ~MyJUCEApp()
  17712. {
  17713. // all your shutdown code must have already been done in the shutdown() method -
  17714. // nothing should happen in this destructor.
  17715. }
  17716. void initialise (const String& commandLine)
  17717. {
  17718. myMainWindow = new MyApplicationWindow();
  17719. myMainWindow->setBounds (100, 100, 400, 500);
  17720. myMainWindow->setVisible (true);
  17721. }
  17722. void shutdown()
  17723. {
  17724. delete myMainWindow;
  17725. }
  17726. const String getApplicationName()
  17727. {
  17728. return T("Super JUCE-o-matic");
  17729. }
  17730. const String getApplicationVersion()
  17731. {
  17732. return T("1.0");
  17733. }
  17734. };
  17735. // this creates wrapper code to actually launch the app properly.
  17736. START_JUCE_APPLICATION (MyJUCEApp)
  17737. @endcode
  17738. Because this object will be created before Juce has properly initialised, you must
  17739. NEVER add any member variable objects that will be automatically constructed. Likewise
  17740. don't put ANY code in the constructor that could call Juce functions. Any objects that
  17741. you want to add to the class must be pointers, which you should instantiate during the
  17742. initialise() method, and delete in the shutdown() method.
  17743. @see MessageManager, DeletedAtShutdown
  17744. */
  17745. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  17746. private ActionListener
  17747. {
  17748. protected:
  17749. /** Constructs a JUCE app object.
  17750. If subclasses implement a constructor or destructor, they shouldn't call any
  17751. JUCE code in there - put your startup/shutdown code in initialise() and
  17752. shutdown() instead.
  17753. */
  17754. JUCEApplication();
  17755. public:
  17756. /** Destructor.
  17757. If subclasses implement a constructor or destructor, they shouldn't call any
  17758. JUCE code in there - put your startup/shutdown code in initialise() and
  17759. shutdown() instead.
  17760. */
  17761. virtual ~JUCEApplication();
  17762. /** Returns the global instance of the application object being run. */
  17763. static JUCEApplication* getInstance() throw();
  17764. /** Called when the application starts.
  17765. This will be called once to let the application do whatever initialisation
  17766. it needs, create its windows, etc.
  17767. After the method returns, the normal event-dispatch loop will be run,
  17768. until the quit() method is called, at which point the shutdown()
  17769. method will be called to let the application clear up anything it needs
  17770. to delete.
  17771. If during the initialise() method, the application decides not to start-up
  17772. after all, it can just call the quit() method and the event loop won't be run.
  17773. @param commandLineParameters the line passed in does not include the
  17774. name of the executable, just the parameter list.
  17775. @see shutdown, quit
  17776. */
  17777. virtual void initialise (const String& commandLineParameters) = 0;
  17778. /** Returns true if the application hasn't yet completed its initialise() method
  17779. and entered the main event loop.
  17780. This is handy for things like splash screens to know when the app's up-and-running
  17781. properly.
  17782. */
  17783. bool isInitialising() const throw();
  17784. /* Called to allow the application to clear up before exiting.
  17785. After JUCEApplication::quit() has been called, the event-dispatch loop will
  17786. terminate, and this method will get called to allow the app to sort itself
  17787. out.
  17788. Be careful that nothing happens in this method that might rely on messages
  17789. being sent, or any kind of window activity, because the message loop is no
  17790. longer running at this point.
  17791. @see DeletedAtShutdown
  17792. */
  17793. virtual void shutdown() = 0;
  17794. /** Returns the application's name.
  17795. An application must implement this to name itself.
  17796. */
  17797. virtual const String getApplicationName() = 0;
  17798. /** Returns the application's version number.
  17799. An application can implement this to give itself a version.
  17800. (The default implementation of this just returns an empty string).
  17801. */
  17802. virtual const String getApplicationVersion();
  17803. /** Checks whether multiple instances of the app are allowed.
  17804. If you application class returns true for this, more than one instance is
  17805. permitted to run (except on the Mac where this isn't possible).
  17806. If it's false, the second instance won't start, but it you will still get a
  17807. callback to anotherInstanceStarted() to tell you about this - which
  17808. gives you a chance to react to what the user was trying to do.
  17809. */
  17810. virtual bool moreThanOneInstanceAllowed();
  17811. /** Indicates that the user has tried to start up another instance of the app.
  17812. This will get called even if moreThanOneInstanceAllowed() is false.
  17813. */
  17814. virtual void anotherInstanceStarted (const String& commandLine);
  17815. /** Called when the operating system is trying to close the application.
  17816. The default implementation of this method is to call quit(), but it may
  17817. be overloaded to ignore the request or do some other special behaviour
  17818. instead. For example, you might want to offer the user the chance to save
  17819. their changes before quitting, and give them the chance to cancel.
  17820. If you want to send a quit signal to your app, this is the correct method
  17821. to call, because it means that requests that come from the system get handled
  17822. in the same way as those from your own application code. So e.g. you'd
  17823. call this method from a "quit" item on a menu bar.
  17824. */
  17825. virtual void systemRequestedQuit();
  17826. /** If any unhandled exceptions make it through to the message dispatch loop, this
  17827. callback will be triggered, in case you want to log them or do some other
  17828. type of error-handling.
  17829. If the type of exception is derived from the std::exception class, the pointer
  17830. passed-in will be valid. If the exception is of unknown type, this pointer
  17831. will be null.
  17832. */
  17833. virtual void unhandledException (const std::exception* e,
  17834. const String& sourceFilename,
  17835. const int lineNumber);
  17836. /** Signals that the main message loop should stop and the application should terminate.
  17837. This isn't synchronous, it just posts a quit message to the main queue, and
  17838. when this message arrives, the message loop will stop, the shutdown() method
  17839. will be called, and the app will exit.
  17840. Note that this will cause an unconditional quit to happen, so if you need an
  17841. extra level before this, e.g. to give the user the chance to save their work
  17842. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  17843. method - see that method's help for more info.
  17844. @see MessageManager, DeletedAtShutdown
  17845. */
  17846. static void quit();
  17847. /** Sets the value that should be returned as the application's exit code when the
  17848. app quits.
  17849. This is the value that's returned by the main() function. Normally you'd leave this
  17850. as 0 unless you want to indicate an error code.
  17851. @see getApplicationReturnValue
  17852. */
  17853. void setApplicationReturnValue (const int newReturnValue) throw();
  17854. /** Returns the value that has been set as the application's exit code.
  17855. @see setApplicationReturnValue
  17856. */
  17857. int getApplicationReturnValue() const throw() { return appReturnValue; }
  17858. /** Returns the application's command line params.
  17859. */
  17860. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  17861. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  17862. /** @internal */
  17863. static int main (String& commandLine, JUCEApplication* const newApp);
  17864. /** @internal */
  17865. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  17866. /** @internal */
  17867. static void sendUnhandledException (const std::exception* const e,
  17868. const char* const sourceFile,
  17869. const int lineNumber);
  17870. /** @internal */
  17871. ApplicationCommandTarget* getNextCommandTarget();
  17872. /** @internal */
  17873. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  17874. /** @internal */
  17875. void getAllCommands (Array <CommandID>& commands);
  17876. /** @internal */
  17877. bool perform (const InvocationInfo& info);
  17878. /** @internal */
  17879. void actionListenerCallback (const String& message);
  17880. private:
  17881. String commandLineParameters;
  17882. int appReturnValue;
  17883. bool stillInitialising;
  17884. static int shutdownAppAndClearUp();
  17885. };
  17886. #endif // __JUCE_APPLICATION_JUCEHEADER__
  17887. /********* End of inlined file: juce_Application.h *********/
  17888. #endif
  17889. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  17890. #endif
  17891. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  17892. #endif
  17893. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17894. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  17895. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17896. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  17897. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  17898. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  17899. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  17900. /**
  17901. Has a callback method that is triggered asynchronously.
  17902. This object allows an asynchronous callback function to be triggered, for
  17903. tasks such as coalescing multiple updates into a single callback later on.
  17904. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  17905. message thread calling handleAsyncUpdate() as soon as it can.
  17906. */
  17907. class JUCE_API AsyncUpdater
  17908. {
  17909. public:
  17910. /** Creates an AsyncUpdater object. */
  17911. AsyncUpdater() throw();
  17912. /** Destructor.
  17913. If there are any pending callbacks when the object is deleted, these are lost.
  17914. */
  17915. virtual ~AsyncUpdater();
  17916. /** Causes the callback to be triggered at a later time.
  17917. This method returns immediately, having made sure that a callback
  17918. to the handleAsyncUpdate() method will occur as soon as possible.
  17919. If an update callback is already pending but hasn't happened yet, calls
  17920. to this method will be ignored.
  17921. It's thread-safe to call this method from any number of threads without
  17922. needing to worry about locking.
  17923. */
  17924. void triggerAsyncUpdate() throw();
  17925. /** This will stop any pending updates from happening.
  17926. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  17927. callback happens, this will cancel the handleAsyncUpdate() callback.
  17928. */
  17929. void cancelPendingUpdate() throw();
  17930. /** If an update has been triggered and is pending, this will invoke it
  17931. synchronously.
  17932. Use this as a kind of "flush" operation - if an update is pending, the
  17933. handleAsyncUpdate() method will be called immediately; if no update is
  17934. pending, then nothing will be done.
  17935. */
  17936. void handleUpdateNowIfNeeded();
  17937. /** Called back to do whatever your class needs to do.
  17938. This method is called by the message thread at the next convenient time
  17939. after the triggerAsyncUpdate() method has been called.
  17940. */
  17941. virtual void handleAsyncUpdate() = 0;
  17942. private:
  17943. class AsyncUpdaterInternal : public MessageListener
  17944. {
  17945. public:
  17946. AsyncUpdaterInternal() throw() {}
  17947. ~AsyncUpdaterInternal() {}
  17948. void handleMessage (const Message&);
  17949. AsyncUpdater* owner;
  17950. private:
  17951. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  17952. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  17953. };
  17954. AsyncUpdaterInternal internalAsyncHandler;
  17955. bool asyncMessagePending;
  17956. };
  17957. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  17958. /********* End of inlined file: juce_AsyncUpdater.h *********/
  17959. /********* Start of inlined file: juce_Desktop.h *********/
  17960. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  17961. #define __JUCE_DESKTOP_JUCEHEADER__
  17962. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  17963. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17964. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17965. /**
  17966. Classes derived from this will be automatically deleted when the application exits.
  17967. After JUCEApplication::shutdown() has been called, any objects derived from
  17968. DeletedAtShutdown which are still in existence will be deleted in the reverse
  17969. order to that in which they were created.
  17970. So if you've got a singleton and don't want to have to explicitly delete it, just
  17971. inherit from this and it'll be taken care of.
  17972. */
  17973. class JUCE_API DeletedAtShutdown
  17974. {
  17975. protected:
  17976. /** Creates a DeletedAtShutdown object. */
  17977. DeletedAtShutdown() throw();
  17978. /** Destructor.
  17979. It's ok to delete these objects explicitly - it's only the ones left
  17980. dangling at the end that will be deleted automatically.
  17981. */
  17982. virtual ~DeletedAtShutdown();
  17983. public:
  17984. /** Deletes all extant objects.
  17985. This shouldn't be used by applications, as it's called automatically
  17986. in the shutdown code of the JUCEApplication class.
  17987. */
  17988. static void deleteAll();
  17989. private:
  17990. DeletedAtShutdown (const DeletedAtShutdown&);
  17991. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  17992. };
  17993. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  17994. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  17995. /********* Start of inlined file: juce_Timer.h *********/
  17996. #ifndef __JUCE_TIMER_JUCEHEADER__
  17997. #define __JUCE_TIMER_JUCEHEADER__
  17998. class InternalTimerThread;
  17999. /**
  18000. Repeatedly calls a user-defined method at a specified time interval.
  18001. A Timer's timerCallback() method will be repeatedly called at a given
  18002. interval. Initially when a Timer object is created, they will do nothing
  18003. until the startTimer() method is called, then the message thread will
  18004. start calling it back until stopTimer() is called.
  18005. The time interval isn't guaranteed to be precise to any more than maybe
  18006. 10-20ms, and the intervals may end up being much longer than requested if the
  18007. system is busy. Because it's the message thread that is doing the callbacks,
  18008. any messages that take a significant amount of time to process will block
  18009. all the timers for that period.
  18010. If you need to have a single callback that is shared by multiple timers with
  18011. different frequencies, then the MultiTimer class allows you to do that - its
  18012. structure is very similar to the Timer class, but contains multiple timers
  18013. internally, each one identified by an ID number.
  18014. @see MultiTimer
  18015. */
  18016. class JUCE_API Timer
  18017. {
  18018. protected:
  18019. /** Creates a Timer.
  18020. When created, the timer is stopped, so use startTimer() to get it going.
  18021. */
  18022. Timer() throw();
  18023. /** Creates a copy of another timer.
  18024. Note that this timer won't be started, even if the one you're copying
  18025. is running.
  18026. */
  18027. Timer (const Timer& other) throw();
  18028. public:
  18029. /** Destructor. */
  18030. virtual ~Timer();
  18031. /** The user-defined callback routine that actually gets called periodically.
  18032. It's perfectly ok to call startTimer() or stopTimer() from within this
  18033. callback to change the subsequent intervals.
  18034. */
  18035. virtual void timerCallback() = 0;
  18036. /** Starts the timer and sets the length of interval required.
  18037. If the timer is already started, this will reset it, so the
  18038. time between calling this method and the next timer callback
  18039. will not be less than the interval length passed in.
  18040. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  18041. rounded up to 1)
  18042. */
  18043. void startTimer (const int intervalInMilliseconds) throw();
  18044. /** Stops the timer.
  18045. No more callbacks will be made after this method returns.
  18046. If this is called from a different thread, any callbacks that may
  18047. be currently executing may be allowed to finish before the method
  18048. returns.
  18049. */
  18050. void stopTimer() throw();
  18051. /** Checks if the timer has been started.
  18052. @returns true if the timer is running.
  18053. */
  18054. bool isTimerRunning() const throw() { return periodMs > 0; }
  18055. /** Returns the timer's interval.
  18056. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  18057. */
  18058. int getTimerInterval() const throw() { return periodMs; }
  18059. private:
  18060. friend class InternalTimerThread;
  18061. int countdownMs, periodMs;
  18062. Timer* previous;
  18063. Timer* next;
  18064. const Timer& operator= (const Timer&);
  18065. };
  18066. #endif // __JUCE_TIMER_JUCEHEADER__
  18067. /********* End of inlined file: juce_Timer.h *********/
  18068. /**
  18069. Classes can implement this interface and register themselves with the Desktop class
  18070. to receive callbacks when the currently focused component changes.
  18071. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  18072. */
  18073. class JUCE_API FocusChangeListener
  18074. {
  18075. public:
  18076. /** Destructor. */
  18077. virtual ~FocusChangeListener() {}
  18078. /** Callback to indicate that the currently focused component has changed. */
  18079. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  18080. };
  18081. /**
  18082. Describes and controls aspects of the computer's desktop.
  18083. */
  18084. class JUCE_API Desktop : private DeletedAtShutdown,
  18085. private Timer,
  18086. private AsyncUpdater
  18087. {
  18088. public:
  18089. /** There's only one dektop object, and this method will return it.
  18090. */
  18091. static Desktop& JUCE_CALLTYPE getInstance() throw();
  18092. /** Returns a list of the positions of all the monitors available.
  18093. The first rectangle in the list will be the main monitor area.
  18094. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  18095. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  18096. */
  18097. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  18098. /** Returns the position and size of the main monitor.
  18099. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  18100. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  18101. */
  18102. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  18103. /** Returns the position and size of the monitor which contains this co-ordinate.
  18104. If none of the monitors contains the point, this will just return the
  18105. main monitor.
  18106. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  18107. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  18108. */
  18109. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  18110. /** Returns the mouse position.
  18111. The co-ordinates are relative to the top-left of the main monitor.
  18112. */
  18113. static void getMousePosition (int& x, int& y) throw();
  18114. /** Makes the mouse pointer jump to a given location.
  18115. The co-ordinates are relative to the top-left of the main monitor.
  18116. */
  18117. static void setMousePosition (int x, int y) throw();
  18118. /** Returns the last position at which a mouse button was pressed.
  18119. */
  18120. static void getLastMouseDownPosition (int& x, int& y) throw();
  18121. /** Returns the number of times the mouse button has been clicked since the
  18122. app started.
  18123. Each mouse-down event increments this number by 1.
  18124. */
  18125. static int getMouseButtonClickCounter() throw();
  18126. /** This lets you prevent the screensaver from becoming active.
  18127. Handy if you're running some sort of presentation app where having a screensaver
  18128. appear would be annoying.
  18129. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  18130. won't enable a screensaver unless the user has actually set one up).
  18131. The disablement will only happen while the Juce application is the foreground
  18132. process - if another task is running in front of it, then the screensaver will
  18133. be unaffected.
  18134. @see isScreenSaverEnabled
  18135. */
  18136. static void setScreenSaverEnabled (const bool isEnabled) throw();
  18137. /** Returns true if the screensaver has not been turned off.
  18138. This will return the last value passed into setScreenSaverEnabled(). Note that
  18139. it won't tell you whether the user is actually using a screen saver, just
  18140. whether this app is deliberately preventing one from running.
  18141. @see setScreenSaverEnabled
  18142. */
  18143. static bool isScreenSaverEnabled() throw();
  18144. /** Registers a MouseListener that will receive all mouse events that occur on
  18145. any component.
  18146. @see removeGlobalMouseListener
  18147. */
  18148. void addGlobalMouseListener (MouseListener* const listener) throw();
  18149. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  18150. method.
  18151. @see addGlobalMouseListener
  18152. */
  18153. void removeGlobalMouseListener (MouseListener* const listener) throw();
  18154. /** Registers a MouseListener that will receive a callback whenever the focused
  18155. component changes.
  18156. */
  18157. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  18158. /** Unregisters a listener that was added with addFocusChangeListener(). */
  18159. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  18160. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  18161. The component must already be on the desktop for this method to work. It will
  18162. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  18163. etc will be hidden.
  18164. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  18165. the component that's currently being used will be resized back to the size
  18166. and position it was in before being put into this mode.
  18167. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  18168. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  18169. to hide as much on-screen paraphenalia as possible.
  18170. */
  18171. void setKioskModeComponent (Component* componentToUse,
  18172. const bool allowMenusAndBars = true);
  18173. /** Returns the component that is currently being used in kiosk-mode.
  18174. This is the component that was last set by setKioskModeComponent(). If none
  18175. has been set, this returns 0.
  18176. */
  18177. Component* getKioskModeComponent() const { return kioskModeComponent; }
  18178. /** Returns the number of components that are currently active as top-level
  18179. desktop windows.
  18180. @see getComponent, Component::addToDesktop
  18181. */
  18182. int getNumComponents() const throw();
  18183. /** Returns one of the top-level desktop window components.
  18184. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  18185. index is out-of-range.
  18186. @see getNumComponents, Component::addToDesktop
  18187. */
  18188. Component* getComponent (const int index) const throw();
  18189. /** Finds the component at a given screen location.
  18190. This will drill down into top-level windows to find the child component at
  18191. the given position.
  18192. Returns 0 if the co-ordinates are inside a non-Juce window.
  18193. */
  18194. Component* findComponentAt (const int screenX,
  18195. const int screenY) const;
  18196. juce_UseDebuggingNewOperator
  18197. /** Tells this object to refresh its idea of what the screen resolution is.
  18198. (Called internally by the native code).
  18199. */
  18200. void refreshMonitorSizes() throw();
  18201. /** True if the OS supports semitransparent windows */
  18202. static bool canUseSemiTransparentWindows() throw();
  18203. private:
  18204. friend class Component;
  18205. friend class ComponentPeer;
  18206. SortedSet <void*> mouseListeners, focusListeners;
  18207. VoidArray desktopComponents;
  18208. friend class DeletedAtShutdown;
  18209. friend class TopLevelWindowManager;
  18210. Desktop() throw();
  18211. ~Desktop() throw();
  18212. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  18213. int lastMouseX, lastMouseY;
  18214. Component* kioskModeComponent;
  18215. Rectangle kioskComponentOriginalBounds;
  18216. void timerCallback();
  18217. void sendMouseMove();
  18218. void resetTimer() throw();
  18219. int getNumDisplayMonitors() const throw();
  18220. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  18221. void addDesktopComponent (Component* const c) throw();
  18222. void removeDesktopComponent (Component* const c) throw();
  18223. void componentBroughtToFront (Component* const c) throw();
  18224. void triggerFocusCallback() throw();
  18225. void handleAsyncUpdate();
  18226. Desktop (const Desktop&);
  18227. const Desktop& operator= (const Desktop&);
  18228. };
  18229. #endif // __JUCE_DESKTOP_JUCEHEADER__
  18230. /********* End of inlined file: juce_Desktop.h *********/
  18231. class KeyPressMappingSet;
  18232. class ApplicationCommandManagerListener;
  18233. /**
  18234. One of these objects holds a list of all the commands your app can perform,
  18235. and despatches these commands when needed.
  18236. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  18237. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  18238. to invoke automatically, which means you don't have to handle the result of a menu
  18239. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  18240. which can choose which events they want to handle.
  18241. This architecture also allows for nested ApplicationCommandTargets, so that for example
  18242. you could have two different objects, one inside the other, both of which can respond to
  18243. a "delete" command. Depending on which one has focus, the command will be sent to the
  18244. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  18245. method.
  18246. To set up your app to use commands, you'll need to do the following:
  18247. - Create a global ApplicationCommandManager to hold the list of all possible
  18248. commands. (This will also manage a set of key-mappings for them).
  18249. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  18250. This allows the object to provide a list of commands that it can perform, and
  18251. to handle them.
  18252. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  18253. or ApplicationCommandManager::registerCommand().
  18254. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  18255. method to access the key-mapper object, which you will need to register as a key-listener
  18256. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  18257. about setting this up.
  18258. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  18259. cause these commands to be invoked automatically.
  18260. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  18261. When a command is invoked, the ApplicationCommandManager will try to choose the best
  18262. ApplicationCommandTarget to receive the specified command. To do this it will use the
  18263. current keyboard focus to see which component might be interested, and will search the
  18264. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  18265. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  18266. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  18267. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  18268. point if the command still hasn't been performed, it will be passed to the current
  18269. JUCEApplication object (which is itself an ApplicationCommandTarget).
  18270. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  18271. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  18272. the object yourself.
  18273. @see ApplicationCommandTarget, ApplicationCommandInfo
  18274. */
  18275. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  18276. private FocusChangeListener
  18277. {
  18278. public:
  18279. /** Creates an ApplicationCommandManager.
  18280. Once created, you'll need to register all your app's commands with it, using
  18281. ApplicationCommandManager::registerAllCommandsForTarget() or
  18282. ApplicationCommandManager::registerCommand().
  18283. */
  18284. ApplicationCommandManager();
  18285. /** Destructor.
  18286. Make sure that you don't delete this if pointers to it are still being used by
  18287. objects such as PopupMenus or Buttons.
  18288. */
  18289. virtual ~ApplicationCommandManager();
  18290. /** Clears the current list of all commands.
  18291. Note that this will also clear the contents of the KeyPressMappingSet.
  18292. */
  18293. void clearCommands();
  18294. /** Adds a command to the list of registered commands.
  18295. @see registerAllCommandsForTarget
  18296. */
  18297. void registerCommand (const ApplicationCommandInfo& newCommand);
  18298. /** Adds all the commands that this target publishes to the manager's list.
  18299. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  18300. to get details about all the commands that this target can do, and will call
  18301. registerCommand() to add each one to the manger's list.
  18302. @see registerCommand
  18303. */
  18304. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  18305. /** Removes the command with a specified ID.
  18306. Note that this will also remove any key mappings that are mapped to the command.
  18307. */
  18308. void removeCommand (const CommandID commandID);
  18309. /** This should be called to tell the manager that one of its registered commands may have changed
  18310. its active status.
  18311. Because the command manager only finds out whether a command is active or inactive by querying
  18312. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  18313. allows things like buttons to update their enablement, etc.
  18314. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  18315. for any registered listeners.
  18316. */
  18317. void commandStatusChanged();
  18318. /** Returns the number of commands that have been registered.
  18319. @see registerCommand
  18320. */
  18321. int getNumCommands() const throw() { return commands.size(); }
  18322. /** Returns the details about one of the registered commands.
  18323. The index is between 0 and (getNumCommands() - 1).
  18324. */
  18325. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  18326. /** Returns the details about a given command ID.
  18327. This will search the list of registered commands for one with the given command
  18328. ID number, and return its associated info. If no matching command is found, this
  18329. will return 0.
  18330. */
  18331. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  18332. /** Returns the name field for a command.
  18333. An empty string is returned if no command with this ID has been registered.
  18334. @see getDescriptionOfCommand
  18335. */
  18336. const String getNameOfCommand (const CommandID commandID) const throw();
  18337. /** Returns the description field for a command.
  18338. An empty string is returned if no command with this ID has been registered. If the
  18339. command has no description, this will return its short name field instead.
  18340. @see getNameOfCommand
  18341. */
  18342. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  18343. /** Returns the list of categories.
  18344. This will go through all registered commands, and return a list of all the distict
  18345. categoryName values from their ApplicationCommandInfo structure.
  18346. @see getCommandsInCategory()
  18347. */
  18348. const StringArray getCommandCategories() const throw();
  18349. /** Returns a list of all the command UIDs in a particular category.
  18350. @see getCommandCategories()
  18351. */
  18352. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  18353. /** Returns the manager's internal set of key mappings.
  18354. This object can be used to edit the keypresses. To actually link this object up
  18355. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  18356. class.
  18357. @see KeyPressMappingSet
  18358. */
  18359. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  18360. /** Invokes the given command directly, sending it to the default target.
  18361. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  18362. structure.
  18363. */
  18364. bool invokeDirectly (const CommandID commandID,
  18365. const bool asynchronously);
  18366. /** Sends a command to the default target.
  18367. This will choose a target using getFirstCommandTarget(), and send the specified command
  18368. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  18369. first target can't handle the command, it will be passed on to targets further down the
  18370. chain (see ApplicationCommandTarget::invoke() for more info).
  18371. @param invocationInfo this must be correctly filled-in, describing the context for
  18372. the invocation.
  18373. @param asynchronously if false, the command will be performed before this method returns.
  18374. If true, a message will be posted so that the command will be performed
  18375. later on the message thread, and this method will return immediately.
  18376. @see ApplicationCommandTarget::invoke
  18377. */
  18378. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  18379. const bool asynchronously);
  18380. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  18381. Whenever the manager needs to know which target a command should be sent to, it calls
  18382. this method to determine the first one to try.
  18383. By default, this method will return the target that was set by calling setFirstCommandTarget().
  18384. If no target is set, it will return the result of findDefaultComponentTarget().
  18385. If you need to make sure all commands go via your own custom target, then you can
  18386. either use setFirstCommandTarget() to specify a single target, or override this method
  18387. if you need more complex logic to choose one.
  18388. It may return 0 if no targets are available.
  18389. @see getTargetForCommand, invoke, invokeDirectly
  18390. */
  18391. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  18392. /** Sets a target to be returned by getFirstCommandTarget().
  18393. If this is set to 0, then getFirstCommandTarget() will by default return the
  18394. result of findDefaultComponentTarget().
  18395. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  18396. deleting the target object.
  18397. */
  18398. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  18399. /** Tries to find the best target to use to perform a given command.
  18400. This will call getFirstCommandTarget() to find the preferred target, and will
  18401. check whether that target can handle the given command. If it can't, then it'll use
  18402. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  18403. so on until no more are available.
  18404. If no targets are found that can perform the command, this method will return 0.
  18405. If a target is found, then it will get the target to fill-in the upToDateInfo
  18406. structure with the latest info about that command, so that the caller can see
  18407. whether the command is disabled, ticked, etc.
  18408. */
  18409. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  18410. ApplicationCommandInfo& upToDateInfo);
  18411. /** Registers a listener that will be called when various events occur. */
  18412. void addListener (ApplicationCommandManagerListener* const listener) throw();
  18413. /** Deregisters a previously-added listener. */
  18414. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  18415. /** Looks for a suitable command target based on which Components have the keyboard focus.
  18416. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  18417. but is exposed here in case it's useful.
  18418. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  18419. windows, etc., and using the findTargetForComponent() method.
  18420. */
  18421. static ApplicationCommandTarget* findDefaultComponentTarget();
  18422. /** Examines this component and all its parents in turn, looking for the first one
  18423. which is a ApplicationCommandTarget.
  18424. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  18425. that class.
  18426. */
  18427. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  18428. juce_UseDebuggingNewOperator
  18429. private:
  18430. OwnedArray <ApplicationCommandInfo> commands;
  18431. SortedSet <void*> listeners;
  18432. KeyPressMappingSet* keyMappings;
  18433. ApplicationCommandTarget* firstTarget;
  18434. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  18435. void handleAsyncUpdate();
  18436. void globalFocusChanged (Component*);
  18437. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  18438. // version of this method.
  18439. virtual short getFirstCommandTarget() { return 0; }
  18440. };
  18441. /**
  18442. A listener that receives callbacks from an ApplicationCommandManager when
  18443. commands are invoked or the command list is changed.
  18444. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  18445. */
  18446. class JUCE_API ApplicationCommandManagerListener
  18447. {
  18448. public:
  18449. /** Destructor. */
  18450. virtual ~ApplicationCommandManagerListener() {}
  18451. /** Called when an app command is about to be invoked. */
  18452. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  18453. /** Called when commands are registered or deregistered from the
  18454. command manager, or when commands are made active or inactive.
  18455. Note that if you're using this to watch for changes to whether a command is disabled,
  18456. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  18457. whenever the status of your command might have changed.
  18458. */
  18459. virtual void applicationCommandListChanged() = 0;
  18460. };
  18461. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  18462. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  18463. #endif
  18464. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  18465. #endif
  18466. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18467. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  18468. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18469. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18470. /********* Start of inlined file: juce_PropertiesFile.h *********/
  18471. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  18472. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  18473. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  18474. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18475. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18476. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  18477. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18478. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18479. /********* Start of inlined file: juce_ChangeListener.h *********/
  18480. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  18481. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  18482. /**
  18483. Receives callbacks about changes to some kind of object.
  18484. Many objects use a ChangeListenerList to keep a set of listeners which they
  18485. will inform when something changes. A subclass of ChangeListener
  18486. is used to receive these callbacks.
  18487. Note that the major difference between an ActionListener and a ChangeListener
  18488. is that for a ChangeListener, multiple changes will be coalesced into fewer
  18489. callbacks, but ActionListeners perform one callback for every event posted.
  18490. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  18491. */
  18492. class JUCE_API ChangeListener
  18493. {
  18494. public:
  18495. /** Destructor. */
  18496. virtual ~ChangeListener() {}
  18497. /** Overridden by your subclass to receive the callback.
  18498. @param objectThatHasChanged the value that was passed to the
  18499. ChangeListenerList::sendChangeMessage() method
  18500. */
  18501. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  18502. };
  18503. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  18504. /********* End of inlined file: juce_ChangeListener.h *********/
  18505. /**
  18506. A set of ChangeListeners.
  18507. Listeners can be added and removed from the list, and change messages can be
  18508. broadcast to all the listeners.
  18509. @see ChangeListener, ChangeBroadcaster
  18510. */
  18511. class JUCE_API ChangeListenerList : public MessageListener
  18512. {
  18513. public:
  18514. /** Creates an empty list. */
  18515. ChangeListenerList() throw();
  18516. /** Destructor. */
  18517. ~ChangeListenerList() throw();
  18518. /** Adds a listener to the list.
  18519. (Trying to add a listener that's already on the list will have no effect).
  18520. */
  18521. void addChangeListener (ChangeListener* const listener) throw();
  18522. /** Removes a listener from the list.
  18523. If the listener isn't on the list, this won't have any effect.
  18524. */
  18525. void removeChangeListener (ChangeListener* const listener) throw();
  18526. /** Removes all listeners from the list. */
  18527. void removeAllChangeListeners() throw();
  18528. /** Posts an asynchronous change message to all the listeners.
  18529. If a message has already been sent and hasn't yet been delivered, this
  18530. method won't send another - in this way it coalesces multiple frequent
  18531. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  18532. with the ActionListener, which posts a new event for every call to its
  18533. sendActionMessage() method.
  18534. Only listeners which are on the list when the change event is delivered
  18535. will receive the event - and this may include listeners that weren't on
  18536. the list when the change message was sent.
  18537. @param objectThatHasChanged this pointer is passed to the
  18538. ChangeListener::changeListenerCallback() method,
  18539. and can be any value the application needs
  18540. @see sendSynchronousChangeMessage
  18541. */
  18542. void sendChangeMessage (void* objectThatHasChanged) throw();
  18543. /** This will synchronously callback all the ChangeListeners.
  18544. Use this if you need to synchronously force a call to all the
  18545. listeners' ChangeListener::changeListenerCallback() methods.
  18546. */
  18547. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18548. /** If a change message has been sent but not yet dispatched, this will
  18549. use sendSynchronousChangeMessage() to make the callback immediately.
  18550. */
  18551. void dispatchPendingMessages();
  18552. /** @internal */
  18553. void handleMessage (const Message&);
  18554. juce_UseDebuggingNewOperator
  18555. private:
  18556. SortedSet <void*> listeners;
  18557. CriticalSection lock;
  18558. void* lastChangedObject;
  18559. bool messagePending;
  18560. ChangeListenerList (const ChangeListenerList&);
  18561. const ChangeListenerList& operator= (const ChangeListenerList&);
  18562. };
  18563. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  18564. /********* End of inlined file: juce_ChangeListenerList.h *********/
  18565. /** Manages a list of ChangeListeners, and can send them messages.
  18566. To quickly add methods to your class that can add/remove change
  18567. listeners and broadcast to them, you can derive from this.
  18568. @see ChangeListenerList, ChangeListener
  18569. */
  18570. class JUCE_API ChangeBroadcaster
  18571. {
  18572. public:
  18573. /** Creates an ChangeBroadcaster. */
  18574. ChangeBroadcaster() throw();
  18575. /** Destructor. */
  18576. virtual ~ChangeBroadcaster();
  18577. /** Adds a listener to the list.
  18578. (Trying to add a listener that's already on the list will have no effect).
  18579. */
  18580. void addChangeListener (ChangeListener* const listener) throw();
  18581. /** Removes a listener from the list.
  18582. If the listener isn't on the list, this won't have any effect.
  18583. */
  18584. void removeChangeListener (ChangeListener* const listener) throw();
  18585. /** Removes all listeners from the list. */
  18586. void removeAllChangeListeners() throw();
  18587. /** Broadcasts a change message to all the registered listeners.
  18588. The message will be delivered asynchronously by the event thread, so this
  18589. method will not directly call any of the listeners. For a synchronous
  18590. message, use sendSynchronousChangeMessage().
  18591. @see ChangeListenerList::sendActionMessage
  18592. */
  18593. void sendChangeMessage (void* objectThatHasChanged) throw();
  18594. /** Sends a synchronous change message to all the registered listeners.
  18595. @see ChangeListenerList::sendSynchronousChangeMessage
  18596. */
  18597. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  18598. /** If a change message has been sent but not yet dispatched, this will
  18599. use sendSynchronousChangeMessage() to make the callback immediately.
  18600. */
  18601. void dispatchPendingMessages();
  18602. private:
  18603. ChangeListenerList changeListenerList;
  18604. ChangeBroadcaster (const ChangeBroadcaster&);
  18605. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  18606. };
  18607. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  18608. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  18609. /** Wrapper on a file that stores a list of key/value data pairs.
  18610. Useful for storing application settings, etc. See the PropertySet class for
  18611. the interfaces that read and write values.
  18612. Not designed for very large amounts of data, as it keeps all the values in
  18613. memory and writes them out to disk lazily when they are changed.
  18614. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  18615. with it, and these will be signalled when a value changes.
  18616. @see PropertySet
  18617. */
  18618. class JUCE_API PropertiesFile : public PropertySet,
  18619. public ChangeBroadcaster,
  18620. private Timer
  18621. {
  18622. public:
  18623. enum FileFormatOptions
  18624. {
  18625. ignoreCaseOfKeyNames = 1,
  18626. storeAsBinary = 2,
  18627. storeAsCompressedBinary = 4,
  18628. storeAsXML = 8
  18629. };
  18630. /**
  18631. Creates a PropertiesFile object.
  18632. @param file the file to use
  18633. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  18634. is changed, the object will wait for this amount
  18635. of time and then save the file. If zero, the file
  18636. will be written to disk immediately on being changed
  18637. (which might be slow, as it'll re-write synchronously
  18638. each time a value-change method is called). If it is
  18639. less than zero, the file won't be saved until
  18640. save() or saveIfNeeded() are explicitly called.
  18641. @param options a combination of the flags in the FileFormatOptions
  18642. enum, which specify the type of file to save, and other
  18643. options.
  18644. */
  18645. PropertiesFile (const File& file,
  18646. const int millisecondsBeforeSaving,
  18647. const int options) throw();
  18648. /** Destructor.
  18649. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  18650. */
  18651. ~PropertiesFile();
  18652. /** This will flush all the values to disk if they've changed since the last
  18653. time they were saved.
  18654. Returns false if it fails to write to the file for some reason (maybe because
  18655. it's read-only or the directory doesn't exist or something).
  18656. @see save
  18657. */
  18658. bool saveIfNeeded();
  18659. /** This will force a write-to-disk of the current values, regardless of whether
  18660. anything has changed since the last save.
  18661. Returns false if it fails to write to the file for some reason (maybe because
  18662. it's read-only or the directory doesn't exist or something).
  18663. @see saveIfNeeded
  18664. */
  18665. bool save();
  18666. /** Returns true if the properties have been altered since the last time they were
  18667. saved.
  18668. */
  18669. bool needsToBeSaved() const throw();
  18670. /** Returns the file that's being used. */
  18671. const File getFile() const throw();
  18672. /** Handy utility to create a properties file in whatever the standard OS-specific
  18673. location is for these things.
  18674. This uses getDefaultAppSettingsFile() to decide what file to create, then
  18675. creates a PropertiesFile object with the specified properties. See
  18676. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  18677. what the parameters do.
  18678. @see getDefaultAppSettingsFile
  18679. */
  18680. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  18681. const String& fileNameSuffix,
  18682. const String& folderName,
  18683. const bool commonToAllUsers,
  18684. const int millisecondsBeforeSaving,
  18685. const int propertiesFileOptions);
  18686. /** Handy utility to choose a file in the standard OS-dependent location for application
  18687. settings files.
  18688. So on a Mac, this will return a file called:
  18689. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  18690. On Windows it'll return something like:
  18691. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  18692. On Linux it'll return
  18693. ~/.[folderName]/[applicationName].[fileNameSuffix]
  18694. If you pass an empty string as the folder name, it'll use the app name for this (or
  18695. omit the folder name on the Mac).
  18696. If commonToAllUsers is true, then this will return the same file for all users of the
  18697. computer, regardless of the current user. If it is false, the file will be specific to
  18698. only the current user. Use this to choose whether you're saving settings that are common
  18699. or user-specific.
  18700. */
  18701. static const File getDefaultAppSettingsFile (const String& applicationName,
  18702. const String& fileNameSuffix,
  18703. const String& folderName,
  18704. const bool commonToAllUsers);
  18705. juce_UseDebuggingNewOperator
  18706. protected:
  18707. virtual void propertyChanged();
  18708. private:
  18709. File file;
  18710. int timerInterval;
  18711. const int options;
  18712. bool needsWriting;
  18713. void timerCallback();
  18714. PropertiesFile (const PropertiesFile&);
  18715. const PropertiesFile& operator= (const PropertiesFile&);
  18716. };
  18717. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  18718. /********* End of inlined file: juce_PropertiesFile.h *********/
  18719. /**
  18720. Manages a collection of properties.
  18721. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  18722. as a singleton.
  18723. It holds two different PropertiesFile objects internally, one for user-specific
  18724. settings (stored in your user directory), and one for settings that are common to
  18725. all users (stored in a folder accessible to all users).
  18726. The class manages the creation of these files on-demand, allowing access via the
  18727. getUserSettings() and getCommonSettings() methods. It also has a few handy
  18728. methods like testWriteAccess() to check that the files can be saved.
  18729. If you're using one of these as a singleton, then your app's start-up code should
  18730. first of all call setStorageParameters() to tell it the parameters to use to create
  18731. the properties files.
  18732. @see PropertiesFile
  18733. */
  18734. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  18735. {
  18736. public:
  18737. /**
  18738. Creates an ApplicationProperties object.
  18739. Before using it, you must call setStorageParameters() to give it the info
  18740. it needs to create the property files.
  18741. */
  18742. ApplicationProperties() throw();
  18743. /** Destructor.
  18744. */
  18745. ~ApplicationProperties();
  18746. juce_DeclareSingleton (ApplicationProperties, false)
  18747. /** Gives the object the information it needs to create the appropriate properties files.
  18748. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  18749. info about how these parameters are used.
  18750. */
  18751. void setStorageParameters (const String& applicationName,
  18752. const String& fileNameSuffix,
  18753. const String& folderName,
  18754. const int millisecondsBeforeSaving,
  18755. const int propertiesFileOptions) throw();
  18756. /** Tests whether the files can be successfully written to, and can show
  18757. an error message if not.
  18758. Returns true if none of the tests fail.
  18759. @param testUserSettings if true, the user settings file will be tested
  18760. @param testCommonSettings if true, the common settings file will be tested
  18761. @param showWarningDialogOnFailure if true, the method will show a helpful error
  18762. message box if either of the tests fail
  18763. */
  18764. bool testWriteAccess (const bool testUserSettings,
  18765. const bool testCommonSettings,
  18766. const bool showWarningDialogOnFailure);
  18767. /** Returns the user settings file.
  18768. The first time this is called, it will create and load the properties file.
  18769. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  18770. the common settings are used as a second-chance place to look. This is done via the
  18771. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  18772. to the fallback for the user settings.
  18773. @see getCommonSettings
  18774. */
  18775. PropertiesFile* getUserSettings() throw();
  18776. /** Returns the common settings file.
  18777. The first time this is called, it will create and load the properties file.
  18778. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  18779. read-only (e.g. because the user doesn't have permission to write
  18780. to shared files), then this will return the user settings instead,
  18781. (like getUserSettings() would do). This is handy if you'd like to
  18782. write a value to the common settings, but if that's no possible,
  18783. then you'd rather write to the user settings than none at all.
  18784. If returnUserPropsIfReadOnly is false, this method will always return
  18785. the common settings, even if any changes to them can't be saved.
  18786. @see getUserSettings
  18787. */
  18788. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  18789. /** Saves both files if they need to be saved.
  18790. @see PropertiesFile::saveIfNeeded
  18791. */
  18792. bool saveIfNeeded();
  18793. /** Flushes and closes both files if they are open.
  18794. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  18795. and closes both files. They will then be re-opened the next time getUserSettings()
  18796. or getCommonSettings() is called.
  18797. */
  18798. void closeFiles();
  18799. juce_UseDebuggingNewOperator
  18800. private:
  18801. PropertiesFile* userProps;
  18802. PropertiesFile* commonProps;
  18803. String appName, fileSuffix, folderName;
  18804. int msBeforeSaving, options;
  18805. int commonSettingsAreReadOnly;
  18806. ApplicationProperties (const ApplicationProperties&);
  18807. const ApplicationProperties& operator= (const ApplicationProperties&);
  18808. void openFiles() throw();
  18809. };
  18810. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  18811. /********* End of inlined file: juce_ApplicationProperties.h *********/
  18812. #endif
  18813. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18814. /********* Start of inlined file: juce_MidiBuffer.h *********/
  18815. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  18816. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  18817. /********* Start of inlined file: juce_MidiMessage.h *********/
  18818. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  18819. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  18820. /**
  18821. Encapsulates a MIDI message.
  18822. @see MidiMessageSequence, MidiOutput, MidiInput
  18823. */
  18824. class JUCE_API MidiMessage
  18825. {
  18826. public:
  18827. /** Creates a 3-byte short midi message.
  18828. @param byte1 message byte 1
  18829. @param byte2 message byte 2
  18830. @param byte3 message byte 3
  18831. @param timeStamp the time to give the midi message - this value doesn't
  18832. use any particular units, so will be application-specific
  18833. */
  18834. MidiMessage (const int byte1,
  18835. const int byte2,
  18836. const int byte3,
  18837. const double timeStamp = 0) throw();
  18838. /** Creates a 2-byte short midi message.
  18839. @param byte1 message byte 1
  18840. @param byte2 message byte 2
  18841. @param timeStamp the time to give the midi message - this value doesn't
  18842. use any particular units, so will be application-specific
  18843. */
  18844. MidiMessage (const int byte1,
  18845. const int byte2,
  18846. const double timeStamp = 0) throw();
  18847. /** Creates a 1-byte short midi message.
  18848. @param byte1 message byte 1
  18849. @param timeStamp the time to give the midi message - this value doesn't
  18850. use any particular units, so will be application-specific
  18851. */
  18852. MidiMessage (const int byte1,
  18853. const double timeStamp = 0) throw();
  18854. /** Creates a midi message from a block of data. */
  18855. MidiMessage (const uint8* const data,
  18856. const int dataSize,
  18857. const double timeStamp = 0) throw();
  18858. /** Reads the next midi message from some data.
  18859. This will read as many bytes from a data stream as it needs to make a
  18860. complete message, and will return the number of bytes it used. This lets
  18861. you read a sequence of midi messages from a file or stream.
  18862. @param data the data to read from
  18863. @param size the maximum number of bytes it's allowed to read
  18864. @param numBytesUsed returns the number of bytes that were actually needed
  18865. @param lastStatusByte in a sequence of midi messages, the initial byte
  18866. can be dropped from a message if it's the same as the
  18867. first byte of the previous message, so this lets you
  18868. supply the byte to use if the first byte of the message
  18869. has in fact been dropped.
  18870. @param timeStamp the time to give the midi message - this value doesn't
  18871. use any particular units, so will be application-specific
  18872. */
  18873. MidiMessage (const uint8* data,
  18874. int size,
  18875. int& numBytesUsed,
  18876. uint8 lastStatusByte,
  18877. double timeStamp = 0) throw();
  18878. /** Creates a copy of another midi message. */
  18879. MidiMessage (const MidiMessage& other) throw();
  18880. /** Creates a copy of another midi message, with a different timestamp. */
  18881. MidiMessage (const MidiMessage& other,
  18882. const double newTimeStamp) throw();
  18883. /** Destructor. */
  18884. ~MidiMessage() throw();
  18885. /** Copies this message from another one. */
  18886. const MidiMessage& operator= (const MidiMessage& other) throw();
  18887. /** Returns a pointer to the raw midi data.
  18888. @see getRawDataSize
  18889. */
  18890. uint8* getRawData() const throw() { return data; }
  18891. /** Returns the number of bytes of data in the message.
  18892. @see getRawData
  18893. */
  18894. int getRawDataSize() const throw() { return size; }
  18895. /** Returns the timestamp associated with this message.
  18896. The exact meaning of this time and its units will vary, as messages are used in
  18897. a variety of different contexts.
  18898. If you're getting the message from a midi file, this could be a time in seconds, or
  18899. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  18900. If the message is being used in a MidiBuffer, it might indicate the number of
  18901. audio samples from the start of the buffer.
  18902. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  18903. for details of the way that it initialises this value.
  18904. @see setTimeStamp, addToTimeStamp
  18905. */
  18906. double getTimeStamp() const throw() { return timeStamp; }
  18907. /** Changes the message's associated timestamp.
  18908. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  18909. @see addToTimeStamp, getTimeStamp
  18910. */
  18911. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18912. /** Adds a value to the message's timestamp.
  18913. The units for the timestamp will be application-specific.
  18914. */
  18915. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18916. /** Returns the midi channel associated with the message.
  18917. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18918. if it's a sysex)
  18919. @see isForChannel, setChannel
  18920. */
  18921. int getChannel() const throw();
  18922. /** Returns true if the message applies to the given midi channel.
  18923. @param channelNumber the channel number to look for, in the range 1 to 16
  18924. @see getChannel, setChannel
  18925. */
  18926. bool isForChannel (const int channelNumber) const throw();
  18927. /** Changes the message's midi channel.
  18928. This won't do anything for non-channel messages like sysexes.
  18929. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18930. */
  18931. void setChannel (const int newChannelNumber) throw();
  18932. /** Returns true if this is a system-exclusive message.
  18933. */
  18934. bool isSysEx() const throw();
  18935. /** Returns a pointer to the sysex data inside the message.
  18936. If this event isn't a sysex event, it'll return 0.
  18937. @see getSysExDataSize
  18938. */
  18939. const uint8* getSysExData() const throw();
  18940. /** Returns the size of the sysex data.
  18941. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18942. @see getSysExData
  18943. */
  18944. int getSysExDataSize() const throw();
  18945. /** Returns true if this message is a 'key-down' event.
  18946. This will return false for a note-on event with a velocity of 0.
  18947. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18948. */
  18949. bool isNoteOn() const throw();
  18950. /** Creates a key-down message (using a floating-point velocity).
  18951. @param channel the midi channel, in the range 1 to 16
  18952. @param noteNumber the key number, 0 to 127
  18953. @param velocity in the range 0 to 1.0
  18954. @see isNoteOn
  18955. */
  18956. static const MidiMessage noteOn (const int channel,
  18957. const int noteNumber,
  18958. const float velocity) throw();
  18959. /** Creates a key-down message (using an integer velocity).
  18960. @param channel the midi channel, in the range 1 to 16
  18961. @param noteNumber the key number, 0 to 127
  18962. @param velocity in the range 0 to 127
  18963. @see isNoteOn
  18964. */
  18965. static const MidiMessage noteOn (const int channel,
  18966. const int noteNumber,
  18967. const uint8 velocity) throw();
  18968. /** Returns true if this message is a 'key-up' event.
  18969. This will also return true for a note-on event with a velocity of 0.
  18970. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18971. */
  18972. bool isNoteOff() const throw();
  18973. /** Creates a key-up message.
  18974. @param channel the midi channel, in the range 1 to 16
  18975. @param noteNumber the key number, 0 to 127
  18976. @see isNoteOff
  18977. */
  18978. static const MidiMessage noteOff (const int channel,
  18979. const int noteNumber) throw();
  18980. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18981. @see isNoteOn, isNoteOff
  18982. */
  18983. bool isNoteOnOrOff() const throw();
  18984. /** Returns the midi note number for note-on and note-off messages.
  18985. If the message isn't a note-on or off, the value returned will be
  18986. meaningless.
  18987. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18988. */
  18989. int getNoteNumber() const throw();
  18990. /** Changes the midi note number of a note-on or note-off message.
  18991. If the message isn't a note on or off, this will do nothing.
  18992. */
  18993. void setNoteNumber (const int newNoteNumber) throw();
  18994. /** Returns the velocity of a note-on or note-off message.
  18995. The value returned will be in the range 0 to 127.
  18996. If the message isn't a note-on or off event, it will return 0.
  18997. @see getFloatVelocity
  18998. */
  18999. uint8 getVelocity() const throw();
  19000. /** Returns the velocity of a note-on or note-off message.
  19001. The value returned will be in the range 0 to 1.0
  19002. If the message isn't a note-on or off event, it will return 0.
  19003. @see getVelocity, setVelocity
  19004. */
  19005. float getFloatVelocity() const throw();
  19006. /** Changes the velocity of a note-on or note-off message.
  19007. If the message isn't a note on or off, this will do nothing.
  19008. @param newVelocity the new velocity, in the range 0 to 1.0
  19009. @see getFloatVelocity, multiplyVelocity
  19010. */
  19011. void setVelocity (const float newVelocity) throw();
  19012. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  19013. If the message isn't a note on or off, this will do nothing.
  19014. @param scaleFactor the value by which to multiply the velocity
  19015. @see setVelocity
  19016. */
  19017. void multiplyVelocity (const float scaleFactor) throw();
  19018. /** Returns true if the message is a program (patch) change message.
  19019. @see getProgramChangeNumber, getGMInstrumentName
  19020. */
  19021. bool isProgramChange() const throw();
  19022. /** Returns the new program number of a program change message.
  19023. If the message isn't a program change, the value returned will be
  19024. nonsense.
  19025. @see isProgramChange, getGMInstrumentName
  19026. */
  19027. int getProgramChangeNumber() const throw();
  19028. /** Creates a program-change message.
  19029. @param channel the midi channel, in the range 1 to 16
  19030. @param programNumber the midi program number, 0 to 127
  19031. @see isProgramChange, getGMInstrumentName
  19032. */
  19033. static const MidiMessage programChange (const int channel,
  19034. const int programNumber) throw();
  19035. /** Returns true if the message is a pitch-wheel move.
  19036. @see getPitchWheelValue, pitchWheel
  19037. */
  19038. bool isPitchWheel() const throw();
  19039. /** Returns the pitch wheel position from a pitch-wheel move message.
  19040. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  19041. If called for messages which aren't pitch wheel events, the number returned will be
  19042. nonsense.
  19043. @see isPitchWheel
  19044. */
  19045. int getPitchWheelValue() const throw();
  19046. /** Creates a pitch-wheel move message.
  19047. @param channel the midi channel, in the range 1 to 16
  19048. @param position the wheel position, in the range 0 to 16383
  19049. @see isPitchWheel
  19050. */
  19051. static const MidiMessage pitchWheel (const int channel,
  19052. const int position) throw();
  19053. /** Returns true if the message is an aftertouch event.
  19054. For aftertouch events, use the getNoteNumber() method to find out the key
  19055. that it applies to, and getAftertouchValue() to find out the amount. Use
  19056. getChannel() to find out the channel.
  19057. @see getAftertouchValue, getNoteNumber
  19058. */
  19059. bool isAftertouch() const throw();
  19060. /** Returns the amount of aftertouch from an aftertouch messages.
  19061. The value returned is in the range 0 to 127, and will be nonsense for messages
  19062. other than aftertouch messages.
  19063. @see isAftertouch
  19064. */
  19065. int getAfterTouchValue() const throw();
  19066. /** Creates an aftertouch message.
  19067. @param channel the midi channel, in the range 1 to 16
  19068. @param noteNumber the key number, 0 to 127
  19069. @param aftertouchAmount the amount of aftertouch, 0 to 127
  19070. @see isAftertouch
  19071. */
  19072. static const MidiMessage aftertouchChange (const int channel,
  19073. const int noteNumber,
  19074. const int aftertouchAmount) throw();
  19075. /** Returns true if the message is a channel-pressure change event.
  19076. This is like aftertouch, but common to the whole channel rather than a specific
  19077. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  19078. to find out the channel.
  19079. @see channelPressureChange
  19080. */
  19081. bool isChannelPressure() const throw();
  19082. /** Returns the pressure from a channel pressure change message.
  19083. @returns the pressure, in the range 0 to 127
  19084. @see isChannelPressure, channelPressureChange
  19085. */
  19086. int getChannelPressureValue() const throw();
  19087. /** Creates a channel-pressure change event.
  19088. @param channel the midi channel: 1 to 16
  19089. @param pressure the pressure, 0 to 127
  19090. @see isChannelPressure
  19091. */
  19092. static const MidiMessage channelPressureChange (const int channel,
  19093. const int pressure) throw();
  19094. /** Returns true if this is a midi controller message.
  19095. @see getControllerNumber, getControllerValue, controllerEvent
  19096. */
  19097. bool isController() const throw();
  19098. /** Returns the controller number of a controller message.
  19099. The name of the controller can be looked up using the getControllerName() method.
  19100. Note that the value returned is invalid for messages that aren't controller changes.
  19101. @see isController, getControllerName, getControllerValue
  19102. */
  19103. int getControllerNumber() const throw();
  19104. /** Returns the controller value from a controller message.
  19105. A value 0 to 127 is returned to indicate the new controller position.
  19106. Note that the value returned is invalid for messages that aren't controller changes.
  19107. @see isController, getControllerNumber
  19108. */
  19109. int getControllerValue() const throw();
  19110. /** Creates a controller message.
  19111. @param channel the midi channel, in the range 1 to 16
  19112. @param controllerType the type of controller
  19113. @param value the controller value
  19114. @see isController
  19115. */
  19116. static const MidiMessage controllerEvent (const int channel,
  19117. const int controllerType,
  19118. const int value) throw();
  19119. /** Checks whether this message is an all-notes-off message.
  19120. @see allNotesOff
  19121. */
  19122. bool isAllNotesOff() const throw();
  19123. /** Checks whether this message is an all-sound-off message.
  19124. @see allSoundOff
  19125. */
  19126. bool isAllSoundOff() const throw();
  19127. /** Creates an all-notes-off message.
  19128. @param channel the midi channel, in the range 1 to 16
  19129. @see isAllNotesOff
  19130. */
  19131. static const MidiMessage allNotesOff (const int channel) throw();
  19132. /** Creates an all-sound-off message.
  19133. @param channel the midi channel, in the range 1 to 16
  19134. @see isAllSoundOff
  19135. */
  19136. static const MidiMessage allSoundOff (const int channel) throw();
  19137. /** Creates an all-controllers-off message.
  19138. @param channel the midi channel, in the range 1 to 16
  19139. */
  19140. static const MidiMessage allControllersOff (const int channel) throw();
  19141. /** Returns true if this event is a meta-event.
  19142. Meta-events are things like tempo changes, track names, etc.
  19143. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  19144. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  19145. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  19146. */
  19147. bool isMetaEvent() const throw();
  19148. /** Returns a meta-event's type number.
  19149. If the message isn't a meta-event, this will return -1.
  19150. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  19151. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  19152. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  19153. */
  19154. int getMetaEventType() const throw();
  19155. /** Returns a pointer to the data in a meta-event.
  19156. @see isMetaEvent, getMetaEventLength
  19157. */
  19158. const uint8* getMetaEventData() const throw();
  19159. /** Returns the length of the data for a meta-event.
  19160. @see isMetaEvent, getMetaEventData
  19161. */
  19162. int getMetaEventLength() const throw();
  19163. /** Returns true if this is a 'track' meta-event. */
  19164. bool isTrackMetaEvent() const throw();
  19165. /** Returns true if this is an 'end-of-track' meta-event. */
  19166. bool isEndOfTrackMetaEvent() const throw();
  19167. /** Creates an end-of-track meta-event.
  19168. @see isEndOfTrackMetaEvent
  19169. */
  19170. static const MidiMessage endOfTrack() throw();
  19171. /** Returns true if this is an 'track name' meta-event.
  19172. You can use the getTextFromTextMetaEvent() method to get the track's name.
  19173. */
  19174. bool isTrackNameEvent() const throw();
  19175. /** Returns true if this is a 'text' meta-event.
  19176. @see getTextFromTextMetaEvent
  19177. */
  19178. bool isTextMetaEvent() const throw();
  19179. /** Returns the text from a text meta-event.
  19180. @see isTextMetaEvent
  19181. */
  19182. const String getTextFromTextMetaEvent() const throw();
  19183. /** Returns true if this is a 'tempo' meta-event.
  19184. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  19185. */
  19186. bool isTempoMetaEvent() const throw();
  19187. /** Returns the tick length from a tempo meta-event.
  19188. @param timeFormat the 16-bit time format value from the midi file's header.
  19189. @returns the tick length (in seconds).
  19190. @see isTempoMetaEvent
  19191. */
  19192. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  19193. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  19194. @see isTempoMetaEvent, getTempoMetaEventTickLength
  19195. */
  19196. double getTempoSecondsPerQuarterNote() const throw();
  19197. /** Creates a tempo meta-event.
  19198. @see isTempoMetaEvent
  19199. */
  19200. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  19201. /** Returns true if this is a 'time-signature' meta-event.
  19202. @see getTimeSignatureInfo
  19203. */
  19204. bool isTimeSignatureMetaEvent() const throw();
  19205. /** Returns the time-signature values from a time-signature meta-event.
  19206. @see isTimeSignatureMetaEvent
  19207. */
  19208. void getTimeSignatureInfo (int& numerator,
  19209. int& denominator) const throw();
  19210. /** Creates a time-signature meta-event.
  19211. @see isTimeSignatureMetaEvent
  19212. */
  19213. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  19214. const int denominator) throw();
  19215. /** Returns true if this is a 'key-signature' meta-event.
  19216. @see getKeySignatureNumberOfSharpsOrFlats
  19217. */
  19218. bool isKeySignatureMetaEvent() const throw();
  19219. /** Returns the key from a key-signature meta-event.
  19220. @see isKeySignatureMetaEvent
  19221. */
  19222. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  19223. /** Returns true if this is a 'channel' meta-event.
  19224. A channel meta-event specifies the midi channel that should be used
  19225. for subsequent meta-events.
  19226. @see getMidiChannelMetaEventChannel
  19227. */
  19228. bool isMidiChannelMetaEvent() const throw();
  19229. /** Returns the channel number from a channel meta-event.
  19230. @returns the channel, in the range 1 to 16.
  19231. @see isMidiChannelMetaEvent
  19232. */
  19233. int getMidiChannelMetaEventChannel() const throw();
  19234. /** Creates a midi channel meta-event.
  19235. @param channel the midi channel, in the range 1 to 16
  19236. @see isMidiChannelMetaEvent
  19237. */
  19238. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  19239. /** Returns true if this is an active-sense message. */
  19240. bool isActiveSense() const throw();
  19241. /** Returns true if this is a midi start event.
  19242. @see midiStart
  19243. */
  19244. bool isMidiStart() const throw();
  19245. /** Creates a midi start event. */
  19246. static const MidiMessage midiStart() throw();
  19247. /** Returns true if this is a midi continue event.
  19248. @see midiContinue
  19249. */
  19250. bool isMidiContinue() const throw();
  19251. /** Creates a midi continue event. */
  19252. static const MidiMessage midiContinue() throw();
  19253. /** Returns true if this is a midi stop event.
  19254. @see midiStop
  19255. */
  19256. bool isMidiStop() const throw();
  19257. /** Creates a midi stop event. */
  19258. static const MidiMessage midiStop() throw();
  19259. /** Returns true if this is a midi clock event.
  19260. @see midiClock, songPositionPointer
  19261. */
  19262. bool isMidiClock() const throw();
  19263. /** Creates a midi clock event. */
  19264. static const MidiMessage midiClock() throw();
  19265. /** Returns true if this is a song-position-pointer message.
  19266. @see getSongPositionPointerMidiBeat, songPositionPointer
  19267. */
  19268. bool isSongPositionPointer() const throw();
  19269. /** Returns the midi beat-number of a song-position-pointer message.
  19270. @see isSongPositionPointer, songPositionPointer
  19271. */
  19272. int getSongPositionPointerMidiBeat() const throw();
  19273. /** Creates a song-position-pointer message.
  19274. The position is a number of midi beats from the start of the song, where 1 midi
  19275. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  19276. are 4 midi beats in a quarter-note.
  19277. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  19278. */
  19279. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  19280. /** Returns true if this is a quarter-frame midi timecode message.
  19281. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  19282. */
  19283. bool isQuarterFrame() const throw();
  19284. /** Returns the sequence number of a quarter-frame midi timecode message.
  19285. This will be a value between 0 and 7.
  19286. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  19287. */
  19288. int getQuarterFrameSequenceNumber() const throw();
  19289. /** Returns the value from a quarter-frame message.
  19290. This will be the lower nybble of the message's data-byte, a value
  19291. between 0 and 15
  19292. */
  19293. int getQuarterFrameValue() const throw();
  19294. /** Creates a quarter-frame MTC message.
  19295. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  19296. @param value a value 0 to 15 for the lower nybble of the message's data byte
  19297. */
  19298. static const MidiMessage quarterFrame (const int sequenceNumber,
  19299. const int value) throw();
  19300. /** SMPTE timecode types.
  19301. Used by the getFullFrameParameters() and fullFrame() methods.
  19302. */
  19303. enum SmpteTimecodeType
  19304. {
  19305. fps24 = 0,
  19306. fps25 = 1,
  19307. fps30drop = 2,
  19308. fps30 = 3
  19309. };
  19310. /** Returns true if this is a full-frame midi timecode message.
  19311. */
  19312. bool isFullFrame() const throw();
  19313. /** Extracts the timecode information from a full-frame midi timecode message.
  19314. You should only call this on messages where you've used isFullFrame() to
  19315. check that they're the right kind.
  19316. */
  19317. void getFullFrameParameters (int& hours,
  19318. int& minutes,
  19319. int& seconds,
  19320. int& frames,
  19321. SmpteTimecodeType& timecodeType) const throw();
  19322. /** Creates a full-frame MTC message.
  19323. */
  19324. static const MidiMessage fullFrame (const int hours,
  19325. const int minutes,
  19326. const int seconds,
  19327. const int frames,
  19328. SmpteTimecodeType timecodeType);
  19329. /** Types of MMC command.
  19330. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  19331. */
  19332. enum MidiMachineControlCommand
  19333. {
  19334. mmc_stop = 1,
  19335. mmc_play = 2,
  19336. mmc_deferredplay = 3,
  19337. mmc_fastforward = 4,
  19338. mmc_rewind = 5,
  19339. mmc_recordStart = 6,
  19340. mmc_recordStop = 7,
  19341. mmc_pause = 9
  19342. };
  19343. /** Checks whether this is an MMC message.
  19344. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  19345. */
  19346. bool isMidiMachineControlMessage() const throw();
  19347. /** For an MMC message, this returns its type.
  19348. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  19349. calling this method.
  19350. */
  19351. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  19352. /** Creates an MMC message.
  19353. */
  19354. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  19355. /** Checks whether this is an MMC "goto" message.
  19356. If it is, the parameters passed-in are set to the time that the message contains.
  19357. @see midiMachineControlGoto
  19358. */
  19359. bool isMidiMachineControlGoto (int& hours,
  19360. int& minutes,
  19361. int& seconds,
  19362. int& frames) const throw();
  19363. /** Creates an MMC "goto" message.
  19364. This messages tells the device to go to a specific frame.
  19365. @see isMidiMachineControlGoto
  19366. */
  19367. static const MidiMessage midiMachineControlGoto (int hours,
  19368. int minutes,
  19369. int seconds,
  19370. int frames);
  19371. /** Creates a master-volume change message.
  19372. @param volume the volume, 0 to 1.0
  19373. */
  19374. static const MidiMessage masterVolume (const float volume) throw();
  19375. /** Creates a system-exclusive message.
  19376. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  19377. */
  19378. static const MidiMessage createSysExMessage (const uint8* sysexData,
  19379. const int dataSize) throw();
  19380. /** Reads a midi variable-length integer.
  19381. @param data the data to read the number from
  19382. @param numBytesUsed on return, this will be set to the number of bytes that were read
  19383. */
  19384. static int readVariableLengthVal (const uint8* data,
  19385. int& numBytesUsed) throw();
  19386. /** Based on the first byte of a short midi message, this uses a lookup table
  19387. to return the message length (either 1, 2, or 3 bytes).
  19388. The value passed in must be 0x80 or higher.
  19389. */
  19390. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  19391. /** Returns the name of a midi note number.
  19392. E.g "C", "D#", etc.
  19393. @param noteNumber the midi note number, 0 to 127
  19394. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  19395. they'll be flattened, e.g. "Db"
  19396. @param includeOctaveNumber if true, the octave number will be appended to the string,
  19397. e.g. "C#4"
  19398. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  19399. number that will be used for middle C's octave
  19400. @see getMidiNoteInHertz
  19401. */
  19402. static const String getMidiNoteName (int noteNumber,
  19403. bool useSharps,
  19404. bool includeOctaveNumber,
  19405. int octaveNumForMiddleC) throw();
  19406. /** Returns the frequency of a midi note number.
  19407. @see getMidiNoteName
  19408. */
  19409. static const double getMidiNoteInHertz (int noteNumber) throw();
  19410. /** Returns the standard name of a GM instrument.
  19411. @param midiInstrumentNumber the program number 0 to 127
  19412. @see getProgramChangeNumber
  19413. */
  19414. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  19415. /** Returns the name of a bank of GM instruments.
  19416. @param midiBankNumber the bank, 0 to 15
  19417. */
  19418. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19419. /** Returns the standard name of a channel 10 percussion sound.
  19420. @param midiNoteNumber the key number, 35 to 81
  19421. */
  19422. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19423. /** Returns the name of a controller type number.
  19424. @see getControllerNumber
  19425. */
  19426. static const String getControllerName (int controllerNumber) throw();
  19427. juce_UseDebuggingNewOperator
  19428. private:
  19429. double timeStamp;
  19430. uint8* data;
  19431. int message, size;
  19432. };
  19433. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19434. /********* End of inlined file: juce_MidiMessage.h *********/
  19435. /**
  19436. Holds a sequence of time-stamped midi events.
  19437. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19438. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19439. @see MidiMessage
  19440. */
  19441. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19442. {
  19443. public:
  19444. /** Creates an empty MidiBuffer. */
  19445. MidiBuffer() throw();
  19446. /** Creates a MidiBuffer containing a single midi message. */
  19447. MidiBuffer (const MidiMessage& message) throw();
  19448. /** Creates a copy of another MidiBuffer. */
  19449. MidiBuffer (const MidiBuffer& other) throw();
  19450. /** Makes a copy of another MidiBuffer. */
  19451. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19452. /** Destructor */
  19453. ~MidiBuffer() throw();
  19454. /** Removes all events from the buffer. */
  19455. void clear() throw();
  19456. /** Removes all events between two times from the buffer.
  19457. All events for which (start <= event position < start + numSamples) will
  19458. be removed.
  19459. */
  19460. void clear (const int start,
  19461. const int numSamples) throw();
  19462. /** Returns true if the buffer is empty.
  19463. To actually retrieve the events, use a MidiBuffer::Iterator object
  19464. */
  19465. bool isEmpty() const throw();
  19466. /** Counts the number of events in the buffer.
  19467. This is actually quite a slow operation, as it has to iterate through all
  19468. the events, so you might prefer to call isEmpty() if that's all you need
  19469. to know.
  19470. */
  19471. int getNumEvents() const throw();
  19472. /** Adds an event to the buffer.
  19473. The sample number will be used to determine the position of the event in
  19474. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19475. ignored.
  19476. If an event is added whose sample position is the same as one or more events
  19477. already in the buffer, the new event will be placed after the existing ones.
  19478. To retrieve events, use a MidiBuffer::Iterator object
  19479. */
  19480. void addEvent (const MidiMessage& midiMessage,
  19481. const int sampleNumber) throw();
  19482. /** Adds an event to the buffer from raw midi data.
  19483. The sample number will be used to determine the position of the event in
  19484. the buffer, which is always kept sorted.
  19485. If an event is added whose sample position is the same as one or more events
  19486. already in the buffer, the new event will be placed after the existing ones.
  19487. The event data will be inspected to calculate the number of bytes in length that
  19488. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19489. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19490. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19491. add an event at all.
  19492. To retrieve events, use a MidiBuffer::Iterator object
  19493. */
  19494. void addEvent (const uint8* const rawMidiData,
  19495. const int maxBytesOfMidiData,
  19496. const int sampleNumber) throw();
  19497. /** Adds some events from another buffer to this one.
  19498. @param otherBuffer the buffer containing the events you want to add
  19499. @param startSample the lowest sample number in the source buffer for which
  19500. events should be added. Any source events whose timestamp is
  19501. less than this will be ignored
  19502. @param numSamples the valid range of samples from the source buffer for which
  19503. events should be added - i.e. events in the source buffer whose
  19504. timestamp is greater than or equal to (startSample + numSamples)
  19505. will be ignored. If this value is less than 0, all events after
  19506. startSample will be taken.
  19507. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19508. that are added to this buffer
  19509. */
  19510. void addEvents (const MidiBuffer& otherBuffer,
  19511. const int startSample,
  19512. const int numSamples,
  19513. const int sampleDeltaToAdd) throw();
  19514. /** Returns the sample number of the first event in the buffer.
  19515. If the buffer's empty, this will just return 0.
  19516. */
  19517. int getFirstEventTime() const throw();
  19518. /** Returns the sample number of the last event in the buffer.
  19519. If the buffer's empty, this will just return 0.
  19520. */
  19521. int getLastEventTime() const throw();
  19522. /** Exchanges the contents of this buffer with another one.
  19523. This is a quick operation, because no memory allocating or copying is done, it
  19524. just swaps the internal state of the two buffers.
  19525. */
  19526. void swap (MidiBuffer& other);
  19527. /**
  19528. Used to iterate through the events in a MidiBuffer.
  19529. Note that altering the buffer while an iterator is using it isn't a
  19530. safe operation.
  19531. @see MidiBuffer
  19532. */
  19533. class Iterator
  19534. {
  19535. public:
  19536. /** Creates an Iterator for this MidiBuffer. */
  19537. Iterator (const MidiBuffer& buffer) throw();
  19538. /** Destructor. */
  19539. ~Iterator() throw();
  19540. /** Repositions the iterator so that the next event retrieved will be the first
  19541. one whose sample position is at greater than or equal to the given position.
  19542. */
  19543. void setNextSamplePosition (const int samplePosition) throw();
  19544. /** Retrieves a copy of the next event from the buffer.
  19545. @param result on return, this will be the message (the MidiMessage's timestamp
  19546. is not set)
  19547. @param samplePosition on return, this will be the position of the event
  19548. @returns true if an event was found, or false if the iterator has reached
  19549. the end of the buffer
  19550. */
  19551. bool getNextEvent (MidiMessage& result,
  19552. int& samplePosition) throw();
  19553. /** Retrieves the next event from the buffer.
  19554. @param midiData on return, this pointer will be set to a block of data containing
  19555. the midi message. Note that to make it fast, this is a pointer
  19556. directly into the MidiBuffer's internal data, so is only valid
  19557. temporarily until the MidiBuffer is altered.
  19558. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19559. midi message
  19560. @param samplePosition on return, this will be the position of the event
  19561. @returns true if an event was found, or false if the iterator has reached
  19562. the end of the buffer
  19563. */
  19564. bool getNextEvent (const uint8* &midiData,
  19565. int& numBytesOfMidiData,
  19566. int& samplePosition) throw();
  19567. juce_UseDebuggingNewOperator
  19568. private:
  19569. const MidiBuffer& buffer;
  19570. const uint8* data;
  19571. Iterator (const Iterator&);
  19572. const Iterator& operator= (const Iterator&);
  19573. };
  19574. juce_UseDebuggingNewOperator
  19575. private:
  19576. friend class MidiBuffer::Iterator;
  19577. int bytesUsed;
  19578. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19579. };
  19580. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19581. /********* End of inlined file: juce_MidiBuffer.h *********/
  19582. #endif
  19583. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19584. /********* Start of inlined file: juce_MidiFile.h *********/
  19585. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19586. #define __JUCE_MIDIFILE_JUCEHEADER__
  19587. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19588. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19589. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19590. /**
  19591. A sequence of timestamped midi messages.
  19592. This allows the sequence to be manipulated, and also to be read from and
  19593. written to a standard midi file.
  19594. @see MidiMessage, MidiFile
  19595. */
  19596. class JUCE_API MidiMessageSequence
  19597. {
  19598. public:
  19599. /** Creates an empty midi sequence object. */
  19600. MidiMessageSequence();
  19601. /** Creates a copy of another sequence. */
  19602. MidiMessageSequence (const MidiMessageSequence& other);
  19603. /** Replaces this sequence with another one. */
  19604. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19605. /** Destructor. */
  19606. ~MidiMessageSequence();
  19607. /** Structure used to hold midi events in the sequence.
  19608. These structures act as 'handles' on the events as they are moved about in
  19609. the list, and make it quick to find the matching note-offs for note-on events.
  19610. @see MidiMessageSequence::getEventPointer
  19611. */
  19612. class MidiEventHolder
  19613. {
  19614. public:
  19615. /** Destructor. */
  19616. ~MidiEventHolder();
  19617. /** The message itself, whose timestamp is used to specify the event's time.
  19618. */
  19619. MidiMessage message;
  19620. /** The matching note-off event (if this is a note-on event).
  19621. If this isn't a note-on, this pointer will be null.
  19622. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19623. note-offs up-to-date after events have been moved around in the sequence
  19624. or deleted.
  19625. */
  19626. MidiEventHolder* noteOffObject;
  19627. juce_UseDebuggingNewOperator
  19628. private:
  19629. friend class MidiMessageSequence;
  19630. MidiEventHolder (const MidiMessage& message);
  19631. };
  19632. /** Clears the sequence. */
  19633. void clear();
  19634. /** Returns the number of events in the sequence. */
  19635. int getNumEvents() const;
  19636. /** Returns a pointer to one of the events. */
  19637. MidiEventHolder* getEventPointer (const int index) const;
  19638. /** Returns the time of the note-up that matches the note-on at this index.
  19639. If the event at this index isn't a note-on, it'll just return 0.
  19640. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19641. */
  19642. double getTimeOfMatchingKeyUp (const int index) const;
  19643. /** Returns the index of the note-up that matches the note-on at this index.
  19644. If the event at this index isn't a note-on, it'll just return -1.
  19645. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19646. */
  19647. int getIndexOfMatchingKeyUp (const int index) const;
  19648. /** Returns the index of an event. */
  19649. int getIndexOf (MidiEventHolder* const event) const;
  19650. /** Returns the index of the first event on or after the given timestamp.
  19651. If the time is beyond the end of the sequence, this will return the
  19652. number of events.
  19653. */
  19654. int getNextIndexAtTime (const double timeStamp) const;
  19655. /** Returns the timestamp of the first event in the sequence.
  19656. @see getEndTime
  19657. */
  19658. double getStartTime() const;
  19659. /** Returns the timestamp of the last event in the sequence.
  19660. @see getStartTime
  19661. */
  19662. double getEndTime() const;
  19663. /** Returns the timestamp of the event at a given index.
  19664. If the index is out-of-range, this will return 0.0
  19665. */
  19666. double getEventTime (const int index) const;
  19667. /** Inserts a midi message into the sequence.
  19668. The index at which the new message gets inserted will depend on its timestamp,
  19669. because the sequence is kept sorted.
  19670. Remember to call updateMatchedPairs() after adding note-on events.
  19671. @param newMessage the new message to add (an internal copy will be made)
  19672. @param timeAdjustment an optional value to add to the timestamp of the message
  19673. that will be inserted
  19674. @see updateMatchedPairs
  19675. */
  19676. void addEvent (const MidiMessage& newMessage,
  19677. double timeAdjustment = 0);
  19678. /** Deletes one of the events in the sequence.
  19679. Remember to call updateMatchedPairs() after removing events.
  19680. @param index the index of the event to delete
  19681. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19682. if the event you're removing is a note-on
  19683. */
  19684. void deleteEvent (const int index,
  19685. const bool deleteMatchingNoteUp);
  19686. /** Merges another sequence into this one.
  19687. Remember to call updateMatchedPairs() after using this method.
  19688. @param other the sequence to add from
  19689. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19690. as they are read from the other sequence
  19691. @param firstAllowableDestTime events will not be added if their time is earlier
  19692. than this time. (This is after their time has been adjusted
  19693. by the timeAdjustmentDelta)
  19694. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19695. or greater than this time. (This is after their time has
  19696. been adjusted by the timeAdjustmentDelta)
  19697. */
  19698. void addSequence (const MidiMessageSequence& other,
  19699. double timeAdjustmentDelta,
  19700. double firstAllowableDestTime,
  19701. double endOfAllowableDestTimes);
  19702. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19703. Call this after moving messages about or deleting/adding messages, and it
  19704. will scan the list and make sure all the note-offs in the MidiEventHolder
  19705. structures are pointing at the correct ones.
  19706. */
  19707. void updateMatchedPairs();
  19708. /** Copies all the messages for a particular midi channel to another sequence.
  19709. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19710. @param destSequence the sequence that the chosen events should be copied to
  19711. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19712. channel) will also be copied across.
  19713. @see extractSysExMessages
  19714. */
  19715. void extractMidiChannelMessages (const int channelNumberToExtract,
  19716. MidiMessageSequence& destSequence,
  19717. const bool alsoIncludeMetaEvents) const;
  19718. /** Copies all midi sys-ex messages to another sequence.
  19719. @param destSequence this is the sequence to which any sys-exes in this sequence
  19720. will be added
  19721. @see extractMidiChannelMessages
  19722. */
  19723. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19724. /** Removes any messages in this sequence that have a specific midi channel.
  19725. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19726. */
  19727. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19728. /** Removes any sys-ex messages from this sequence.
  19729. */
  19730. void deleteSysExMessages();
  19731. /** Adds an offset to the timestamps of all events in the sequence.
  19732. @param deltaTime the amount to add to each timestamp.
  19733. */
  19734. void addTimeToMessages (const double deltaTime);
  19735. /** Scans through the sequence to determine the state of any midi controllers at
  19736. a given time.
  19737. This will create a sequence of midi controller changes that can be
  19738. used to set all midi controllers to the state they would be in at the
  19739. specified time within this sequence.
  19740. As well as controllers, it will also recreate the midi program number
  19741. and pitch bend position.
  19742. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19743. for other channels will be ignored.
  19744. @param time the time at which you want to find out the state - there are
  19745. no explicit units for this time measurement, it's the same units
  19746. as used for the timestamps of the messages
  19747. @param resultMessages an array to which midi controller-change messages will be added. This
  19748. will be the minimum number of controller changes to recreate the
  19749. state at the required time.
  19750. */
  19751. void createControllerUpdatesForTime (const int channelNumber,
  19752. const double time,
  19753. OwnedArray<MidiMessage>& resultMessages);
  19754. juce_UseDebuggingNewOperator
  19755. /** @internal */
  19756. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19757. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19758. private:
  19759. friend class MidiComparator;
  19760. friend class MidiFile;
  19761. OwnedArray <MidiEventHolder> list;
  19762. void sort();
  19763. };
  19764. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19765. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19766. /**
  19767. Reads/writes standard midi format files.
  19768. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19769. can then get the individual midi tracks from it using the getTrack() method.
  19770. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19771. to it using the addTrack() method, and then call its writeTo() method to stream
  19772. it out.
  19773. @see MidiMessageSequence
  19774. */
  19775. class JUCE_API MidiFile
  19776. {
  19777. public:
  19778. /** Creates an empty MidiFile object.
  19779. */
  19780. MidiFile() throw();
  19781. /** Destructor. */
  19782. ~MidiFile() throw();
  19783. /** Returns the number of tracks in the file.
  19784. @see getTrack, addTrack
  19785. */
  19786. int getNumTracks() const throw();
  19787. /** Returns a pointer to one of the tracks in the file.
  19788. @returns a pointer to the track, or 0 if the index is out-of-range
  19789. @see getNumTracks, addTrack
  19790. */
  19791. const MidiMessageSequence* getTrack (const int index) const throw();
  19792. /** Adds a midi track to the file.
  19793. This will make its own internal copy of the sequence that is passed-in.
  19794. @see getNumTracks, getTrack
  19795. */
  19796. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19797. /** Removes all midi tracks from the file.
  19798. @see getNumTracks
  19799. */
  19800. void clear() throw();
  19801. /** Returns the raw time format code that will be written to a stream.
  19802. After reading a midi file, this method will return the time-format that
  19803. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19804. or setSmpteTimeFormat() methods.
  19805. If the value returned is positive, it indicates the number of midi ticks
  19806. per quarter-note - see setTicksPerQuarterNote().
  19807. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19808. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19809. */
  19810. short getTimeFormat() const throw();
  19811. /** Sets the time format to use when this file is written to a stream.
  19812. If this is called, the file will be written as bars/beats using the
  19813. specified resolution, rather than SMPTE absolute times, as would be
  19814. used if setSmpteTimeFormat() had been called instead.
  19815. @param ticksPerQuarterNote e.g. 96, 960
  19816. @see setSmpteTimeFormat
  19817. */
  19818. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19819. /** Sets the time format to use when this file is written to a stream.
  19820. If this is called, the file will be written using absolute times, rather
  19821. than bars/beats as would be the case if setTicksPerBeat() had been called
  19822. instead.
  19823. @param framesPerSecond must be 24, 25, 29 or 30
  19824. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19825. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19826. timing, setSmpteTimeFormat (25, 40)
  19827. @see setTicksPerBeat
  19828. */
  19829. void setSmpteTimeFormat (const int framesPerSecond,
  19830. const int subframeResolution) throw();
  19831. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19832. Useful for finding the positions of all the tempo changes in a file.
  19833. @param tempoChangeEvents a list to which all the events will be added
  19834. */
  19835. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19836. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19837. Useful for finding the positions of all the tempo changes in a file.
  19838. @param timeSigEvents a list to which all the events will be added
  19839. */
  19840. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19841. /** Returns the latest timestamp in any of the tracks.
  19842. (Useful for finding the length of the file).
  19843. */
  19844. double getLastTimestamp() const;
  19845. /** Reads a midi file format stream.
  19846. After calling this, you can get the tracks that were read from the file by using the
  19847. getNumTracks() and getTrack() methods.
  19848. The timestamps of the midi events in the tracks will represent their positions in
  19849. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19850. method.
  19851. @returns true if the stream was read successfully
  19852. */
  19853. bool readFrom (InputStream& sourceStream);
  19854. /** Writes the midi tracks as a standard midi file.
  19855. @returns true if the operation succeeded.
  19856. */
  19857. bool writeTo (OutputStream& destStream);
  19858. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19859. This will use the midi time format and tempo/time signature info in the
  19860. tracks to convert all the timestamps to absolute values in seconds.
  19861. */
  19862. void convertTimestampTicksToSeconds();
  19863. juce_UseDebuggingNewOperator
  19864. /** @internal */
  19865. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19866. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19867. private:
  19868. MidiMessageSequence* tracks [128];
  19869. short numTracks, timeFormat;
  19870. MidiFile (const MidiFile&);
  19871. const MidiFile& operator= (const MidiFile&);
  19872. void readNextTrack (const char* data, int size);
  19873. void writeTrack (OutputStream& mainOut, const int trackNum);
  19874. };
  19875. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19876. /********* End of inlined file: juce_MidiFile.h *********/
  19877. #endif
  19878. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19879. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  19880. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19881. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19882. class MidiKeyboardState;
  19883. /**
  19884. Receives events from a MidiKeyboardState object.
  19885. @see MidiKeyboardState
  19886. */
  19887. class JUCE_API MidiKeyboardStateListener
  19888. {
  19889. public:
  19890. MidiKeyboardStateListener() throw() {}
  19891. virtual ~MidiKeyboardStateListener() {}
  19892. /** Called when one of the MidiKeyboardState's keys is pressed.
  19893. This will be called synchronously when the state is either processing a
  19894. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19895. when a note is being played with its MidiKeyboardState::noteOn() method.
  19896. Note that this callback could happen from an audio callback thread, so be
  19897. careful not to block, and avoid any UI activity in the callback.
  19898. */
  19899. virtual void handleNoteOn (MidiKeyboardState* source,
  19900. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19901. /** Called when one of the MidiKeyboardState's keys is released.
  19902. This will be called synchronously when the state is either processing a
  19903. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19904. when a note is being played with its MidiKeyboardState::noteOff() method.
  19905. Note that this callback could happen from an audio callback thread, so be
  19906. careful not to block, and avoid any UI activity in the callback.
  19907. */
  19908. virtual void handleNoteOff (MidiKeyboardState* source,
  19909. int midiChannel, int midiNoteNumber) = 0;
  19910. };
  19911. /**
  19912. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19913. This object can parse a stream of midi events, using them to update its idea
  19914. of which keys are pressed for each individiual midi channel.
  19915. When keys go up or down, it can broadcast these events to listener objects.
  19916. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19917. methods, and midi messages for these events will be merged into the
  19918. midi stream that gets processed by processNextMidiBuffer().
  19919. */
  19920. class JUCE_API MidiKeyboardState
  19921. {
  19922. public:
  19923. MidiKeyboardState();
  19924. ~MidiKeyboardState();
  19925. /** Resets the state of the object.
  19926. All internal data for all the channels is reset, but no events are sent as a
  19927. result.
  19928. If you want to release any keys that are currently down, and to send out note-up
  19929. midi messages for this, use the allNotesOff() method instead.
  19930. */
  19931. void reset();
  19932. /** Returns true if the given midi key is currently held down for the given midi channel.
  19933. The channel number must be between 1 and 16. If you want to see if any notes are
  19934. on for a range of channels, use the isNoteOnForChannels() method.
  19935. */
  19936. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19937. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19938. The channel mask has a bit set for each midi channel you want to test for - bit
  19939. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19940. If a note is on for at least one of the specified channels, this returns true.
  19941. */
  19942. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19943. /** Turns a specified note on.
  19944. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19945. next call to processNextMidiBuffer().
  19946. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19947. gone down.
  19948. */
  19949. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19950. /** Turns a specified note off.
  19951. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  19952. next call to processNextMidiBuffer().
  19953. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19954. gone up.
  19955. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19956. */
  19957. void noteOff (const int midiChannel, const int midiNoteNumber);
  19958. /** This will turn off any currently-down notes for the given midi channel.
  19959. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19960. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19961. and events being added to the midi stream.
  19962. */
  19963. void allNotesOff (const int midiChannel);
  19964. /** Looks at a key-up/down event and uses it to update the state of this object.
  19965. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19966. instead.
  19967. */
  19968. void processNextMidiEvent (const MidiMessage& message);
  19969. /** Scans a midi stream for up/down events and adds its own events to it.
  19970. This will look for any up/down events and use them to update the internal state,
  19971. synchronously making suitable callbacks to the listeners.
  19972. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19973. and noteOff() calls will be added into the buffer.
  19974. Only the section of the buffer whose timestamps are between startSample and
  19975. (startSample + numSamples) will be affected, and any events added will be placed
  19976. between these times.
  19977. If you're going to use this method, you'll need to keep calling it regularly for
  19978. it to work satisfactorily.
  19979. To process a single midi event at a time, use the processNextMidiEvent() method
  19980. instead.
  19981. */
  19982. void processNextMidiBuffer (MidiBuffer& buffer,
  19983. const int startSample,
  19984. const int numSamples,
  19985. const bool injectIndirectEvents);
  19986. /** Registers a listener for callbacks when keys go up or down.
  19987. @see removeListener
  19988. */
  19989. void addListener (MidiKeyboardStateListener* const listener) throw();
  19990. /** Deregisters a listener.
  19991. @see addListener
  19992. */
  19993. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19994. juce_UseDebuggingNewOperator
  19995. private:
  19996. CriticalSection lock;
  19997. uint16 noteStates [128];
  19998. MidiBuffer eventsToAdd;
  19999. VoidArray listeners;
  20000. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  20001. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  20002. MidiKeyboardState (const MidiKeyboardState&);
  20003. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  20004. };
  20005. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  20006. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  20007. #endif
  20008. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  20009. #endif
  20010. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20011. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  20012. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20013. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20014. /********* Start of inlined file: juce_MidiInput.h *********/
  20015. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  20016. #define __JUCE_MIDIINPUT_JUCEHEADER__
  20017. class MidiInput;
  20018. /**
  20019. Receives midi messages from a midi input device.
  20020. This class is overridden to handle incoming midi messages. See the MidiInput
  20021. class for more details.
  20022. @see MidiInput
  20023. */
  20024. class JUCE_API MidiInputCallback
  20025. {
  20026. public:
  20027. /** Destructor. */
  20028. virtual ~MidiInputCallback() {}
  20029. /** Receives an incoming message.
  20030. A MidiInput object will call this method when a midi event arrives. It'll be
  20031. called on a high-priority system thread, so avoid doing anything time-consuming
  20032. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  20033. for queueing incoming messages for use later.
  20034. @param source the MidiInput object that generated the message
  20035. @param message the incoming message. The message's timestamp is set to a value
  20036. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  20037. time when the message arrived.
  20038. */
  20039. virtual void handleIncomingMidiMessage (MidiInput* source,
  20040. const MidiMessage& message) = 0;
  20041. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  20042. If a long sysex message is broken up into multiple packets, this callback is made
  20043. for each packet that arrives until the message is finished, at which point
  20044. the normal handleIncomingMidiMessage() callback will be made with the entire
  20045. message.
  20046. The message passed in will contain the start of a sysex, but won't be finished
  20047. with the terminating 0xf7 byte.
  20048. */
  20049. virtual void handlePartialSysexMessage (MidiInput* source,
  20050. const uint8* messageData,
  20051. const int numBytesSoFar,
  20052. const double timestamp)
  20053. {
  20054. // (this bit is just to avoid compiler warnings about unused variables)
  20055. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  20056. }
  20057. };
  20058. /**
  20059. Represents a midi input device.
  20060. To create one of these, use the static getDevices() method to find out what inputs are
  20061. available, and then use the openDevice() method to try to open one.
  20062. @see MidiOutput
  20063. */
  20064. class JUCE_API MidiInput
  20065. {
  20066. public:
  20067. /** Returns a list of the available midi input devices.
  20068. You can open one of the devices by passing its index into the
  20069. openDevice() method.
  20070. @see getDefaultDeviceIndex, openDevice
  20071. */
  20072. static const StringArray getDevices();
  20073. /** Returns the index of the default midi input device to use.
  20074. This refers to the index in the list returned by getDevices().
  20075. */
  20076. static int getDefaultDeviceIndex();
  20077. /** Tries to open one of the midi input devices.
  20078. This will return a MidiInput object if it manages to open it. You can then
  20079. call start() and stop() on this device, and delete it when no longer needed.
  20080. If the device can't be opened, this will return a null pointer.
  20081. @param deviceIndex the index of a device from the list returned by getDevices()
  20082. @param callback the object that will receive the midi messages from this device.
  20083. @see MidiInputCallback, getDevices
  20084. */
  20085. static MidiInput* openDevice (int deviceIndex,
  20086. MidiInputCallback* callback);
  20087. #if JUCE_LINUX || DOXYGEN
  20088. /** LINUX ONLY - This will try to create a new midi input device.
  20089. This will attempt to create a new midi input device with the specified name,
  20090. for other apps to connect to.
  20091. Returns 0 if a device can't be created.
  20092. @param deviceName the name to use for the new device
  20093. @param callback the object that will receive the midi messages from this device.
  20094. */
  20095. static MidiInput* createNewDevice (const String& deviceName,
  20096. MidiInputCallback* callback);
  20097. #endif
  20098. /** Destructor. */
  20099. virtual ~MidiInput();
  20100. /** Returns the name of this device.
  20101. */
  20102. virtual const String getName() const throw() { return name; }
  20103. /** Allows you to set a custom name for the device, in case you don't like the name
  20104. it was given when created.
  20105. */
  20106. virtual void setName (const String& newName) throw() { name = newName; }
  20107. /** Starts the device running.
  20108. After calling this, the device will start sending midi messages to the
  20109. MidiInputCallback object that was specified when the openDevice() method
  20110. was called.
  20111. @see stop
  20112. */
  20113. virtual void start();
  20114. /** Stops the device running.
  20115. @see start
  20116. */
  20117. virtual void stop();
  20118. juce_UseDebuggingNewOperator
  20119. protected:
  20120. String name;
  20121. void* internal;
  20122. MidiInput (const String& name);
  20123. MidiInput (const MidiInput&);
  20124. };
  20125. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  20126. /********* End of inlined file: juce_MidiInput.h *********/
  20127. /**
  20128. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  20129. processing by a block-based audio callback.
  20130. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  20131. so it can easily use a midi input or keyboard component as its source.
  20132. @see MidiMessage, MidiInput
  20133. */
  20134. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  20135. public MidiInputCallback
  20136. {
  20137. public:
  20138. /** Creates a MidiMessageCollector. */
  20139. MidiMessageCollector();
  20140. /** Destructor. */
  20141. ~MidiMessageCollector();
  20142. /** Clears any messages from the queue.
  20143. You need to call this method before starting to use the collector, so that
  20144. it knows the correct sample rate to use.
  20145. */
  20146. void reset (const double sampleRate);
  20147. /** Takes an incoming real-time message and adds it to the queue.
  20148. The message's timestamp is taken, and it will be ready for retrieval as part
  20149. of the block returned by the next call to removeNextBlockOfMessages().
  20150. This method is fully thread-safe when overlapping calls are made with
  20151. removeNextBlockOfMessages().
  20152. */
  20153. void addMessageToQueue (const MidiMessage& message);
  20154. /** Removes all the pending messages from the queue as a buffer.
  20155. This will also correct the messages' timestamps to make sure they're in
  20156. the range 0 to numSamples - 1.
  20157. This call should be made regularly by something like an audio processing
  20158. callback, because the time that it happens is used in calculating the
  20159. midi event positions.
  20160. This method is fully thread-safe when overlapping calls are made with
  20161. addMessageToQueue().
  20162. */
  20163. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20164. const int numSamples);
  20165. /** @internal */
  20166. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  20167. /** @internal */
  20168. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  20169. /** @internal */
  20170. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  20171. juce_UseDebuggingNewOperator
  20172. private:
  20173. double lastCallbackTime;
  20174. CriticalSection midiCallbackLock;
  20175. MidiBuffer incomingMessages;
  20176. double sampleRate;
  20177. MidiMessageCollector (const MidiMessageCollector&);
  20178. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  20179. };
  20180. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20181. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  20182. #endif
  20183. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  20184. #endif
  20185. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20186. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  20187. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20188. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20189. /**
  20190. A set of routines to convert buffers of 32-bit floating point data to and from
  20191. various integer formats.
  20192. */
  20193. class JUCE_API AudioDataConverters
  20194. {
  20195. public:
  20196. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  20197. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  20198. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  20199. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  20200. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20201. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20202. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20203. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20204. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  20205. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  20206. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  20207. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  20208. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20209. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20210. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20211. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20212. enum DataFormat
  20213. {
  20214. int16LE,
  20215. int16BE,
  20216. int24LE,
  20217. int24BE,
  20218. int32LE,
  20219. int32BE,
  20220. float32LE,
  20221. float32BE,
  20222. };
  20223. static void convertFloatToFormat (const DataFormat destFormat,
  20224. const float* source, void* dest, int numSamples);
  20225. static void convertFormatToFloat (const DataFormat sourceFormat,
  20226. const void* source, float* dest, int numSamples);
  20227. static void interleaveSamples (const float** source, float* dest,
  20228. const int numSamples, const int numChannels);
  20229. static void deinterleaveSamples (const float* source, float** dest,
  20230. const int numSamples, const int numChannels);
  20231. };
  20232. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20233. /********* End of inlined file: juce_AudioDataConverters.h *********/
  20234. #endif
  20235. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20236. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  20237. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20238. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20239. class AudioFormatReader;
  20240. class AudioFormatWriter;
  20241. /**
  20242. A multi-channel buffer of 32-bit floating point audio samples.
  20243. */
  20244. class JUCE_API AudioSampleBuffer
  20245. {
  20246. public:
  20247. /** Creates a buffer with a specified number of channels and samples.
  20248. The contents of the buffer will initially be undefined, so use clear() to
  20249. set all the samples to zero.
  20250. The buffer will allocate its memory internally, and this will be released
  20251. when the buffer is deleted.
  20252. */
  20253. AudioSampleBuffer (const int numChannels,
  20254. const int numSamples) throw();
  20255. /** Creates a buffer using a pre-allocated block of memory.
  20256. Note that if the buffer is resized or its number of channels is changed, it
  20257. will re-allocate memory internally and copy the existing data to this new area,
  20258. so it will then stop directly addressing this memory.
  20259. @param dataToReferTo a pre-allocated array containing pointers to the data
  20260. for each channel that should be used by this buffer. The
  20261. buffer will only refer to this memory, it won't try to delete
  20262. it when the buffer is deleted or resized.
  20263. @param numChannels the number of channels to use - this must correspond to the
  20264. number of elements in the array passed in
  20265. @param numSamples the number of samples to use - this must correspond to the
  20266. size of the arrays passed in
  20267. */
  20268. AudioSampleBuffer (float** dataToReferTo,
  20269. const int numChannels,
  20270. const int numSamples) throw();
  20271. /** Copies another buffer.
  20272. This buffer will make its own copy of the other's data, unless the buffer was created
  20273. using an external data buffer, in which case boths buffers will just point to the same
  20274. shared block of data.
  20275. */
  20276. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  20277. /** Copies another buffer onto this one.
  20278. This buffer's size will be changed to that of the other buffer.
  20279. */
  20280. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  20281. /** Destructor.
  20282. This will free any memory allocated by the buffer.
  20283. */
  20284. virtual ~AudioSampleBuffer() throw();
  20285. /** Returns the number of channels of audio data that this buffer contains.
  20286. @see getSampleData
  20287. */
  20288. int getNumChannels() const throw() { return numChannels; }
  20289. /** Returns the number of samples allocated in each of the buffer's channels.
  20290. @see getSampleData
  20291. */
  20292. int getNumSamples() const throw() { return size; }
  20293. /** Returns a pointer one of the buffer's channels.
  20294. For speed, this doesn't check whether the channel number is out of range,
  20295. so be careful when using it!
  20296. */
  20297. float* getSampleData (const int channelNumber) const throw()
  20298. {
  20299. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20300. return channels [channelNumber];
  20301. }
  20302. /** Returns a pointer to a sample in one of the buffer's channels.
  20303. For speed, this doesn't check whether the channel and sample number
  20304. are out-of-range, so be careful when using it!
  20305. */
  20306. float* getSampleData (const int channelNumber,
  20307. const int sampleOffset) const throw()
  20308. {
  20309. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20310. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  20311. return channels [channelNumber] + sampleOffset;
  20312. }
  20313. /** Returns an array of pointers to the channels in the buffer.
  20314. Don't modify any of the pointers that are returned, and bear in mind that
  20315. these will become invalid if the buffer is resized.
  20316. */
  20317. float** getArrayOfChannels() const throw() { return channels; }
  20318. /** Chages the buffer's size or number of channels.
  20319. This can expand or contract the buffer's length, and add or remove channels.
  20320. If keepExistingContent is true, it will try to preserve as much of the
  20321. old data as it can in the new buffer.
  20322. If clearExtraSpace is true, then any extra channels or space that is
  20323. allocated will be also be cleared. If false, then this space is left
  20324. uninitialised.
  20325. If avoidReallocating is true, then changing the buffer's size won't reduce the
  20326. amount of memory that is currently allocated (but it will still increase it if
  20327. the new size is bigger than the amount it currently has). If this is false, then
  20328. a new allocation will be done so that the buffer uses takes up the minimum amount
  20329. of memory that it needs.
  20330. */
  20331. void setSize (const int newNumChannels,
  20332. const int newNumSamples,
  20333. const bool keepExistingContent = false,
  20334. const bool clearExtraSpace = false,
  20335. const bool avoidReallocating = false) throw();
  20336. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  20337. There's also a constructor that lets you specify arrays like this, but this
  20338. lets you change the channels dynamically.
  20339. Note that if the buffer is resized or its number of channels is changed, it
  20340. will re-allocate memory internally and copy the existing data to this new area,
  20341. so it will then stop directly addressing this memory.
  20342. @param dataToReferTo a pre-allocated array containing pointers to the data
  20343. for each channel that should be used by this buffer. The
  20344. buffer will only refer to this memory, it won't try to delete
  20345. it when the buffer is deleted or resized.
  20346. @param numChannels the number of channels to use - this must correspond to the
  20347. number of elements in the array passed in
  20348. @param numSamples the number of samples to use - this must correspond to the
  20349. size of the arrays passed in
  20350. */
  20351. void setDataToReferTo (float** dataToReferTo,
  20352. const int numChannels,
  20353. const int numSamples) throw();
  20354. /** Clears all the samples in all channels. */
  20355. void clear() throw();
  20356. /** Clears a specified region of all the channels.
  20357. For speed, this doesn't check whether the channel and sample number
  20358. are in-range, so be careful!
  20359. */
  20360. void clear (const int startSample,
  20361. const int numSamples) throw();
  20362. /** Clears a specified region of just one channel.
  20363. For speed, this doesn't check whether the channel and sample number
  20364. are in-range, so be careful!
  20365. */
  20366. void clear (const int channel,
  20367. const int startSample,
  20368. const int numSamples) throw();
  20369. /** Applies a gain multiple to a region of one channel.
  20370. For speed, this doesn't check whether the channel and sample number
  20371. are in-range, so be careful!
  20372. */
  20373. void applyGain (const int channel,
  20374. const int startSample,
  20375. int numSamples,
  20376. const float gain) throw();
  20377. /** Applies a gain multiple to a region of all the channels.
  20378. For speed, this doesn't check whether the sample numbers
  20379. are in-range, so be careful!
  20380. */
  20381. void applyGain (const int startSample,
  20382. const int numSamples,
  20383. const float gain) throw();
  20384. /** Applies a range of gains to a region of a channel.
  20385. The gain that is applied to each sample will vary from
  20386. startGain on the first sample to endGain on the last Sample,
  20387. so it can be used to do basic fades.
  20388. For speed, this doesn't check whether the sample numbers
  20389. are in-range, so be careful!
  20390. */
  20391. void applyGainRamp (const int channel,
  20392. const int startSample,
  20393. int numSamples,
  20394. float startGain,
  20395. float endGain) throw();
  20396. /** Adds samples from another buffer to this one.
  20397. @param destChannel the channel within this buffer to add the samples to
  20398. @param destStartSample the start sample within this buffer's channel
  20399. @param source the source buffer to add from
  20400. @param sourceChannel the channel within the source buffer to read from
  20401. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20402. @param numSamples the number of samples to process
  20403. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20404. added to this buffer's samples
  20405. @see copyFrom
  20406. */
  20407. void addFrom (const int destChannel,
  20408. const int destStartSample,
  20409. const AudioSampleBuffer& source,
  20410. const int sourceChannel,
  20411. const int sourceStartSample,
  20412. int numSamples,
  20413. const float gainToApplyToSource = 1.0f) throw();
  20414. /** Adds samples from an array of floats to one of the channels.
  20415. @param destChannel the channel within this buffer to add the samples to
  20416. @param destStartSample the start sample within this buffer's channel
  20417. @param source the source data to use
  20418. @param numSamples the number of samples to process
  20419. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20420. added to this buffer's samples
  20421. @see copyFrom
  20422. */
  20423. void addFrom (const int destChannel,
  20424. const int destStartSample,
  20425. const float* source,
  20426. int numSamples,
  20427. const float gainToApplyToSource = 1.0f) throw();
  20428. /** Adds samples from an array of floats, applying a gain ramp to them.
  20429. @param destChannel the channel within this buffer to add the samples to
  20430. @param destStartSample the start sample within this buffer's channel
  20431. @param source the source data to use
  20432. @param numSamples the number of samples to process
  20433. @param startGain the gain to apply to the first sample (this is multiplied with
  20434. the source samples before they are added to this buffer)
  20435. @param endGain the gain to apply to the final sample. The gain is linearly
  20436. interpolated between the first and last samples.
  20437. */
  20438. void addFromWithRamp (const int destChannel,
  20439. const int destStartSample,
  20440. const float* source,
  20441. int numSamples,
  20442. float startGain,
  20443. float endGain) throw();
  20444. /** Copies samples from another buffer to this one.
  20445. @param destChannel the channel within this buffer to copy the samples to
  20446. @param destStartSample the start sample within this buffer's channel
  20447. @param source the source buffer to read from
  20448. @param sourceChannel the channel within the source buffer to read from
  20449. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20450. @param numSamples the number of samples to process
  20451. @see addFrom
  20452. */
  20453. void copyFrom (const int destChannel,
  20454. const int destStartSample,
  20455. const AudioSampleBuffer& source,
  20456. const int sourceChannel,
  20457. const int sourceStartSample,
  20458. int numSamples) throw();
  20459. /** Copies samples from an array of floats into one of the channels.
  20460. @param destChannel the channel within this buffer to copy the samples to
  20461. @param destStartSample the start sample within this buffer's channel
  20462. @param source the source buffer to read from
  20463. @param numSamples the number of samples to process
  20464. @see addFrom
  20465. */
  20466. void copyFrom (const int destChannel,
  20467. const int destStartSample,
  20468. const float* source,
  20469. int numSamples) throw();
  20470. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  20471. @param destChannel the channel within this buffer to copy the samples to
  20472. @param destStartSample the start sample within this buffer's channel
  20473. @param source the source buffer to read from
  20474. @param numSamples the number of samples to process
  20475. @param gain the gain to apply
  20476. @see addFrom
  20477. */
  20478. void copyFrom (const int destChannel,
  20479. const int destStartSample,
  20480. const float* source,
  20481. int numSamples,
  20482. const float gain) throw();
  20483. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  20484. @param destChannel the channel within this buffer to copy the samples to
  20485. @param destStartSample the start sample within this buffer's channel
  20486. @param source the source buffer to read from
  20487. @param numSamples the number of samples to process
  20488. @param startGain the gain to apply to the first sample (this is multiplied with
  20489. the source samples before they are copied to this buffer)
  20490. @param endGain the gain to apply to the final sample. The gain is linearly
  20491. interpolated between the first and last samples.
  20492. @see addFrom
  20493. */
  20494. void copyFromWithRamp (const int destChannel,
  20495. const int destStartSample,
  20496. const float* source,
  20497. int numSamples,
  20498. float startGain,
  20499. float endGain) throw();
  20500. /** Finds the highest and lowest sample values in a given range.
  20501. @param channel the channel to read from
  20502. @param startSample the start sample within the channel
  20503. @param numSamples the number of samples to check
  20504. @param minVal on return, the lowest value that was found
  20505. @param maxVal on return, the highest value that was found
  20506. */
  20507. void findMinMax (const int channel,
  20508. const int startSample,
  20509. int numSamples,
  20510. float& minVal,
  20511. float& maxVal) const throw();
  20512. /** Finds the highest absolute sample value within a region of a channel.
  20513. */
  20514. float getMagnitude (const int channel,
  20515. const int startSample,
  20516. const int numSamples) const throw();
  20517. /** Finds the highest absolute sample value within a region on all channels.
  20518. */
  20519. float getMagnitude (const int startSample,
  20520. const int numSamples) const throw();
  20521. /** Returns the root mean squared level for a region of a channel.
  20522. */
  20523. float getRMSLevel (const int channel,
  20524. const int startSample,
  20525. const int numSamples) const throw();
  20526. /** Fills a section of the buffer using an AudioReader as its source.
  20527. This will convert the reader's fixed- or floating-point data to
  20528. the buffer's floating-point format, and will try to intelligently
  20529. cope with mismatches between the number of channels in the reader
  20530. and the buffer.
  20531. @see writeToAudioWriter
  20532. */
  20533. void readFromAudioReader (AudioFormatReader* reader,
  20534. const int startSample,
  20535. const int numSamples,
  20536. const int readerStartSample,
  20537. const bool useReaderLeftChan,
  20538. const bool useReaderRightChan) throw();
  20539. /** Writes a section of this buffer to an audio writer.
  20540. This saves you having to mess about with channels or floating/fixed
  20541. point conversion.
  20542. @see readFromAudioReader
  20543. */
  20544. void writeToAudioWriter (AudioFormatWriter* writer,
  20545. const int startSample,
  20546. const int numSamples) const throw();
  20547. juce_UseDebuggingNewOperator
  20548. private:
  20549. int numChannels, size, allocatedBytes;
  20550. float** channels;
  20551. float* allocatedData;
  20552. float* preallocatedChannelSpace [32];
  20553. };
  20554. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20555. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20556. #endif
  20557. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20558. /********* Start of inlined file: juce_IIRFilter.h *********/
  20559. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20560. #define __JUCE_IIRFILTER_JUCEHEADER__
  20561. /**
  20562. An IIR filter that can perform low, high, or band-pass filtering on an
  20563. audio signal.
  20564. @see IIRFilterAudioSource
  20565. */
  20566. class JUCE_API IIRFilter
  20567. {
  20568. public:
  20569. /** Creates a filter.
  20570. Initially the filter is inactive, so will have no effect on samples that
  20571. you process with it. Use the appropriate method to turn it into the type
  20572. of filter needed.
  20573. */
  20574. IIRFilter() throw();
  20575. /** Creates a copy of another filter. */
  20576. IIRFilter (const IIRFilter& other) throw();
  20577. /** Destructor. */
  20578. ~IIRFilter() throw();
  20579. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20580. Note that this clears the processing state, but the type of filter and
  20581. its coefficients aren't changed. To put a filter into an inactive state, use
  20582. the makeInactive() method.
  20583. */
  20584. void reset() throw();
  20585. /** Performs the filter operation on the given set of samples.
  20586. */
  20587. void processSamples (float* const samples,
  20588. const int numSamples) throw();
  20589. /** Processes a single sample, without any locking or checking.
  20590. Use this if you need fast processing of a single value, but be aware that
  20591. this isn't thread-safe in the way that processSamples() is.
  20592. */
  20593. float processSingleSampleRaw (const float sample) throw();
  20594. /** Sets the filter up to act as a low-pass filter.
  20595. */
  20596. void makeLowPass (const double sampleRate,
  20597. const double frequency) throw();
  20598. /** Sets the filter up to act as a high-pass filter.
  20599. */
  20600. void makeHighPass (const double sampleRate,
  20601. const double frequency) throw();
  20602. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20603. The gain is a scale factor that the low frequencies are multiplied by, so values
  20604. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20605. attenuate them.
  20606. */
  20607. void makeLowShelf (const double sampleRate,
  20608. const double cutOffFrequency,
  20609. const double Q,
  20610. const float gainFactor) throw();
  20611. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20612. The gain is a scale factor that the high frequencies are multiplied by, so values
  20613. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20614. attenuate them.
  20615. */
  20616. void makeHighShelf (const double sampleRate,
  20617. const double cutOffFrequency,
  20618. const double Q,
  20619. const float gainFactor) throw();
  20620. /** Sets the filter up to act as a band pass filter centred around a
  20621. frequency, with a variable Q and gain.
  20622. The gain is a scale factor that the centre frequencies are multiplied by, so
  20623. values greater than 1.0 will boost the centre frequencies, values less than
  20624. 1.0 will attenuate them.
  20625. */
  20626. void makeBandPass (const double sampleRate,
  20627. const double centreFrequency,
  20628. const double Q,
  20629. const float gainFactor) throw();
  20630. /** Clears the filter's coefficients so that it becomes inactive.
  20631. */
  20632. void makeInactive() throw();
  20633. /** Makes this filter duplicate the set-up of another one.
  20634. */
  20635. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20636. juce_UseDebuggingNewOperator
  20637. protected:
  20638. CriticalSection processLock;
  20639. void setCoefficients (double c1, double c2, double c3,
  20640. double c4, double c5, double c6) throw();
  20641. bool active;
  20642. float coefficients[6];
  20643. float x1, x2, y1, y2;
  20644. // (use the copyCoefficientsFrom() method instead of this operator)
  20645. const IIRFilter& operator= (const IIRFilter&);
  20646. };
  20647. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20648. /********* End of inlined file: juce_IIRFilter.h *********/
  20649. #endif
  20650. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20651. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20652. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20653. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20654. /**
  20655. A subclass of AudioPlayHead can supply information about the position and
  20656. status of a moving play head during audio playback.
  20657. One of these can be supplied to an AudioProcessor object so that it can find
  20658. out about the position of the audio that it is rendering.
  20659. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20660. */
  20661. class JUCE_API AudioPlayHead
  20662. {
  20663. protected:
  20664. AudioPlayHead() {}
  20665. public:
  20666. virtual ~AudioPlayHead() {}
  20667. /** Frame rate types. */
  20668. enum FrameRateType
  20669. {
  20670. fps24 = 0,
  20671. fps25 = 1,
  20672. fps2997 = 2,
  20673. fps30 = 3,
  20674. fps2997drop = 4,
  20675. fps30drop = 5,
  20676. fpsUnknown = 99
  20677. };
  20678. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20679. */
  20680. struct CurrentPositionInfo
  20681. {
  20682. /** The tempo in BPM */
  20683. double bpm;
  20684. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20685. int timeSigNumerator;
  20686. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20687. int timeSigDenominator;
  20688. /** The current play position, in seconds from the start of the edit. */
  20689. double timeInSeconds;
  20690. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20691. double editOriginTime;
  20692. /** The current play position in pulses-per-quarter-note.
  20693. This is the number of quarter notes since the edit start.
  20694. */
  20695. double ppqPosition;
  20696. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20697. This is the number of quarter notes from the start of the edit to the
  20698. start of the current bar.
  20699. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20700. it's not available, the value will be 0.
  20701. */
  20702. double ppqPositionOfLastBarStart;
  20703. /** The video frame rate, if applicable. */
  20704. FrameRateType frameRate;
  20705. /** True if the transport is currently playing. */
  20706. bool isPlaying;
  20707. /** True if the transport is currently recording.
  20708. (When isRecording is true, then isPlaying will also be true).
  20709. */
  20710. bool isRecording;
  20711. };
  20712. /** Fills-in the given structure with details about the transport's
  20713. position at the start of the current processing block.
  20714. */
  20715. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20716. };
  20717. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20718. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20719. #endif
  20720. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20721. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20722. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20723. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20724. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20725. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20726. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20727. class AudioProcessor;
  20728. /**
  20729. Base class for the component that acts as the GUI for an AudioProcessor.
  20730. Derive your editor component from this class, and create an instance of it
  20731. by overriding the AudioProcessor::createEditor() method.
  20732. @see AudioProcessor, GenericAudioProcessorEditor
  20733. */
  20734. class JUCE_API AudioProcessorEditor : public Component
  20735. {
  20736. protected:
  20737. /** Creates an editor for the specified processor.
  20738. */
  20739. AudioProcessorEditor (AudioProcessor* const owner);
  20740. public:
  20741. /** Destructor. */
  20742. ~AudioProcessorEditor();
  20743. /** Returns a pointer to the processor that this editor represents. */
  20744. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20745. private:
  20746. AudioProcessor* const owner;
  20747. };
  20748. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20749. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20750. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20751. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20752. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20753. class AudioProcessor;
  20754. /**
  20755. Base class for listeners that want to know about changes to an AudioProcessor.
  20756. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20757. @see AudioProcessor
  20758. */
  20759. class JUCE_API AudioProcessorListener
  20760. {
  20761. public:
  20762. /** Destructor. */
  20763. virtual ~AudioProcessorListener() {}
  20764. /** Receives a callback when a parameter is changed.
  20765. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20766. many audio processors will change their parameter during their audio callback.
  20767. This means that not only has your handler code got to be completely thread-safe,
  20768. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20769. this event on your message thread, use this callback to trigger an AsyncUpdater
  20770. or ChangeBroadcaster which you can respond to on the message thread.
  20771. */
  20772. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20773. int parameterIndex,
  20774. float newValue) = 0;
  20775. /** Called to indicate that something else in the plugin has changed, like its
  20776. program, number of parameters, etc.
  20777. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20778. call it during their audio callback. This means that not only has your handler code
  20779. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20780. blocking. If you need to handle this event on your message thread, use this callback
  20781. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20782. message thread.
  20783. */
  20784. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20785. /** Indicates that a parameter change gesture has started.
  20786. E.g. if the user is dragging a slider, this would be called when they first
  20787. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20788. called when they release it.
  20789. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20790. call it during their audio callback. This means that not only has your handler code
  20791. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20792. blocking. If you need to handle this event on your message thread, use this callback
  20793. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20794. message thread.
  20795. @see audioProcessorParameterChangeGestureEnd
  20796. */
  20797. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20798. int parameterIndex);
  20799. /** Indicates that a parameter change gesture has finished.
  20800. E.g. if the user is dragging a slider, this would be called when they release
  20801. the mouse button.
  20802. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20803. call it during their audio callback. This means that not only has your handler code
  20804. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20805. blocking. If you need to handle this event on your message thread, use this callback
  20806. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20807. message thread.
  20808. @see audioPluginParameterChangeGestureStart
  20809. */
  20810. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20811. int parameterIndex);
  20812. };
  20813. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20814. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20815. /**
  20816. Base class for audio processing filters or plugins.
  20817. This is intended to act as a base class of audio filter that is general enough to
  20818. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20819. It is also used by the plugin hosting code as the wrapper around an instance
  20820. of a loaded plugin.
  20821. Derive your filter class from this base class, and if you're building a plugin,
  20822. you should implement a global function called createPluginFilter() which creates
  20823. and returns a new instance of your subclass.
  20824. */
  20825. class JUCE_API AudioProcessor
  20826. {
  20827. protected:
  20828. /** Constructor.
  20829. You can also do your initialisation tasks in the initialiseFilterInfo()
  20830. call, which will be made after this object has been created.
  20831. */
  20832. AudioProcessor();
  20833. public:
  20834. /** Destructor. */
  20835. virtual ~AudioProcessor();
  20836. /** Returns the name of this processor.
  20837. */
  20838. virtual const String getName() const = 0;
  20839. /** Called before playback starts, to let the filter prepare itself.
  20840. The sample rate is the target sample rate, and will remain constant until
  20841. playback stops.
  20842. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20843. samples that will be processed for each callback, but isn't any kind
  20844. of guarantee. The actual block sizes that the host uses may be different
  20845. each time the callback happens, and may be more or less than this value.
  20846. */
  20847. virtual void prepareToPlay (double sampleRate,
  20848. int estimatedSamplesPerBlock) = 0;
  20849. /** Called after playback has stopped, to let the filter free up any resources it
  20850. no longer needs.
  20851. */
  20852. virtual void releaseResources() = 0;
  20853. /** Renders the next block.
  20854. When this method is called, the buffer contains a number of channels which is
  20855. at least as great as the maximum number of input and output channels that
  20856. this filter is using. It will be filled with the filter's input data and
  20857. should be replaced with the filter's output.
  20858. So for example if your filter has 2 input channels and 4 output channels, then
  20859. the buffer will contain 4 channels, the first two being filled with the
  20860. input data. Your filter should read these, do its processing, and replace
  20861. the contents of all 4 channels with its output.
  20862. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20863. all filled with data, and your filter should overwrite the first 2 of these
  20864. with its output. But be VERY careful not to write anything to the last 3
  20865. channels, as these might be mapped to memory that the host assumes is read-only!
  20866. Note that if you have more outputs than inputs, then only those channels that
  20867. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20868. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20869. but the last two channels may contain garbage, so you should be careful not to
  20870. let this pass through without being overwritten or cleared.
  20871. Also note that the buffer may have more channels than are strictly necessary,
  20872. but your should only read/write from the ones that your filter is supposed to
  20873. be using.
  20874. The number of samples in these buffers is NOT guaranteed to be the same for every
  20875. callback, and may be more or less than the estimated value given to prepareToPlay().
  20876. Your code must be able to cope with variable-sized blocks, or you're going to get
  20877. clicks and crashes!
  20878. If the filter is receiving a midi input, then the midiMessages array will be filled
  20879. with the midi messages for this block. Each message's timestamp will indicate the
  20880. message's time, as a number of samples from the start of the block.
  20881. Any messages left in the midi buffer when this method has finished are assumed to
  20882. be the filter's midi output. This means that your filter should be careful to
  20883. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20884. Be very careful about what you do in this callback - it's going to be called by
  20885. the audio thread, so any kind of interaction with the UI is absolutely
  20886. out of the question. If you change a parameter in here and need to tell your UI to
  20887. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20888. the UI components register as listeners, and then call sendChangeMessage() inside the
  20889. processBlock() method to send out an asynchronous message. You could also use
  20890. the AsyncUpdater class in a similar way.
  20891. */
  20892. virtual void processBlock (AudioSampleBuffer& buffer,
  20893. MidiBuffer& midiMessages) = 0;
  20894. /** Returns the current AudioPlayHead object that should be used to find
  20895. out the state and position of the playhead.
  20896. You can call this from your processBlock() method, and use the AudioPlayHead
  20897. object to get the details about the time of the start of the block currently
  20898. being processed.
  20899. If the host hasn't supplied a playhead object, this will return 0.
  20900. */
  20901. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20902. /** Returns the current sample rate.
  20903. This can be called from your processBlock() method - it's not guaranteed
  20904. to be valid at any other time, and may return 0 if it's unknown.
  20905. */
  20906. double getSampleRate() const throw() { return sampleRate; }
  20907. /** Returns the current typical block size that is being used.
  20908. This can be called from your processBlock() method - it's not guaranteed
  20909. to be valid at any other time.
  20910. Remember it's not the ONLY block size that may be used when calling
  20911. processBlock, it's just the normal one. The actual block sizes used may be
  20912. larger or smaller than this, and will vary between successive calls.
  20913. */
  20914. int getBlockSize() const throw() { return blockSize; }
  20915. /** Returns the number of input channels that the host will be sending the filter.
  20916. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20917. number of channels that your filter would prefer to have, and this method lets
  20918. you know how many the host is actually using.
  20919. Note that this method is only valid during or after the prepareToPlay()
  20920. method call. Until that point, the number of channels will be unknown.
  20921. */
  20922. int getNumInputChannels() const throw() { return numInputChannels; }
  20923. /** Returns the number of output channels that the host will be sending the filter.
  20924. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20925. number of channels that your filter would prefer to have, and this method lets
  20926. you know how many the host is actually using.
  20927. Note that this method is only valid during or after the prepareToPlay()
  20928. method call. Until that point, the number of channels will be unknown.
  20929. */
  20930. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20931. /** Returns the name of one of the input channels, as returned by the host.
  20932. The host might not supply very useful names for channels, and this might be
  20933. something like "1", "2", "left", "right", etc.
  20934. */
  20935. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20936. /** Returns the name of one of the output channels, as returned by the host.
  20937. The host might not supply very useful names for channels, and this might be
  20938. something like "1", "2", "left", "right", etc.
  20939. */
  20940. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20941. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20942. virtual bool isInputChannelStereoPair (int index) const = 0;
  20943. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20944. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20945. /** This returns the number of samples delay that the filter imposes on the audio
  20946. passing through it.
  20947. The host will call this to find the latency - the filter itself should set this value
  20948. by calling setLatencySamples() as soon as it can during its initialisation.
  20949. */
  20950. int getLatencySamples() const throw() { return latencySamples; }
  20951. /** The filter should call this to set the number of samples delay that it introduces.
  20952. The filter should call this as soon as it can during initialisation, and can call it
  20953. later if the value changes.
  20954. */
  20955. void setLatencySamples (const int newLatency);
  20956. /** Returns true if the processor wants midi messages. */
  20957. virtual bool acceptsMidi() const = 0;
  20958. /** Returns true if the processor produces midi messages. */
  20959. virtual bool producesMidi() const = 0;
  20960. /** This returns a critical section that will automatically be locked while the host
  20961. is calling the processBlock() method.
  20962. Use it from your UI or other threads to lock access to variables that are used
  20963. by the process callback, but obviously be careful not to keep it locked for
  20964. too long, because that could cause stuttering playback. If you need to do something
  20965. that'll take a long time and need the processing to stop while it happens, use the
  20966. suspendProcessing() method instead.
  20967. @see suspendProcessing
  20968. */
  20969. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20970. /** Enables and disables the processing callback.
  20971. If you need to do something time-consuming on a thread and would like to make sure
  20972. the audio processing callback doesn't happen until you've finished, use this
  20973. to disable the callback and re-enable it again afterwards.
  20974. E.g.
  20975. @code
  20976. void loadNewPatch()
  20977. {
  20978. suspendProcessing (true);
  20979. ..do something that takes ages..
  20980. suspendProcessing (false);
  20981. }
  20982. @endcode
  20983. If the host tries to make an audio callback while processing is suspended, the
  20984. filter will return an empty buffer, but won't block the audio thread like it would
  20985. do if you use the getCallbackLock() critical section to synchronise access.
  20986. If you're going to use this, your processBlock() method must call isSuspended() and
  20987. check whether it's suspended or not. If it is, then it should skip doing any real
  20988. processing, either emitting silence or passing the input through unchanged.
  20989. @see getCallbackLock
  20990. */
  20991. void suspendProcessing (const bool shouldBeSuspended);
  20992. /** Returns true if processing is currently suspended.
  20993. @see suspendProcessing
  20994. */
  20995. bool isSuspended() const throw() { return suspended; }
  20996. /** A plugin can override this to be told when it should reset any playing voices.
  20997. The default implementation does nothing, but a host may call this to tell the
  20998. plugin that it should stop any tails or sounds that have been left running.
  20999. */
  21000. virtual void reset();
  21001. /** Returns true if the processor is being run in an offline mode for rendering.
  21002. If the processor is being run live on realtime signals, this returns false.
  21003. If the mode is unknown, this will assume it's realtime and return false.
  21004. This value may be unreliable until the prepareToPlay() method has been called,
  21005. and could change each time prepareToPlay() is called.
  21006. @see setNonRealtime()
  21007. */
  21008. bool isNonRealtime() const throw() { return nonRealtime; }
  21009. /** Called by the host to tell this processor whether it's being used in a non-realime
  21010. capacity for offline rendering or bouncing.
  21011. Whatever value is passed-in will be
  21012. */
  21013. void setNonRealtime (const bool isNonRealtime) throw();
  21014. /** Creates the filter's UI.
  21015. This can return 0 if you want a UI-less filter, in which case the host may create
  21016. a generic UI that lets the user twiddle the parameters directly.
  21017. If you do want to pass back a component, the component should be created and set to
  21018. the correct size before returning it.
  21019. Remember not to do anything silly like allowing your filter to keep a pointer to
  21020. the component that gets created - it could be deleted later without any warning, which
  21021. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  21022. The correct way to handle the connection between an editor component and its
  21023. filter is to use something like a ChangeBroadcaster so that the editor can
  21024. register itself as a listener, and be told when a change occurs. This lets them
  21025. safely unregister themselves when they are deleted.
  21026. Here are a few things to bear in mind when writing an editor:
  21027. - Initially there won't be an editor, until the user opens one, or they might
  21028. not open one at all. Your filter mustn't rely on it being there.
  21029. - An editor object may be deleted and a replacement one created again at any time.
  21030. - It's safe to assume that an editor will be deleted before its filter.
  21031. */
  21032. virtual AudioProcessorEditor* createEditor() = 0;
  21033. /** Returns the active editor, if there is one.
  21034. Bear in mind this can return 0, even if an editor has previously been
  21035. opened.
  21036. */
  21037. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  21038. /** Returns the active editor, or if there isn't one, it will create one.
  21039. This may call createEditor() internally to create the component.
  21040. */
  21041. AudioProcessorEditor* createEditorIfNeeded();
  21042. /** This must return the correct value immediately after the object has been
  21043. created, and mustn't change the number of parameters later.
  21044. */
  21045. virtual int getNumParameters() = 0;
  21046. /** Returns the name of a particular parameter. */
  21047. virtual const String getParameterName (int parameterIndex) = 0;
  21048. /** Called by the host to find out the value of one of the filter's parameters.
  21049. The host will expect the value returned to be between 0 and 1.0.
  21050. This could be called quite frequently, so try to make your code efficient.
  21051. It's also likely to be called by non-UI threads, so the code in here should
  21052. be thread-aware.
  21053. */
  21054. virtual float getParameter (int parameterIndex) = 0;
  21055. /** Returns the value of a parameter as a text string. */
  21056. virtual const String getParameterText (int parameterIndex) = 0;
  21057. /** The host will call this method to change the value of one of the filter's parameters.
  21058. The host may call this at any time, including during the audio processing
  21059. callback, so the filter has to process this very fast and avoid blocking.
  21060. If you want to set the value of a parameter internally, e.g. from your
  21061. editor component, then don't call this directly - instead, use the
  21062. setParameterNotifyingHost() method, which will also send a message to
  21063. the host telling it about the change. If the message isn't sent, the host
  21064. won't be able to automate your parameters properly.
  21065. The value passed will be between 0 and 1.0.
  21066. */
  21067. virtual void setParameter (int parameterIndex,
  21068. float newValue) = 0;
  21069. /** Your filter can call this when it needs to change one of its parameters.
  21070. This could happen when the editor or some other internal operation changes
  21071. a parameter. This method will call the setParameter() method to change the
  21072. value, and will then send a message to the host telling it about the change.
  21073. Note that to make sure the host correctly handles automation, you should call
  21074. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  21075. tell the host when the user has started and stopped changing the parameter.
  21076. */
  21077. void setParameterNotifyingHost (int parameterIndex,
  21078. float newValue);
  21079. /** Returns true if the host can automate this parameter.
  21080. By default, this returns true for all parameters.
  21081. */
  21082. virtual bool isParameterAutomatable (int parameterIndex) const;
  21083. /** Should return true if this parameter is a "meta" parameter.
  21084. A meta-parameter is a parameter that changes other params. It is used
  21085. by some hosts (e.g. AudioUnit hosts).
  21086. By default this returns false.
  21087. */
  21088. virtual bool isMetaParameter (int parameterIndex) const;
  21089. /** Sends a signal to the host to tell it that the user is about to start changing this
  21090. parameter.
  21091. This allows the host to know when a parameter is actively being held by the user, and
  21092. it may use this information to help it record automation.
  21093. If you call this, it must be matched by a later call to endParameterChangeGesture().
  21094. */
  21095. void beginParameterChangeGesture (int parameterIndex);
  21096. /** Tells the host that the user has finished changing this parameter.
  21097. This allows the host to know when a parameter is actively being held by the user, and
  21098. it may use this information to help it record automation.
  21099. A call to this method must follow a call to beginParameterChangeGesture().
  21100. */
  21101. void endParameterChangeGesture (int parameterIndex);
  21102. /** The filter can call this when something (apart from a parameter value) has changed.
  21103. It sends a hint to the host that something like the program, number of parameters,
  21104. etc, has changed, and that it should update itself.
  21105. */
  21106. void updateHostDisplay();
  21107. /** Returns the number of preset programs the filter supports.
  21108. The value returned must be valid as soon as this object is created, and
  21109. must not change over its lifetime.
  21110. This value shouldn't be less than 1.
  21111. */
  21112. virtual int getNumPrograms() = 0;
  21113. /** Returns the number of the currently active program.
  21114. */
  21115. virtual int getCurrentProgram() = 0;
  21116. /** Called by the host to change the current program.
  21117. */
  21118. virtual void setCurrentProgram (int index) = 0;
  21119. /** Must return the name of a given program. */
  21120. virtual const String getProgramName (int index) = 0;
  21121. /** Called by the host to rename a program.
  21122. */
  21123. virtual void changeProgramName (int index, const String& newName) = 0;
  21124. /** The host will call this method when it wants to save the filter's internal state.
  21125. This must copy any info about the filter's state into the block of memory provided,
  21126. so that the host can store this and later restore it using setStateInformation().
  21127. Note that there's also a getCurrentProgramStateInformation() method, which only
  21128. stores the current program, not the state of the entire filter.
  21129. See also the helper function copyXmlToBinary() for storing settings as XML.
  21130. @see getCurrentProgramStateInformation
  21131. */
  21132. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  21133. /** The host will call this method if it wants to save the state of just the filter's
  21134. current program.
  21135. Unlike getStateInformation, this should only return the current program's state.
  21136. Not all hosts support this, and if you don't implement it, the base class
  21137. method just calls getStateInformation() instead. If you do implement it, be
  21138. sure to also implement getCurrentProgramStateInformation.
  21139. @see getStateInformation, setCurrentProgramStateInformation
  21140. */
  21141. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21142. /** This must restore the filter's state from a block of data previously created
  21143. using getStateInformation().
  21144. Note that there's also a setCurrentProgramStateInformation() method, which tries
  21145. to restore just the current program, not the state of the entire filter.
  21146. See also the helper function getXmlFromBinary() for loading settings as XML.
  21147. @see setCurrentProgramStateInformation
  21148. */
  21149. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  21150. /** The host will call this method if it wants to restore the state of just the filter's
  21151. current program.
  21152. Not all hosts support this, and if you don't implement it, the base class
  21153. method just calls setStateInformation() instead. If you do implement it, be
  21154. sure to also implement getCurrentProgramStateInformation.
  21155. @see setStateInformation, getCurrentProgramStateInformation
  21156. */
  21157. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  21158. /** Adds a listener that will be called when an aspect of this processor changes. */
  21159. void addListener (AudioProcessorListener* const newListener) throw();
  21160. /** Removes a previously added listener. */
  21161. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  21162. /** Not for public use - this is called before deleting an editor component. */
  21163. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  21164. /** Not for public use - this is called to initialise the processor. */
  21165. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  21166. /** Not for public use - this is called to initialise the processor before playing. */
  21167. void setPlayConfigDetails (const int numIns, const int numOuts,
  21168. const double sampleRate,
  21169. const int blockSize) throw();
  21170. juce_UseDebuggingNewOperator
  21171. protected:
  21172. /** Helper function that just converts an xml element into a binary blob.
  21173. Use this in your filter's getStateInformation() method if you want to
  21174. store its state as xml.
  21175. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  21176. from a binary blob.
  21177. */
  21178. static void copyXmlToBinary (const XmlElement& xml,
  21179. JUCE_NAMESPACE::MemoryBlock& destData);
  21180. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  21181. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  21182. an XmlElement object that the caller must delete when no longer needed.
  21183. */
  21184. static XmlElement* getXmlFromBinary (const void* data,
  21185. const int sizeInBytes);
  21186. /** @internal */
  21187. AudioPlayHead* playHead;
  21188. /** @internal */
  21189. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  21190. private:
  21191. VoidArray listeners;
  21192. AudioProcessorEditor* activeEditor;
  21193. double sampleRate;
  21194. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  21195. bool suspended, nonRealtime;
  21196. CriticalSection callbackLock, listenerLock;
  21197. #ifdef JUCE_DEBUG
  21198. BitArray changingParams;
  21199. #endif
  21200. AudioProcessor (const AudioProcessor&);
  21201. const AudioProcessor& operator= (const AudioProcessor&);
  21202. };
  21203. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21204. /********* End of inlined file: juce_AudioProcessor.h *********/
  21205. #endif
  21206. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21207. #endif
  21208. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21209. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  21210. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21211. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21212. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  21213. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21214. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21215. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  21216. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21217. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21218. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  21219. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21220. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21221. /********* Start of inlined file: juce_PluginDescription.h *********/
  21222. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21223. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21224. /**
  21225. A small class to represent some facts about a particular type of plugin.
  21226. This class is for storing and managing the details about a plugin without
  21227. actually having to load an instance of it.
  21228. A KnownPluginList contains a list of PluginDescription objects.
  21229. @see KnownPluginList
  21230. */
  21231. class JUCE_API PluginDescription
  21232. {
  21233. public:
  21234. PluginDescription() throw();
  21235. PluginDescription (const PluginDescription& other) throw();
  21236. const PluginDescription& operator= (const PluginDescription& other) throw();
  21237. ~PluginDescription() throw();
  21238. /** The name of the plugin. */
  21239. String name;
  21240. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  21241. */
  21242. String pluginFormatName;
  21243. /** A category, such as "Dynamics", "Reverbs", etc.
  21244. */
  21245. String category;
  21246. /** The manufacturer. */
  21247. String manufacturerName;
  21248. /** The version. This string doesn't have any particular format. */
  21249. String version;
  21250. /** Either the file containing the plugin module, or some other unique way
  21251. of identifying it.
  21252. E.g. for an AU, this would be an ID string that the component manager
  21253. could use to retrieve the plugin. For a VST, it's the file path.
  21254. */
  21255. String fileOrIdentifier;
  21256. /** The last time the plugin file was changed.
  21257. This is handy when scanning for new or changed plugins.
  21258. */
  21259. Time lastFileModTime;
  21260. /** A unique ID for the plugin.
  21261. Note that this might not be unique between formats, e.g. a VST and some
  21262. other format might actually have the same id.
  21263. @see createIdentifierString
  21264. */
  21265. int uid;
  21266. /** True if the plugin identifies itself as a synthesiser. */
  21267. bool isInstrument;
  21268. /** The number of inputs. */
  21269. int numInputChannels;
  21270. /** The number of outputs. */
  21271. int numOutputChannels;
  21272. /** Returns true if the two descriptions refer the the same plugin.
  21273. This isn't quite as simple as them just having the same file (because of
  21274. shell plugins).
  21275. */
  21276. bool isDuplicateOf (const PluginDescription& other) const;
  21277. /** Returns a string that can be saved and used to uniquely identify the
  21278. plugin again.
  21279. This contains less info than the XML encoding, and is independent of the
  21280. plugin's file location, so can be used to store a plugin ID for use
  21281. across different machines.
  21282. */
  21283. const String createIdentifierString() const throw();
  21284. /** Creates an XML object containing these details.
  21285. @see loadFromXml
  21286. */
  21287. XmlElement* createXml() const;
  21288. /** Reloads the info in this structure from an XML record that was previously
  21289. saved with createXML().
  21290. Returns true if the XML was a valid plugin description.
  21291. */
  21292. bool loadFromXml (const XmlElement& xml);
  21293. juce_UseDebuggingNewOperator
  21294. };
  21295. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21296. /********* End of inlined file: juce_PluginDescription.h *********/
  21297. /**
  21298. Base class for an active instance of a plugin.
  21299. This derives from the AudioProcessor class, and adds some extra functionality
  21300. that helps when wrapping dynamically loaded plugins.
  21301. @see AudioProcessor, AudioPluginFormat
  21302. */
  21303. class JUCE_API AudioPluginInstance : public AudioProcessor
  21304. {
  21305. public:
  21306. /** Destructor.
  21307. Make sure that you delete any UI components that belong to this plugin before
  21308. deleting the plugin.
  21309. */
  21310. virtual ~AudioPluginInstance();
  21311. /** Fills-in the appropriate parts of this plugin description object.
  21312. */
  21313. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  21314. juce_UseDebuggingNewOperator
  21315. protected:
  21316. AudioPluginInstance();
  21317. AudioPluginInstance (const AudioPluginInstance&);
  21318. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  21319. };
  21320. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21321. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  21322. class PluginDescription;
  21323. /**
  21324. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  21325. Use the static getNumFormats() and getFormat() calls to find the types
  21326. of format that are available.
  21327. */
  21328. class JUCE_API AudioPluginFormat
  21329. {
  21330. public:
  21331. /** Destructor. */
  21332. virtual ~AudioPluginFormat();
  21333. /** Returns the format name.
  21334. E.g. "VST", "AudioUnit", etc.
  21335. */
  21336. virtual const String getName() const = 0;
  21337. /** This tries to create descriptions for all the plugin types available in
  21338. a binary module file.
  21339. The file will be some kind of DLL or bundle.
  21340. Normally there will only be one type returned, but some plugins
  21341. (e.g. VST shells) can use a single DLL to create a set of different plugin
  21342. subtypes, so in that case, each subtype is returned as a separate object.
  21343. */
  21344. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  21345. const String& fileOrIdentifier) = 0;
  21346. /** Tries to recreate a type from a previously generated PluginDescription.
  21347. @see PluginDescription::createInstance
  21348. */
  21349. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  21350. /** Should do a quick check to see if this file or directory might be a plugin of
  21351. this format.
  21352. This is for searching for potential files, so it shouldn't actually try to
  21353. load the plugin or do anything time-consuming.
  21354. */
  21355. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  21356. /** Returns a readable version of the name of the plugin that this identifier refers to.
  21357. */
  21358. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  21359. /** Checks whether this plugin could possibly be loaded.
  21360. It doesn't actually need to load it, just to check whether the file or component
  21361. still exists.
  21362. */
  21363. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  21364. /** Searches a suggested set of directories for any plugins in this format.
  21365. The path might be ignored, e.g. by AUs, which are found by the OS rather
  21366. than manually.
  21367. */
  21368. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  21369. const bool recursive) = 0;
  21370. /** Returns the typical places to look for this kind of plugin.
  21371. Note that if this returns no paths, it means that the format can't be scanned-for
  21372. (i.e. it's an internal format that doesn't live in files)
  21373. */
  21374. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  21375. juce_UseDebuggingNewOperator
  21376. protected:
  21377. AudioPluginFormat() throw();
  21378. AudioPluginFormat (const AudioPluginFormat&);
  21379. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  21380. };
  21381. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21382. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  21383. /**
  21384. This maintains a list of known AudioPluginFormats.
  21385. @see AudioPluginFormat
  21386. */
  21387. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  21388. {
  21389. public:
  21390. AudioPluginFormatManager() throw();
  21391. /** Destructor. */
  21392. ~AudioPluginFormatManager() throw();
  21393. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  21394. /** Adds any formats that it knows about, e.g. VST.
  21395. */
  21396. void addDefaultFormats();
  21397. /** Returns the number of types of format that are available.
  21398. Use getFormat() to get one of them.
  21399. */
  21400. int getNumFormats() throw();
  21401. /** Returns one of the available formats.
  21402. @see getNumFormats
  21403. */
  21404. AudioPluginFormat* getFormat (const int index) throw();
  21405. /** Adds a format to the list.
  21406. The object passed in will be owned and deleted by the manager.
  21407. */
  21408. void addFormat (AudioPluginFormat* const format) throw();
  21409. /** Tries to load the type for this description, by trying all the formats
  21410. that this manager knows about.
  21411. The caller is responsible for deleting the object that is returned.
  21412. If it can't load the plugin, it returns 0 and leaves a message in the
  21413. errorMessage string.
  21414. */
  21415. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  21416. String& errorMessage) const;
  21417. /** Checks that the file or component for this plugin actually still exists.
  21418. (This won't try to load the plugin)
  21419. */
  21420. bool doesPluginStillExist (const PluginDescription& description) const;
  21421. juce_UseDebuggingNewOperator
  21422. private:
  21423. OwnedArray <AudioPluginFormat> formats;
  21424. AudioPluginFormatManager (const AudioPluginFormatManager&);
  21425. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  21426. };
  21427. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21428. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  21429. /********* Start of inlined file: juce_KnownPluginList.h *********/
  21430. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21431. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21432. /********* Start of inlined file: juce_PopupMenu.h *********/
  21433. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  21434. #define __JUCE_POPUPMENU_JUCEHEADER__
  21435. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  21436. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21437. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21438. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  21439. @see PopupMenu::addCustomItem
  21440. */
  21441. class JUCE_API PopupMenuCustomComponent : public Component
  21442. {
  21443. public:
  21444. /** Destructor. */
  21445. ~PopupMenuCustomComponent();
  21446. /** Chooses the size that this component would like to have.
  21447. Note that the size which this method returns isn't necessarily the one that
  21448. the menu will give it, as it will be stretched to fit the other items in
  21449. the menu.
  21450. */
  21451. virtual void getIdealSize (int& idealWidth,
  21452. int& idealHeight) = 0;
  21453. /** Dismisses the menu indicating that this item has been chosen.
  21454. This will cause the menu to exit from its modal state, returning
  21455. this item's id as the result.
  21456. */
  21457. void triggerMenuItem();
  21458. /** Returns true if this item should be highlighted because the mouse is
  21459. over it.
  21460. You can call this method in your paint() method to find out whether
  21461. to draw a highlight.
  21462. */
  21463. bool isItemHighlighted() const throw() { return isHighlighted; }
  21464. protected:
  21465. /** Constructor.
  21466. If isTriggeredAutomatically is true, then the menu will automatically detect
  21467. a click on this component and use that to trigger it. If it's false, then it's
  21468. up to your class to manually trigger the item if it wants to.
  21469. */
  21470. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  21471. private:
  21472. friend class MenuItemInfo;
  21473. friend class MenuItemComponent;
  21474. friend class PopupMenuWindow;
  21475. int refCount_;
  21476. bool isHighlighted, isTriggeredAutomatically;
  21477. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  21478. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  21479. };
  21480. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21481. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  21482. /** Creates and displays a popup-menu.
  21483. To show a popup-menu, you create one of these, add some items to it, then
  21484. call its show() method, which returns the id of the item the user selects.
  21485. E.g. @code
  21486. void MyWidget::mouseDown (const MouseEvent& e)
  21487. {
  21488. PopupMenu m;
  21489. m.addItem (1, "item 1");
  21490. m.addItem (2, "item 2");
  21491. const int result = m.show();
  21492. if (result == 0)
  21493. {
  21494. // user dismissed the menu without picking anything
  21495. }
  21496. else if (result == 1)
  21497. {
  21498. // user picked item 1
  21499. }
  21500. else if (result == 2)
  21501. {
  21502. // user picked item 2
  21503. }
  21504. }
  21505. @endcode
  21506. Submenus are easy too: @code
  21507. void MyWidget::mouseDown (const MouseEvent& e)
  21508. {
  21509. PopupMenu subMenu;
  21510. subMenu.addItem (1, "item 1");
  21511. subMenu.addItem (2, "item 2");
  21512. PopupMenu mainMenu;
  21513. mainMenu.addItem (3, "item 3");
  21514. mainMenu.addSubMenu ("other choices", subMenu);
  21515. const int result = m.show();
  21516. ...etc
  21517. }
  21518. @endcode
  21519. */
  21520. class JUCE_API PopupMenu
  21521. {
  21522. public:
  21523. /** Creates an empty popup menu. */
  21524. PopupMenu() throw();
  21525. /** Creates a copy of another menu. */
  21526. PopupMenu (const PopupMenu& other) throw();
  21527. /** Destructor. */
  21528. ~PopupMenu() throw();
  21529. /** Copies this menu from another one. */
  21530. const PopupMenu& operator= (const PopupMenu& other) throw();
  21531. /** Resets the menu, removing all its items. */
  21532. void clear() throw();
  21533. /** Appends a new text item for this menu to show.
  21534. @param itemResultId the number that will be returned from the show() method
  21535. if the user picks this item. The value should never be
  21536. zero, because that's used to indicate that the user didn't
  21537. select anything.
  21538. @param itemText the text to show.
  21539. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21540. picked
  21541. @param isTicked if true, the item will be shown with a tick next to it
  21542. @param iconToUse if this is non-zero, it should be an image that will be
  21543. displayed to the left of the item. This method will take its
  21544. own copy of the image passed-in, so there's no need to keep
  21545. it hanging around.
  21546. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21547. */
  21548. void addItem (const int itemResultId,
  21549. const String& itemText,
  21550. const bool isActive = true,
  21551. const bool isTicked = false,
  21552. const Image* const iconToUse = 0) throw();
  21553. /** Adds an item that represents one of the commands in a command manager object.
  21554. @param commandManager the manager to use to trigger the command and get information
  21555. about it
  21556. @param commandID the ID of the command
  21557. @param displayName if this is non-empty, then this string will be used instead of
  21558. the command's registered name
  21559. */
  21560. void addCommandItem (ApplicationCommandManager* commandManager,
  21561. const int commandID,
  21562. const String& displayName = String::empty) throw();
  21563. /** Appends a text item with a special colour.
  21564. This is the same as addItem(), but specifies a colour to use for the
  21565. text, which will override the default colours that are used by the
  21566. current look-and-feel. See addItem() for a description of the parameters.
  21567. */
  21568. void addColouredItem (const int itemResultId,
  21569. const String& itemText,
  21570. const Colour& itemTextColour,
  21571. const bool isActive = true,
  21572. const bool isTicked = false,
  21573. const Image* const iconToUse = 0) throw();
  21574. /** Appends a custom menu item.
  21575. This will add a user-defined component to use as a menu item. The component
  21576. passed in will be deleted by this menu when it's no longer needed.
  21577. @see PopupMenuCustomComponent
  21578. */
  21579. void addCustomItem (const int itemResultId,
  21580. PopupMenuCustomComponent* const customComponent) throw();
  21581. /** Appends a custom menu item that can't be used to trigger a result.
  21582. This will add a user-defined component to use as a menu item. Unlike the
  21583. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21584. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21585. delete the component when it's finished, so it's the caller's responsibility
  21586. to manage the component that is passed-in.
  21587. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21588. detection of a mouse-click on your component, and use that to trigger the
  21589. menu ID specified in itemResultId. If this is false, the menu item can't
  21590. be triggered, so itemResultId is not used.
  21591. @see PopupMenuCustomComponent
  21592. */
  21593. void addCustomItem (const int itemResultId,
  21594. Component* customComponent,
  21595. int idealWidth, int idealHeight,
  21596. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21597. /** Appends a sub-menu.
  21598. If the menu that's passed in is empty, it will appear as an inactive item.
  21599. */
  21600. void addSubMenu (const String& subMenuName,
  21601. const PopupMenu& subMenu,
  21602. const bool isActive = true,
  21603. Image* const iconToUse = 0,
  21604. const bool isTicked = false) throw();
  21605. /** Appends a separator to the menu, to help break it up into sections.
  21606. The menu class is smart enough not to display separators at the top or bottom
  21607. of the menu, and it will replace mutliple adjacent separators with a single
  21608. one, so your code can be quite free and easy about adding these, and it'll
  21609. always look ok.
  21610. */
  21611. void addSeparator() throw();
  21612. /** Adds a non-clickable text item to the menu.
  21613. This is a bold-font items which can be used as a header to separate the items
  21614. into named groups.
  21615. */
  21616. void addSectionHeader (const String& title) throw();
  21617. /** Returns the number of items that the menu currently contains.
  21618. (This doesn't count separators).
  21619. */
  21620. int getNumItems() const throw();
  21621. /** Returns true if the menu contains a command item that triggers the given command. */
  21622. bool containsCommandItem (const int commandID) const throw();
  21623. /** Returns true if the menu contains any items that can be used. */
  21624. bool containsAnyActiveItems() const throw();
  21625. /** Displays the menu and waits for the user to pick something.
  21626. This will display the menu modally, and return the ID of the item that the
  21627. user picks. If they click somewhere off the menu to get rid of it without
  21628. choosing anything, this will return 0.
  21629. The current location of the mouse will be used as the position to show the
  21630. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21631. on where this point is on the screen, the menu will appear above, below or
  21632. to the side of the point.
  21633. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21634. then when the menu first appears, it will make sure
  21635. that this item is visible. So if the menu has too many
  21636. items to fit on the screen, it will be scrolled to a
  21637. position where this item is visible.
  21638. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21639. than this if some items are too long to fit.
  21640. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21641. vertical column, the menu may be laid out as a series of
  21642. columns - this is the maximum number allowed. To use the
  21643. default value for this (probably about 7), you can pass
  21644. in zero.
  21645. @param standardItemHeight if this is non-zero, it will be used as the standard
  21646. height for menu items (apart from custom items)
  21647. @see showAt
  21648. */
  21649. int show (const int itemIdThatMustBeVisible = 0,
  21650. const int minimumWidth = 0,
  21651. const int maximumNumColumns = 0,
  21652. const int standardItemHeight = 0);
  21653. /** Displays the menu at a specific location.
  21654. This is the same as show(), but uses a specific location (in global screen
  21655. co-ordinates) rather than the current mouse position.
  21656. Note that the co-ordinates don't specify the top-left of the menu - they
  21657. indicate a point of interest, and the menu will position itself nearby to
  21658. this point, trying to keep it fully on-screen.
  21659. @see show()
  21660. */
  21661. int showAt (const int screenX,
  21662. const int screenY,
  21663. const int itemIdThatMustBeVisible = 0,
  21664. const int minimumWidth = 0,
  21665. const int maximumNumColumns = 0,
  21666. const int standardItemHeight = 0);
  21667. /** Displays the menu as if it's attached to a component such as a button.
  21668. This is similar to showAt(), but will position it next to the given component, e.g.
  21669. so that the menu's edge is aligned with that of the component. This is intended for
  21670. things like buttons that trigger a pop-up menu.
  21671. */
  21672. int showAt (Component* componentToAttachTo,
  21673. const int itemIdThatMustBeVisible = 0,
  21674. const int minimumWidth = 0,
  21675. const int maximumNumColumns = 0,
  21676. const int standardItemHeight = 0);
  21677. /** Closes any menus that are currently open.
  21678. This might be useful if you have a situation where your window is being closed
  21679. by some means other than a user action, and you'd like to make sure that menus
  21680. aren't left hanging around.
  21681. */
  21682. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21683. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21684. This can be called before show() if you need a customised menu. Be careful
  21685. not to delete the LookAndFeel object before the menu has been deleted.
  21686. */
  21687. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21688. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21689. These constants can be used either via the LookAndFeel::setColour()
  21690. method for the look and feel that is set for this menu with setLookAndFeel()
  21691. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21692. */
  21693. enum ColourIds
  21694. {
  21695. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21696. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21697. colour is specified when the item is added). */
  21698. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21699. addSectionHeader() method). */
  21700. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21701. highlighted menu item. */
  21702. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21703. highlighted item. */
  21704. };
  21705. /**
  21706. Allows you to iterate through the items in a pop-up menu, and examine
  21707. their properties.
  21708. To use this, just create one and repeatedly call its next() method. When this
  21709. returns true, all the member variables of the iterator are filled-out with
  21710. information describing the menu item. When it returns false, the end of the
  21711. list has been reached.
  21712. */
  21713. class JUCE_API MenuItemIterator
  21714. {
  21715. public:
  21716. /** Creates an iterator that will scan through the items in the specified
  21717. menu.
  21718. Be careful not to add any items to a menu while it is being iterated,
  21719. or things could get out of step.
  21720. */
  21721. MenuItemIterator (const PopupMenu& menu) throw();
  21722. /** Destructor. */
  21723. ~MenuItemIterator() throw();
  21724. /** Returns true if there is another item, and sets up all this object's
  21725. member variables to reflect that item's properties.
  21726. */
  21727. bool next() throw();
  21728. String itemName;
  21729. const PopupMenu* subMenu;
  21730. int itemId;
  21731. bool isSeparator;
  21732. bool isTicked;
  21733. bool isEnabled;
  21734. bool isCustomComponent;
  21735. bool isSectionHeader;
  21736. const Colour* customColour;
  21737. const Image* customImage;
  21738. ApplicationCommandManager* commandManager;
  21739. juce_UseDebuggingNewOperator
  21740. private:
  21741. const PopupMenu& menu;
  21742. int index;
  21743. MenuItemIterator (const MenuItemIterator&);
  21744. const MenuItemIterator& operator= (const MenuItemIterator&);
  21745. };
  21746. juce_UseDebuggingNewOperator
  21747. private:
  21748. friend class PopupMenuWindow;
  21749. friend class MenuItemIterator;
  21750. VoidArray items;
  21751. LookAndFeel* lookAndFeel;
  21752. bool separatorPending;
  21753. void addSeparatorIfPending();
  21754. int showMenu (const int x, const int y, const int w, const int h,
  21755. const int itemIdThatMustBeVisible,
  21756. const int minimumWidth,
  21757. const int maximumNumColumns,
  21758. const int standardItemHeight,
  21759. const bool alignToRectangle,
  21760. Component* const componentAttachedTo) throw();
  21761. friend class MenuBarComponent;
  21762. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21763. const int itemIdThatMustBeVisible,
  21764. const int minimumWidth,
  21765. const int maximumNumColumns,
  21766. const int standardItemHeight,
  21767. const bool alignToRectangle,
  21768. Component* menuBarComponent,
  21769. ApplicationCommandManager** managerOfChosenCommand,
  21770. Component* const componentAttachedTo) throw();
  21771. };
  21772. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21773. /********* End of inlined file: juce_PopupMenu.h *********/
  21774. /**
  21775. Manages a list of plugin types.
  21776. This can be easily edited, saved and loaded, and used to create instances of
  21777. the plugin types in it.
  21778. @see PluginListComponent
  21779. */
  21780. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21781. {
  21782. public:
  21783. /** Creates an empty list.
  21784. */
  21785. KnownPluginList();
  21786. /** Destructor. */
  21787. ~KnownPluginList();
  21788. /** Clears the list. */
  21789. void clear();
  21790. /** Returns the number of types currently in the list.
  21791. @see getType
  21792. */
  21793. int getNumTypes() const throw() { return types.size(); }
  21794. /** Returns one of the types.
  21795. @see getNumTypes
  21796. */
  21797. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21798. /** Looks for a type in the list which comes from this file.
  21799. */
  21800. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  21801. /** Looks for a type in the list which matches a plugin type ID.
  21802. The identifierString parameter must have been created by
  21803. PluginDescription::createIdentifierString().
  21804. */
  21805. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21806. /** Adds a type manually from its description. */
  21807. bool addType (const PluginDescription& type);
  21808. /** Removes a type. */
  21809. void removeType (const int index) throw();
  21810. /** Looks for all types that can be loaded from a given file, and adds them
  21811. to the list.
  21812. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21813. re-tested if it's not already in the list, or if the file's modification
  21814. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21815. false, the file will always be reloaded and tested.
  21816. Returns true if any new types were added, and all the types found in this
  21817. file (even if it was already known and hasn't been re-scanned) get returned
  21818. in the array.
  21819. */
  21820. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  21821. const bool dontRescanIfAlreadyInList,
  21822. OwnedArray <PluginDescription>& typesFound,
  21823. AudioPluginFormat& formatToUse);
  21824. /** Returns true if the specified file is already known about and if it
  21825. hasn't been modified since our entry was created.
  21826. */
  21827. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  21828. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21829. If any types are found in the files, their descriptions are returned in the array.
  21830. */
  21831. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21832. OwnedArray <PluginDescription>& typesFound);
  21833. /** Sort methods used to change the order of the plugins in the list.
  21834. */
  21835. enum SortMethod
  21836. {
  21837. defaultOrder = 0,
  21838. sortAlphabetically,
  21839. sortByCategory,
  21840. sortByManufacturer,
  21841. sortByFileSystemLocation
  21842. };
  21843. /** Adds all the plugin types to a popup menu so that the user can select one.
  21844. Depending on the sort method, it may add sub-menus for categories,
  21845. manufacturers, etc.
  21846. Use getIndexChosenByMenu() to find out the type that was chosen.
  21847. */
  21848. void addToMenu (PopupMenu& menu,
  21849. const SortMethod sortMethod) const;
  21850. /** Converts a menu item index that has been chosen into its index in this list.
  21851. Returns -1 if it's not an ID that was used.
  21852. @see addToMenu
  21853. */
  21854. int getIndexChosenByMenu (const int menuResultCode) const;
  21855. /** Sorts the list. */
  21856. void sort (const SortMethod method);
  21857. /** Creates some XML that can be used to store the state of this list.
  21858. */
  21859. XmlElement* createXml() const;
  21860. /** Recreates the state of this list from its stored XML format.
  21861. */
  21862. void recreateFromXml (const XmlElement& xml);
  21863. juce_UseDebuggingNewOperator
  21864. private:
  21865. OwnedArray <PluginDescription> types;
  21866. KnownPluginList (const KnownPluginList&);
  21867. const KnownPluginList& operator= (const KnownPluginList&);
  21868. };
  21869. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21870. /********* End of inlined file: juce_KnownPluginList.h *********/
  21871. /**
  21872. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21873. Use one of these objects if you want to wire-up a set of AudioProcessors
  21874. and play back the result.
  21875. Processors can be added to the graph as "nodes" using addNode(), and once
  21876. added, you can connect any of their input or output channels to other
  21877. nodes using addConnection().
  21878. To play back a graph through an audio device, you might want to use an
  21879. AudioProcessorPlayer object.
  21880. */
  21881. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21882. public AsyncUpdater
  21883. {
  21884. public:
  21885. /** Creates an empty graph.
  21886. */
  21887. AudioProcessorGraph();
  21888. /** Destructor.
  21889. Any processor objects that have been added to the graph will also be deleted.
  21890. */
  21891. ~AudioProcessorGraph();
  21892. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21893. To create a node, call AudioProcessorGraph::addNode().
  21894. */
  21895. class JUCE_API Node : public ReferenceCountedObject
  21896. {
  21897. public:
  21898. /** Destructor.
  21899. */
  21900. ~Node();
  21901. /** The ID number assigned to this node.
  21902. This is assigned by the graph that owns it, and can't be changed.
  21903. */
  21904. const uint32 id;
  21905. /** The actual processor object that this node represents.
  21906. */
  21907. AudioProcessor* const processor;
  21908. /** A set of user-definable properties that are associated with this node.
  21909. This can be used to attach values to the node for whatever purpose seems
  21910. useful. For example, you might store an x and y position if your application
  21911. is displaying the nodes on-screen.
  21912. */
  21913. PropertySet properties;
  21914. /** A convenient typedef for referring to a pointer to a node object.
  21915. */
  21916. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21917. juce_UseDebuggingNewOperator
  21918. private:
  21919. friend class AudioProcessorGraph;
  21920. bool isPrepared;
  21921. Node (const uint32 id, AudioProcessor* const processor) throw();
  21922. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21923. void unprepare();
  21924. Node (const Node&);
  21925. const Node& operator= (const Node&);
  21926. };
  21927. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21928. To create a connection, use AudioProcessorGraph::addConnection().
  21929. */
  21930. struct JUCE_API Connection
  21931. {
  21932. public:
  21933. /** The ID number of the node which is the input source for this connection.
  21934. @see AudioProcessorGraph::getNodeForId
  21935. */
  21936. uint32 sourceNodeId;
  21937. /** The index of the output channel of the source node from which this
  21938. connection takes its data.
  21939. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21940. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21941. index of an audio output channel in the source node.
  21942. */
  21943. int sourceChannelIndex;
  21944. /** The ID number of the node which is the destination for this connection.
  21945. @see AudioProcessorGraph::getNodeForId
  21946. */
  21947. uint32 destNodeId;
  21948. /** The index of the input channel of the destination node to which this
  21949. connection delivers its data.
  21950. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21951. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21952. index of an audio input channel in the destination node.
  21953. */
  21954. int destChannelIndex;
  21955. juce_UseDebuggingNewOperator
  21956. private:
  21957. };
  21958. /** Deletes all nodes and connections from this graph.
  21959. Any processor objects in the graph will be deleted.
  21960. */
  21961. void clear();
  21962. /** Returns the number of nodes in the graph. */
  21963. int getNumNodes() const throw() { return nodes.size(); }
  21964. /** Returns a pointer to one of the nodes in the graph.
  21965. This will return 0 if the index is out of range.
  21966. @see getNodeForId
  21967. */
  21968. Node* getNode (const int index) const throw() { return nodes [index]; }
  21969. /** Searches the graph for a node with the given ID number and returns it.
  21970. If no such node was found, this returns 0.
  21971. @see getNode
  21972. */
  21973. Node* getNodeForId (const uint32 nodeId) const throw();
  21974. /** Adds a node to the graph.
  21975. This creates a new node in the graph, for the specified processor. Once you have
  21976. added a processor to the graph, the graph owns it and will delete it later when
  21977. it is no longer needed.
  21978. The optional nodeId parameter lets you specify an ID to use for the node, but
  21979. if the value is already in use, this new node will overwrite the old one.
  21980. If this succeeds, it returns a pointer to the newly-created node.
  21981. */
  21982. Node* addNode (AudioProcessor* const newProcessor,
  21983. uint32 nodeId = 0);
  21984. /** Deletes a node within the graph which has the specified ID.
  21985. This will also delete any connections that are attached to this node.
  21986. */
  21987. bool removeNode (const uint32 nodeId);
  21988. /** Returns the number of connections in the graph. */
  21989. int getNumConnections() const throw() { return connections.size(); }
  21990. /** Returns a pointer to one of the connections in the graph. */
  21991. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21992. /** Searches for a connection between some specified channels.
  21993. If no such connection is found, this returns 0.
  21994. */
  21995. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21996. const int sourceChannelIndex,
  21997. const uint32 destNodeId,
  21998. const int destChannelIndex) const throw();
  21999. /** Returns true if there is a connection between any of the channels of
  22000. two specified nodes.
  22001. */
  22002. bool isConnected (const uint32 possibleSourceNodeId,
  22003. const uint32 possibleDestNodeId) const throw();
  22004. /** Returns true if it would be legal to connect the specified points.
  22005. */
  22006. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  22007. const uint32 destNodeId, const int destChannelIndex) const throw();
  22008. /** Attempts to connect two specified channels of two nodes.
  22009. If this isn't allowed (e.g. because you're trying to connect a midi channel
  22010. to an audio one or other such nonsense), then it'll return false.
  22011. */
  22012. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  22013. const uint32 destNodeId, const int destChannelIndex);
  22014. /** Deletes the connection with the specified index.
  22015. Returns true if a connection was actually deleted.
  22016. */
  22017. void removeConnection (const int index);
  22018. /** Deletes any connection between two specified points.
  22019. Returns true if a connection was actually deleted.
  22020. */
  22021. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  22022. const uint32 destNodeId, const int destChannelIndex);
  22023. /** Removes all connections from the specified node.
  22024. */
  22025. bool disconnectNode (const uint32 nodeId);
  22026. /** Performs a sanity checks of all the connections.
  22027. This might be useful if some of the processors are doing things like changing
  22028. their channel counts, which could render some connections obsolete.
  22029. */
  22030. bool removeIllegalConnections();
  22031. /** A special number that represents the midi channel of a node.
  22032. This is used as a channel index value if you want to refer to the midi input
  22033. or output instead of an audio channel.
  22034. */
  22035. static const int midiChannelIndex;
  22036. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  22037. in order to use the audio that comes into and out of the graph itself.
  22038. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  22039. node in the graph which delivers the audio that is coming into the parent
  22040. graph. This allows you to stream the data to other nodes and process the
  22041. incoming audio.
  22042. Likewise, one of these in "output" mode can be sent data which it will add to
  22043. the sum of data being sent to the graph's output.
  22044. @see AudioProcessorGraph
  22045. */
  22046. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  22047. {
  22048. public:
  22049. /** Specifies the mode in which this processor will operate.
  22050. */
  22051. enum IODeviceType
  22052. {
  22053. audioInputNode, /**< In this mode, the processor has output channels
  22054. representing all the audio input channels that are
  22055. coming into its parent audio graph. */
  22056. audioOutputNode, /**< In this mode, the processor has input channels
  22057. representing all the audio output channels that are
  22058. going out of its parent audio graph. */
  22059. midiInputNode, /**< In this mode, the processor has a midi output which
  22060. delivers the same midi data that is arriving at its
  22061. parent graph. */
  22062. midiOutputNode /**< In this mode, the processor has a midi input and
  22063. any data sent to it will be passed out of the parent
  22064. graph. */
  22065. };
  22066. /** Returns the mode of this processor. */
  22067. IODeviceType getType() const throw() { return type; }
  22068. /** Returns the parent graph to which this processor belongs, or 0 if it
  22069. hasn't yet been added to one. */
  22070. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  22071. /** True if this is an audio or midi input. */
  22072. bool isInput() const throw();
  22073. /** True if this is an audio or midi output. */
  22074. bool isOutput() const throw();
  22075. AudioGraphIOProcessor (const IODeviceType type);
  22076. ~AudioGraphIOProcessor();
  22077. const String getName() const;
  22078. void fillInPluginDescription (PluginDescription& d) const;
  22079. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22080. void releaseResources();
  22081. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  22082. const String getInputChannelName (const int channelIndex) const;
  22083. const String getOutputChannelName (const int channelIndex) const;
  22084. bool isInputChannelStereoPair (int index) const;
  22085. bool isOutputChannelStereoPair (int index) const;
  22086. bool acceptsMidi() const;
  22087. bool producesMidi() const;
  22088. AudioProcessorEditor* createEditor();
  22089. int getNumParameters();
  22090. const String getParameterName (int);
  22091. float getParameter (int);
  22092. const String getParameterText (int);
  22093. void setParameter (int, float);
  22094. int getNumPrograms();
  22095. int getCurrentProgram();
  22096. void setCurrentProgram (int);
  22097. const String getProgramName (int);
  22098. void changeProgramName (int, const String&);
  22099. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  22100. void setStateInformation (const void* data, int sizeInBytes);
  22101. /** @internal */
  22102. void setParentGraph (AudioProcessorGraph* const graph) throw();
  22103. juce_UseDebuggingNewOperator
  22104. private:
  22105. const IODeviceType type;
  22106. AudioProcessorGraph* graph;
  22107. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  22108. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  22109. };
  22110. // AudioProcessor methods:
  22111. const String getName() const;
  22112. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22113. void releaseResources();
  22114. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  22115. const String getInputChannelName (const int channelIndex) const;
  22116. const String getOutputChannelName (const int channelIndex) const;
  22117. bool isInputChannelStereoPair (int index) const;
  22118. bool isOutputChannelStereoPair (int index) const;
  22119. bool acceptsMidi() const;
  22120. bool producesMidi() const;
  22121. AudioProcessorEditor* createEditor() { return 0; }
  22122. int getNumParameters() { return 0; }
  22123. const String getParameterName (int) { return String::empty; }
  22124. float getParameter (int) { return 0; }
  22125. const String getParameterText (int) { return String::empty; }
  22126. void setParameter (int, float) { }
  22127. int getNumPrograms() { return 0; }
  22128. int getCurrentProgram() { return 0; }
  22129. void setCurrentProgram (int) { }
  22130. const String getProgramName (int) { return String::empty; }
  22131. void changeProgramName (int, const String&) { }
  22132. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  22133. void setStateInformation (const void* data, int sizeInBytes);
  22134. /** @internal */
  22135. void handleAsyncUpdate();
  22136. juce_UseDebuggingNewOperator
  22137. private:
  22138. ReferenceCountedArray <Node> nodes;
  22139. OwnedArray <Connection> connections;
  22140. int lastNodeId;
  22141. AudioSampleBuffer renderingBuffers;
  22142. OwnedArray <MidiBuffer> midiBuffers;
  22143. CriticalSection renderLock;
  22144. VoidArray renderingOps;
  22145. friend class AudioGraphIOProcessor;
  22146. AudioSampleBuffer* currentAudioInputBuffer;
  22147. AudioSampleBuffer currentAudioOutputBuffer;
  22148. MidiBuffer* currentMidiInputBuffer;
  22149. MidiBuffer currentMidiOutputBuffer;
  22150. void clearRenderingSequence();
  22151. void buildRenderingSequence();
  22152. bool isAnInputTo (const uint32 possibleInputId,
  22153. const uint32 possibleDestinationId,
  22154. const int recursionCheck) const throw();
  22155. AudioProcessorGraph (const AudioProcessorGraph&);
  22156. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  22157. };
  22158. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  22159. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  22160. #endif
  22161. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  22162. #endif
  22163. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22164. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  22165. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22166. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22167. /********* Start of inlined file: juce_AudioIODevice.h *********/
  22168. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22169. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22170. class AudioIODevice;
  22171. /**
  22172. One of these is passed to an AudioIODevice object to stream the audio data
  22173. in and out.
  22174. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  22175. method on its own high-priority audio thread, when it needs to send or receive
  22176. the next block of data.
  22177. @see AudioIODevice, AudioDeviceManager
  22178. */
  22179. class JUCE_API AudioIODeviceCallback
  22180. {
  22181. public:
  22182. /** Destructor. */
  22183. virtual ~AudioIODeviceCallback() {}
  22184. /** Processes a block of incoming and outgoing audio data.
  22185. The subclass's implementation should use the incoming audio for whatever
  22186. purposes it needs to, and must fill all the output channels with the next
  22187. block of output data before returning.
  22188. The channel data is arranged with the same array indices as the channel name
  22189. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  22190. that aren't specified in AudioIODevice::open() will have a null pointer for their
  22191. associated channel, so remember to check for this.
  22192. @param inputChannelData a set of arrays containing the audio data for each
  22193. incoming channel - this data is valid until the function
  22194. returns. There will be one channel of data for each input
  22195. channel that was enabled when the audio device was opened
  22196. (see AudioIODevice::open())
  22197. @param numInputChannels the number of pointers to channel data in the
  22198. inputChannelData array.
  22199. @param outputChannelData a set of arrays which need to be filled with the data
  22200. that should be sent to each outgoing channel of the device.
  22201. There will be one channel of data for each output channel
  22202. that was enabled when the audio device was opened (see
  22203. AudioIODevice::open())
  22204. The initial contents of the array is undefined, so the
  22205. callback function must fill all the channels with zeros if
  22206. its output is silence. Failing to do this could cause quite
  22207. an unpleasant noise!
  22208. @param numOutputChannels the number of pointers to channel data in the
  22209. outputChannelData array.
  22210. @param numSamples the number of samples in each channel of the input and
  22211. output arrays. The number of samples will depend on the
  22212. audio device's buffer size and will usually remain constant,
  22213. although this isn't guaranteed, so make sure your code can
  22214. cope with reasonable changes in the buffer size from one
  22215. callback to the next.
  22216. */
  22217. virtual void audioDeviceIOCallback (const float** inputChannelData,
  22218. int numInputChannels,
  22219. float** outputChannelData,
  22220. int numOutputChannels,
  22221. int numSamples) = 0;
  22222. /** Called to indicate that the device is about to start calling back.
  22223. This will be called just before the audio callbacks begin, either when this
  22224. callback has just been added to an audio device, or after the device has been
  22225. restarted because of a sample-rate or block-size change.
  22226. You can use this opportunity to find out the sample rate and block size
  22227. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  22228. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  22229. @param device the audio IO device that will be used to drive the callback.
  22230. Note that if you're going to store this this pointer, it is
  22231. only valid until the next time that audioDeviceStopped is called.
  22232. */
  22233. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  22234. /** Called to indicate that the device has stopped.
  22235. */
  22236. virtual void audioDeviceStopped() = 0;
  22237. };
  22238. /**
  22239. Base class for an audio device with synchronised input and output channels.
  22240. Subclasses of this are used to implement different protocols such as DirectSound,
  22241. ASIO, CoreAudio, etc.
  22242. To create one of these, you'll need to use the AudioIODeviceType class - see the
  22243. documentation for that class for more info.
  22244. For an easier way of managing audio devices and their settings, have a look at the
  22245. AudioDeviceManager class.
  22246. @see AudioIODeviceType, AudioDeviceManager
  22247. */
  22248. class JUCE_API AudioIODevice
  22249. {
  22250. public:
  22251. /** Destructor. */
  22252. virtual ~AudioIODevice();
  22253. /** Returns the device's name, (as set in the constructor). */
  22254. const String& getName() const throw() { return name; }
  22255. /** Returns the type of the device.
  22256. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  22257. */
  22258. const String& getTypeName() const throw() { return typeName; }
  22259. /** Returns the names of all the available output channels on this device.
  22260. To find out which of these are currently in use, call getActiveOutputChannels().
  22261. */
  22262. virtual const StringArray getOutputChannelNames() = 0;
  22263. /** Returns the names of all the available input channels on this device.
  22264. To find out which of these are currently in use, call getActiveInputChannels().
  22265. */
  22266. virtual const StringArray getInputChannelNames() = 0;
  22267. /** Returns the number of sample-rates this device supports.
  22268. To find out which rates are available on this device, use this method to
  22269. find out how many there are, and getSampleRate() to get the rates.
  22270. @see getSampleRate
  22271. */
  22272. virtual int getNumSampleRates() = 0;
  22273. /** Returns one of the sample-rates this device supports.
  22274. To find out which rates are available on this device, use getNumSampleRates() to
  22275. find out how many there are, and getSampleRate() to get the individual rates.
  22276. The sample rate is set by the open() method.
  22277. (Note that for DirectSound some rates might not work, depending on combinations
  22278. of i/o channels that are being opened).
  22279. @see getNumSampleRates
  22280. */
  22281. virtual double getSampleRate (int index) = 0;
  22282. /** Returns the number of sizes of buffer that are available.
  22283. @see getBufferSizeSamples, getDefaultBufferSize
  22284. */
  22285. virtual int getNumBufferSizesAvailable() = 0;
  22286. /** Returns one of the possible buffer-sizes.
  22287. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  22288. @returns a number of samples
  22289. @see getNumBufferSizesAvailable, getDefaultBufferSize
  22290. */
  22291. virtual int getBufferSizeSamples (int index) = 0;
  22292. /** Returns the default buffer-size to use.
  22293. @returns a number of samples
  22294. @see getNumBufferSizesAvailable, getBufferSizeSamples
  22295. */
  22296. virtual int getDefaultBufferSize() = 0;
  22297. /** Tries to open the device ready to play.
  22298. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  22299. input channel should be enabled
  22300. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  22301. output channel should be enabled
  22302. @param sampleRate the sample rate to try to use - to find out which rates are
  22303. available, see getNumSampleRates() and getSampleRate()
  22304. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  22305. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  22306. @returns an error description if there's a problem, or an empty string if it succeeds in
  22307. opening the device
  22308. @see close
  22309. */
  22310. virtual const String open (const BitArray& inputChannels,
  22311. const BitArray& outputChannels,
  22312. double sampleRate,
  22313. int bufferSizeSamples) = 0;
  22314. /** Closes and releases the device if it's open. */
  22315. virtual void close() = 0;
  22316. /** Returns true if the device is still open.
  22317. A device might spontaneously close itself if something goes wrong, so this checks if
  22318. it's still open.
  22319. */
  22320. virtual bool isOpen() = 0;
  22321. /** Starts the device actually playing.
  22322. This must be called after the device has been opened.
  22323. @param callback the callback to use for streaming the data.
  22324. @see AudioIODeviceCallback, open
  22325. */
  22326. virtual void start (AudioIODeviceCallback* callback) = 0;
  22327. /** Stops the device playing.
  22328. Once a device has been started, this will stop it. Any pending calls to the
  22329. callback class will be flushed before this method returns.
  22330. */
  22331. virtual void stop() = 0;
  22332. /** Returns true if the device is still calling back.
  22333. The device might mysteriously stop, so this checks whether it's
  22334. still playing.
  22335. */
  22336. virtual bool isPlaying() = 0;
  22337. /** Returns the last error that happened if anything went wrong. */
  22338. virtual const String getLastError() = 0;
  22339. /** Returns the buffer size that the device is currently using.
  22340. If the device isn't actually open, this value doesn't really mean much.
  22341. */
  22342. virtual int getCurrentBufferSizeSamples() = 0;
  22343. /** Returns the sample rate that the device is currently using.
  22344. If the device isn't actually open, this value doesn't really mean much.
  22345. */
  22346. virtual double getCurrentSampleRate() = 0;
  22347. /** Returns the device's current physical bit-depth.
  22348. If the device isn't actually open, this value doesn't really mean much.
  22349. */
  22350. virtual int getCurrentBitDepth() = 0;
  22351. /** Returns a mask showing which of the available output channels are currently
  22352. enabled.
  22353. @see getOutputChannelNames
  22354. */
  22355. virtual const BitArray getActiveOutputChannels() const = 0;
  22356. /** Returns a mask showing which of the available input channels are currently
  22357. enabled.
  22358. @see getInputChannelNames
  22359. */
  22360. virtual const BitArray getActiveInputChannels() const = 0;
  22361. /** Returns the device's output latency.
  22362. This is the delay in samples between a callback getting a block of data, and
  22363. that data actually getting played.
  22364. */
  22365. virtual int getOutputLatencyInSamples() = 0;
  22366. /** Returns the device's input latency.
  22367. This is the delay in samples between some audio actually arriving at the soundcard,
  22368. and the callback getting passed this block of data.
  22369. */
  22370. virtual int getInputLatencyInSamples() = 0;
  22371. /** True if this device can show a pop-up control panel for editing its settings.
  22372. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  22373. to display it.
  22374. */
  22375. virtual bool hasControlPanel() const;
  22376. /** Shows a device-specific control panel if there is one.
  22377. This should only be called for devices which return true from hasControlPanel().
  22378. */
  22379. virtual bool showControlPanel();
  22380. protected:
  22381. /** Creates a device, setting its name and type member variables. */
  22382. AudioIODevice (const String& deviceName,
  22383. const String& typeName);
  22384. /** @internal */
  22385. String name, typeName;
  22386. };
  22387. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22388. /********* End of inlined file: juce_AudioIODevice.h *********/
  22389. /**
  22390. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  22391. To use one of these, just make it the callback used by your AudioIODevice, and
  22392. give it a processor to use by calling setProcessor().
  22393. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  22394. input to send both streams through the processor.
  22395. @see AudioProcessor, AudioProcessorGraph
  22396. */
  22397. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  22398. public MidiInputCallback
  22399. {
  22400. public:
  22401. /**
  22402. */
  22403. AudioProcessorPlayer();
  22404. /** Destructor. */
  22405. virtual ~AudioProcessorPlayer();
  22406. /** Sets the processor that should be played.
  22407. The processor that is passed in will not be deleted or owned by this object.
  22408. To stop anything playing, pass in 0 to this method.
  22409. */
  22410. void setProcessor (AudioProcessor* const processorToPlay);
  22411. /** Returns the current audio processor that is being played.
  22412. */
  22413. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  22414. /** Returns a midi message collector that you can pass midi messages to if you
  22415. want them to be injected into the midi stream that is being sent to the
  22416. processor.
  22417. */
  22418. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  22419. /** @internal */
  22420. void audioDeviceIOCallback (const float** inputChannelData,
  22421. int totalNumInputChannels,
  22422. float** outputChannelData,
  22423. int totalNumOutputChannels,
  22424. int numSamples);
  22425. /** @internal */
  22426. void audioDeviceAboutToStart (AudioIODevice* device);
  22427. /** @internal */
  22428. void audioDeviceStopped();
  22429. /** @internal */
  22430. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  22431. juce_UseDebuggingNewOperator
  22432. private:
  22433. AudioProcessor* processor;
  22434. CriticalSection lock;
  22435. double sampleRate;
  22436. int blockSize;
  22437. bool isPrepared;
  22438. int numInputChans, numOutputChans;
  22439. float* channels [128];
  22440. AudioSampleBuffer tempBuffer;
  22441. MidiBuffer incomingMidi;
  22442. MidiMessageCollector messageCollector;
  22443. AudioProcessorPlayer (const AudioProcessorPlayer&);
  22444. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  22445. };
  22446. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22447. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  22448. #endif
  22449. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22450. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22451. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22452. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22453. /********* Start of inlined file: juce_PropertyPanel.h *********/
  22454. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  22455. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  22456. /********* Start of inlined file: juce_PropertyComponent.h *********/
  22457. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22458. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22459. class EditableProperty;
  22460. /**
  22461. A base class for a component that goes in a PropertyPanel and displays one of
  22462. an item's properties.
  22463. Subclasses of this are used to display a property in various forms, e.g. a
  22464. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  22465. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  22466. A subclass must implement the refresh() method which will be called to tell the
  22467. component to update itself, and is also responsible for calling this it when the
  22468. item that it refers to is changed.
  22469. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  22470. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  22471. */
  22472. class JUCE_API PropertyComponent : public Component
  22473. {
  22474. public:
  22475. /** Creates a PropertyComponent.
  22476. @param propertyName the name is stored as this component's name, and is
  22477. used as the name displayed next to this component in
  22478. a property panel
  22479. @param preferredHeight the height that the component should be given - some
  22480. items may need to be larger than a normal row height.
  22481. This value can also be set if a subclass changes the
  22482. preferredHeight member variable.
  22483. */
  22484. PropertyComponent (const String& propertyName,
  22485. const int preferredHeight = 25);
  22486. /** Destructor. */
  22487. ~PropertyComponent();
  22488. /** Returns this item's preferred height.
  22489. This value is specified either in the constructor or by a subclass changing the
  22490. preferredHeight member variable.
  22491. */
  22492. int getPreferredHeight() const throw() { return preferredHeight; }
  22493. /** Updates the property component if the item it refers to has changed.
  22494. A subclass must implement this method, and other objects may call it to
  22495. force it to refresh itself.
  22496. The subclass should be economical in the amount of work is done, so for
  22497. example it should check whether it really needs to do a repaint rather than
  22498. just doing one every time this method is called, as it may be called when
  22499. the value being displayed hasn't actually changed.
  22500. */
  22501. virtual void refresh() = 0;
  22502. /** The default paint method fills the background and draws a label for the
  22503. item's name.
  22504. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22505. */
  22506. void paint (Graphics& g);
  22507. /** The default resize method positions any child component to the right of this
  22508. one, based on the look and feel's default label size.
  22509. */
  22510. void resized();
  22511. /** By default, this just repaints the component. */
  22512. void enablementChanged();
  22513. juce_UseDebuggingNewOperator
  22514. protected:
  22515. /** Used by the PropertyPanel to determine how high this component needs to be.
  22516. A subclass can update this value in its constructor but shouldn't alter it later
  22517. as changes won't necessarily be picked up.
  22518. */
  22519. int preferredHeight;
  22520. };
  22521. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22522. /********* End of inlined file: juce_PropertyComponent.h *********/
  22523. /********* Start of inlined file: juce_Viewport.h *********/
  22524. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22525. #define __JUCE_VIEWPORT_JUCEHEADER__
  22526. /********* Start of inlined file: juce_ScrollBar.h *********/
  22527. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22528. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22529. /********* Start of inlined file: juce_Button.h *********/
  22530. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22531. #define __JUCE_BUTTON_JUCEHEADER__
  22532. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22533. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22534. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22535. /********* Start of inlined file: juce_TooltipClient.h *********/
  22536. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22537. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22538. /**
  22539. Components that want to use pop-up tooltips should implement this interface.
  22540. A TooltipWindow will wait for the mouse to hover over a component that
  22541. implements the TooltipClient interface, and when it finds one, it will display
  22542. the tooltip returned by its getTooltip() method.
  22543. @see TooltipWindow, SettableTooltipClient
  22544. */
  22545. class JUCE_API TooltipClient
  22546. {
  22547. public:
  22548. /** Destructor. */
  22549. virtual ~TooltipClient() {}
  22550. /** Returns the string that this object wants to show as its tooltip. */
  22551. virtual const String getTooltip() = 0;
  22552. };
  22553. /**
  22554. An implementation of TooltipClient that stores the tooltip string and a method
  22555. for changing it.
  22556. This makes it easy to add a tooltip to a custom component, by simply adding this
  22557. as a base class and calling setTooltip().
  22558. Many of the Juce widgets already use this as a base class to implement their
  22559. tooltips.
  22560. @see TooltipClient, TooltipWindow
  22561. */
  22562. class JUCE_API SettableTooltipClient : public TooltipClient
  22563. {
  22564. public:
  22565. /** Destructor. */
  22566. virtual ~SettableTooltipClient() {}
  22567. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22568. virtual const String getTooltip() { return tooltipString; }
  22569. juce_UseDebuggingNewOperator
  22570. protected:
  22571. String tooltipString;
  22572. };
  22573. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22574. /********* End of inlined file: juce_TooltipClient.h *********/
  22575. /**
  22576. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22577. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22578. object.
  22579. The TooltipWindow object will then stay invisible, waiting until the mouse
  22580. hovers for the specified length of time - it will then see if it's currently
  22581. over a component which implements the TooltipClient interface, and if so,
  22582. it will make itself visible to show the tooltip in the appropriate place.
  22583. @see TooltipClient, SettableTooltipClient
  22584. */
  22585. class JUCE_API TooltipWindow : public Component,
  22586. private Timer
  22587. {
  22588. public:
  22589. /** Creates a tooltip window.
  22590. Make sure your app only creates one instance of this class, otherwise you'll
  22591. get multiple overlaid tooltips appearing. The window will initially be invisible
  22592. and will make itself visible when it needs to display a tip.
  22593. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22594. methods.
  22595. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22596. otherwise the tooltip will be added to the given parent
  22597. component.
  22598. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22599. before a tooltip will be shown
  22600. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22601. */
  22602. TooltipWindow (Component* parentComponent = 0,
  22603. const int millisecondsBeforeTipAppears = 700);
  22604. /** Destructor. */
  22605. ~TooltipWindow();
  22606. /** Changes the time before the tip appears.
  22607. This lets you change the value that was set in the constructor.
  22608. */
  22609. void setMillisecondsBeforeTipAppears (const int newTimeMs = 700) throw();
  22610. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22611. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22612. methods.
  22613. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22614. */
  22615. enum ColourIds
  22616. {
  22617. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22618. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22619. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22620. };
  22621. juce_UseDebuggingNewOperator
  22622. private:
  22623. int millisecondsBeforeTipAppears;
  22624. int mouseX, mouseY, mouseClicks;
  22625. unsigned int lastCompChangeTime, lastHideTime;
  22626. Component* lastComponentUnderMouse;
  22627. bool changedCompsSinceShown;
  22628. String tipShowing, lastTipUnderMouse;
  22629. void paint (Graphics& g);
  22630. void mouseEnter (const MouseEvent& e);
  22631. void timerCallback();
  22632. static const String getTipFor (Component* const c);
  22633. void showFor (Component* const c, const String& tip);
  22634. void hide();
  22635. TooltipWindow (const TooltipWindow&);
  22636. const TooltipWindow& operator= (const TooltipWindow&);
  22637. };
  22638. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22639. /********* End of inlined file: juce_TooltipWindow.h *********/
  22640. class Button;
  22641. /**
  22642. Used to receive callbacks when a button is clicked.
  22643. @see Button::addButtonListener, Button::removeButtonListener
  22644. */
  22645. class JUCE_API ButtonListener
  22646. {
  22647. public:
  22648. /** Destructor. */
  22649. virtual ~ButtonListener() {}
  22650. /** Called when the button is clicked. */
  22651. virtual void buttonClicked (Button* button) = 0;
  22652. /** Called when the button's state changes. */
  22653. virtual void buttonStateChanged (Button*) {}
  22654. };
  22655. /**
  22656. A base class for buttons.
  22657. This contains all the logic for button behaviours such as enabling/disabling,
  22658. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22659. and radio groups, etc.
  22660. @see TextButton, DrawableButton, ToggleButton
  22661. */
  22662. class JUCE_API Button : public Component,
  22663. public SettableTooltipClient,
  22664. public ApplicationCommandManagerListener,
  22665. private KeyListener
  22666. {
  22667. protected:
  22668. /** Creates a button.
  22669. @param buttonName the text to put in the button (the component's name is also
  22670. initially set to this string, but these can be changed later
  22671. using the setName() and setButtonText() methods)
  22672. */
  22673. Button (const String& buttonName);
  22674. public:
  22675. /** Destructor. */
  22676. virtual ~Button();
  22677. /** Changes the button's text.
  22678. @see getButtonText
  22679. */
  22680. void setButtonText (const String& newText) throw();
  22681. /** Returns the text displayed in the button.
  22682. @see setButtonText
  22683. */
  22684. const String getButtonText() const throw() { return text; }
  22685. /** Returns true if the button is currently being held down by the mouse.
  22686. @see isOver
  22687. */
  22688. bool isDown() const throw();
  22689. /** Returns true if the mouse is currently over the button.
  22690. This will be also be true if the mouse is being held down.
  22691. @see isDown
  22692. */
  22693. bool isOver() const throw();
  22694. /** A button has an on/off state associated with it, and this changes that.
  22695. By default buttons are 'off' and for simple buttons that you click to perform
  22696. an action you won't change this. Toggle buttons, however will want to
  22697. change their state when turned on or off.
  22698. @param shouldBeOn whether to set the button's toggle state to be on or
  22699. off. If it's a member of a button group, this will
  22700. always try to turn it on, and to turn off any other
  22701. buttons in the group
  22702. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22703. the button will be repainted but no notification will
  22704. be sent
  22705. @see getToggleState, setRadioGroupId
  22706. */
  22707. void setToggleState (const bool shouldBeOn,
  22708. const bool sendChangeNotification);
  22709. /** Returns true if the button in 'on'.
  22710. By default buttons are 'off' and for simple buttons that you click to perform
  22711. an action you won't change this. Toggle buttons, however will want to
  22712. change their state when turned on or off.
  22713. @see setToggleState
  22714. */
  22715. bool getToggleState() const throw() { return isOn; }
  22716. /** This tells the button to automatically flip the toggle state when
  22717. the button is clicked.
  22718. If set to true, then before the clicked() callback occurs, the toggle-state
  22719. of the button is flipped.
  22720. */
  22721. void setClickingTogglesState (const bool shouldToggle) throw();
  22722. /** Returns true if this button is set to be an automatic toggle-button.
  22723. This returns the last value that was passed to setClickingTogglesState().
  22724. */
  22725. bool getClickingTogglesState() const throw();
  22726. /** Enables the button to act as a member of a mutually-exclusive group
  22727. of 'radio buttons'.
  22728. If the group ID is set to a non-zero number, then this button will
  22729. act as part of a group of buttons with the same ID, only one of
  22730. which can be 'on' at the same time. Note that when it's part of
  22731. a group, clicking a toggle-button that's 'on' won't turn it off.
  22732. To find other buttons with the same ID, this button will search through
  22733. its sibling components for ToggleButtons, so all the buttons for a
  22734. particular group must be placed inside the same parent component.
  22735. Set the group ID back to zero if you want it to act as a normal toggle
  22736. button again.
  22737. @see getRadioGroupId
  22738. */
  22739. void setRadioGroupId (const int newGroupId);
  22740. /** Returns the ID of the group to which this button belongs.
  22741. (See setRadioGroupId() for an explanation of this).
  22742. */
  22743. int getRadioGroupId() const throw() { return radioGroupId; }
  22744. /** Registers a listener to receive events when this button's state changes.
  22745. If the listener is already registered, this will not register it again.
  22746. @see removeButtonListener
  22747. */
  22748. void addButtonListener (ButtonListener* const newListener) throw();
  22749. /** Removes a previously-registered button listener
  22750. @see addButtonListener
  22751. */
  22752. void removeButtonListener (ButtonListener* const listener) throw();
  22753. /** Causes the button to act as if it's been clicked.
  22754. This will asynchronously make the button draw itself going down and up, and
  22755. will then call back the clicked() method as if mouse was clicked on it.
  22756. @see clicked
  22757. */
  22758. virtual void triggerClick();
  22759. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22760. When the button is pressed, it will use the given manager to trigger the
  22761. command ID.
  22762. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22763. before this button is. To disable the command triggering, call this method and
  22764. pass 0 for the parameters.
  22765. If generateTooltip is true, then the button's tooltip will be automatically
  22766. generated based on the name of this command and its current shortcut key.
  22767. @see addShortcut, getCommandID
  22768. */
  22769. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22770. const int commandID,
  22771. const bool generateTooltip);
  22772. /** Returns the command ID that was set by setCommandToTrigger().
  22773. */
  22774. int getCommandID() const throw() { return commandID; }
  22775. /** Assigns a shortcut key to trigger the button.
  22776. The button registers itself with its top-level parent component for keypresses.
  22777. Note that a different way of linking buttons to keypresses is by using the
  22778. setKeyPressToTrigger() method to invoke a command - the difference being that
  22779. setting a shortcut allows the button to be temporarily linked to a keypress
  22780. only while it's on-screen.
  22781. @see clearShortcuts
  22782. */
  22783. void addShortcut (const KeyPress& key);
  22784. /** Removes all key shortcuts that had been set for this button.
  22785. @see addShortcut
  22786. */
  22787. void clearShortcuts();
  22788. /** Returns true if the given keypress is a shortcut for this button.
  22789. @see addShortcut
  22790. */
  22791. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22792. /** Sets an auto-repeat speed for the button when it is held down.
  22793. (Auto-repeat is disabled by default).
  22794. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22795. triggering the next click. If this is zero, auto-repeat
  22796. is disabled
  22797. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22798. triggered
  22799. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22800. get faster, the longer the button is held down, up to the
  22801. minimum interval specified here
  22802. */
  22803. void setRepeatSpeed (const int initialDelayInMillisecs,
  22804. const int repeatDelayInMillisecs,
  22805. const int minimumDelayInMillisecs = -1) throw();
  22806. /** Sets whether the button click should happen when the mouse is pressed or released.
  22807. By default the button is only considered to have been clicked when the mouse is
  22808. released, but setting this to true will make it call the clicked() method as soon
  22809. as the button is pressed.
  22810. This is useful if the button is being used to show a pop-up menu, as it allows
  22811. the click to be used as a drag onto the menu.
  22812. */
  22813. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22814. /** Returns the number of milliseconds since the last time the button
  22815. went into the 'down' state.
  22816. */
  22817. uint32 getMillisecondsSinceButtonDown() const throw();
  22818. /** (overridden from Component to do special stuff). */
  22819. void setVisible (bool shouldBeVisible);
  22820. /** Sets the tooltip for this button.
  22821. @see TooltipClient, TooltipWindow
  22822. */
  22823. void setTooltip (const String& newTooltip);
  22824. // (implementation of the TooltipClient method)
  22825. const String getTooltip();
  22826. /** A combination of these flags are used by setConnectedEdges().
  22827. */
  22828. enum ConnectedEdgeFlags
  22829. {
  22830. ConnectedOnLeft = 1,
  22831. ConnectedOnRight = 2,
  22832. ConnectedOnTop = 4,
  22833. ConnectedOnBottom = 8
  22834. };
  22835. /** Hints about which edges of the button might be connected to adjoining buttons.
  22836. The value passed in is a bitwise combination of any of the values in the
  22837. ConnectedEdgeFlags enum.
  22838. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22839. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22840. without rounded corners on the edges that connect. It's only a hint, so the
  22841. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22842. button.
  22843. */
  22844. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22845. /** Returns the set of flags passed into setConnectedEdges(). */
  22846. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22847. /** Indicates whether the button adjoins another one on its left edge.
  22848. @see setConnectedEdges
  22849. */
  22850. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22851. /** Indicates whether the button adjoins another one on its right edge.
  22852. @see setConnectedEdges
  22853. */
  22854. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22855. /** Indicates whether the button adjoins another one on its top edge.
  22856. @see setConnectedEdges
  22857. */
  22858. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22859. /** Indicates whether the button adjoins another one on its bottom edge.
  22860. @see setConnectedEdges
  22861. */
  22862. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22863. /** Used by setState(). */
  22864. enum ButtonState
  22865. {
  22866. buttonNormal,
  22867. buttonOver,
  22868. buttonDown
  22869. };
  22870. /** Can be used to force the button into a particular state.
  22871. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22872. from happening.
  22873. The state that you set here will only last until it is automatically changed when the mouse
  22874. enters or exits the button, or the mouse-button is pressed or released.
  22875. */
  22876. void setState (const ButtonState newState);
  22877. juce_UseDebuggingNewOperator
  22878. protected:
  22879. /** This method is called when the button has been clicked.
  22880. Subclasses can override this to perform whatever they actions they need
  22881. to do.
  22882. Alternatively, a ButtonListener can be added to the button, and these listeners
  22883. will be called when the click occurs.
  22884. @see triggerClick
  22885. */
  22886. virtual void clicked();
  22887. /** This method is called when the button has been clicked.
  22888. By default it just calls clicked(), but you might want to override it to handle
  22889. things like clicking when a modifier key is pressed, etc.
  22890. @see ModifierKeys
  22891. */
  22892. virtual void clicked (const ModifierKeys& modifiers);
  22893. /** Subclasses should override this to actually paint the button's contents.
  22894. It's better to use this than the paint method, because it gives you information
  22895. about the over/down state of the button.
  22896. @param g the graphics context to use
  22897. @param isMouseOverButton true if the button is either in the 'over' or
  22898. 'down' state
  22899. @param isButtonDown true if the button should be drawn in the 'down' position
  22900. */
  22901. virtual void paintButton (Graphics& g,
  22902. bool isMouseOverButton,
  22903. bool isButtonDown) = 0;
  22904. /** Called when the button's up/down/over state changes.
  22905. Subclasses can override this if they need to do something special when the button
  22906. goes up or down.
  22907. @see isDown, isOver
  22908. */
  22909. virtual void buttonStateChanged();
  22910. /** @internal */
  22911. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22912. /** @internal */
  22913. void handleCommandMessage (int commandId);
  22914. /** @internal */
  22915. void mouseEnter (const MouseEvent& e);
  22916. /** @internal */
  22917. void mouseExit (const MouseEvent& e);
  22918. /** @internal */
  22919. void mouseDown (const MouseEvent& e);
  22920. /** @internal */
  22921. void mouseDrag (const MouseEvent& e);
  22922. /** @internal */
  22923. void mouseUp (const MouseEvent& e);
  22924. /** @internal */
  22925. bool keyPressed (const KeyPress& key);
  22926. /** @internal */
  22927. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22928. /** @internal */
  22929. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  22930. /** @internal */
  22931. void paint (Graphics& g);
  22932. /** @internal */
  22933. void parentHierarchyChanged();
  22934. /** @internal */
  22935. void focusGained (FocusChangeType cause);
  22936. /** @internal */
  22937. void focusLost (FocusChangeType cause);
  22938. /** @internal */
  22939. void enablementChanged();
  22940. /** @internal */
  22941. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22942. /** @internal */
  22943. void applicationCommandListChanged();
  22944. private:
  22945. Array <KeyPress> shortcuts;
  22946. Component* keySource;
  22947. String text;
  22948. SortedSet <void*> buttonListeners;
  22949. friend class InternalButtonRepeatTimer;
  22950. Timer* repeatTimer;
  22951. uint32 buttonPressTime, lastTimeCallbackTime;
  22952. ApplicationCommandManager* commandManagerToUse;
  22953. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22954. int radioGroupId, commandID, connectedEdgeFlags;
  22955. ButtonState buttonState;
  22956. bool isOn : 1;
  22957. bool clickTogglesState : 1;
  22958. bool needsToRelease : 1;
  22959. bool needsRepainting : 1;
  22960. bool isKeyDown : 1;
  22961. bool triggerOnMouseDown : 1;
  22962. bool generateTooltip : 1;
  22963. void repeatTimerCallback() throw();
  22964. Timer& getRepeatTimer() throw();
  22965. ButtonState updateState (const MouseEvent* const e) throw();
  22966. bool isShortcutPressed() const throw();
  22967. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22968. void flashButtonState() throw();
  22969. void sendClickMessage (const ModifierKeys& modifiers);
  22970. void sendStateMessage();
  22971. Button (const Button&);
  22972. const Button& operator= (const Button&);
  22973. };
  22974. #endif // __JUCE_BUTTON_JUCEHEADER__
  22975. /********* End of inlined file: juce_Button.h *********/
  22976. class ScrollBar;
  22977. /**
  22978. A class for receiving events from a ScrollBar.
  22979. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22980. method, and it will be called when the bar's position changes.
  22981. @see ScrollBar::addListener, ScrollBar::removeListener
  22982. */
  22983. class JUCE_API ScrollBarListener
  22984. {
  22985. public:
  22986. /** Destructor. */
  22987. virtual ~ScrollBarListener() {}
  22988. /** Called when a ScrollBar is moved.
  22989. @param scrollBarThatHasMoved the bar that has moved
  22990. @param newRangeStart the new range start of this bar
  22991. */
  22992. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22993. const double newRangeStart) = 0;
  22994. };
  22995. /**
  22996. A scrollbar component.
  22997. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22998. sets the range of values it can represent. Then you can use setCurrentRange() to
  22999. change the position and size of the scrollbar's 'thumb'.
  23000. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  23001. the user moves it, and you can use the getCurrentRangeStart() to find out where
  23002. they moved it to.
  23003. The scrollbar will adjust its own visibility according to whether its thumb size
  23004. allows it to actually be scrolled.
  23005. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  23006. instead of handling a scrollbar directly.
  23007. @see ScrollBarListener
  23008. */
  23009. class JUCE_API ScrollBar : public Component,
  23010. public AsyncUpdater,
  23011. private Timer
  23012. {
  23013. public:
  23014. /** Creates a Scrollbar.
  23015. @param isVertical whether it should be a vertical or horizontal bar
  23016. @param buttonsAreVisible whether to show the up/down or left/right buttons
  23017. */
  23018. ScrollBar (const bool isVertical,
  23019. const bool buttonsAreVisible = true);
  23020. /** Destructor. */
  23021. ~ScrollBar();
  23022. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  23023. bool isVertical() const throw() { return vertical; }
  23024. /** Changes the scrollbar's direction.
  23025. You'll also need to resize the bar appropriately - this just changes its internal
  23026. layout.
  23027. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  23028. */
  23029. void setOrientation (const bool shouldBeVertical) throw();
  23030. /** Shows or hides the scrollbar's buttons. */
  23031. void setButtonVisibility (const bool buttonsAreVisible);
  23032. /** Tells the scrollbar whether to make itself invisible when not needed.
  23033. The default behaviour is for a scrollbar to become invisible when the thumb
  23034. fills the whole of its range (i.e. when it can't be moved). Setting this
  23035. value to false forces the bar to always be visible.
  23036. */
  23037. void setAutoHide (const bool shouldHideWhenFullRange);
  23038. /** Sets the minimum and maximum values that the bar will move between.
  23039. The bar's thumb will always be constrained so that the top of the thumb
  23040. will be >= minimum, and the bottom of the thumb <= maximum.
  23041. @see setCurrentRange
  23042. */
  23043. void setRangeLimits (const double minimum,
  23044. const double maximum) throw();
  23045. /** Returns the lower value that the thumb can be set to.
  23046. This is the value set by setRangeLimits().
  23047. */
  23048. double getMinimumRangeLimit() const throw() { return minimum; }
  23049. /** Returns the upper value that the thumb can be set to.
  23050. This is the value set by setRangeLimits().
  23051. */
  23052. double getMaximumRangeLimit() const throw() { return maximum; }
  23053. /** Changes the position of the scrollbar's 'thumb'.
  23054. This sets both the position and size of the thumb - to just set the position without
  23055. changing the size, you can use setCurrentRangeStart().
  23056. If this method call actually changes the scrollbar's position, it will trigger an
  23057. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  23058. are registered.
  23059. @param newStart the top (or left) of the thumb, in the range
  23060. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  23061. value is beyond these limits, it will be clipped.
  23062. @param newSize the size of the thumb, such that
  23063. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  23064. size is beyond these limits, it will be clipped.
  23065. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  23066. */
  23067. void setCurrentRange (double newStart,
  23068. double newSize) throw();
  23069. /** Moves the bar's thumb position.
  23070. This will move the thumb position without changing the thumb size. Note
  23071. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  23072. If this method call actually changes the scrollbar's position, it will trigger an
  23073. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  23074. are registered.
  23075. @see setCurrentRange
  23076. */
  23077. void setCurrentRangeStart (double newStart) throw();
  23078. /** Returns the position of the top of the thumb.
  23079. @see setCurrentRangeStart
  23080. */
  23081. double getCurrentRangeStart() const throw() { return rangeStart; }
  23082. /** Returns the current size of the thumb.
  23083. @see setCurrentRange
  23084. */
  23085. double getCurrentRangeSize() const throw() { return rangeSize; }
  23086. /** Sets the amount by which the up and down buttons will move the bar.
  23087. The value here is in terms of the total range, and is added or subtracted
  23088. from the thumb position when the user clicks an up/down (or left/right) button.
  23089. */
  23090. void setSingleStepSize (const double newSingleStepSize) throw();
  23091. /** Moves the scrollbar by a number of single-steps.
  23092. This will move the bar by a multiple of its single-step interval (as
  23093. specified using the setSingleStepSize() method).
  23094. A positive value here will move the bar down or to the right, a negative
  23095. value moves it up or to the left.
  23096. */
  23097. void moveScrollbarInSteps (const int howManySteps) throw();
  23098. /** Moves the scroll bar up or down in pages.
  23099. This will move the bar by a multiple of its current thumb size, effectively
  23100. doing a page-up or down.
  23101. A positive value here will move the bar down or to the right, a negative
  23102. value moves it up or to the left.
  23103. */
  23104. void moveScrollbarInPages (const int howManyPages) throw();
  23105. /** Scrolls to the top (or left).
  23106. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  23107. */
  23108. void scrollToTop() throw();
  23109. /** Scrolls to the bottom (or right).
  23110. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  23111. */
  23112. void scrollToBottom() throw();
  23113. /** Changes the delay before the up and down buttons autorepeat when they are held
  23114. down.
  23115. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  23116. @see Button::setRepeatSpeed
  23117. */
  23118. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  23119. const int repeatDelayInMillisecs,
  23120. const int minimumDelayInMillisecs = -1) throw();
  23121. /** A set of colour IDs to use to change the colour of various aspects of the component.
  23122. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  23123. methods.
  23124. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  23125. */
  23126. enum ColourIds
  23127. {
  23128. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  23129. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  23130. 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. */
  23131. };
  23132. /** Registers a listener that will be called when the scrollbar is moved. */
  23133. void addListener (ScrollBarListener* const listener) throw();
  23134. /** Deregisters a previously-registered listener. */
  23135. void removeListener (ScrollBarListener* const listener) throw();
  23136. /** @internal */
  23137. bool keyPressed (const KeyPress& key);
  23138. /** @internal */
  23139. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23140. /** @internal */
  23141. void lookAndFeelChanged();
  23142. /** @internal */
  23143. void handleAsyncUpdate();
  23144. /** @internal */
  23145. void mouseDown (const MouseEvent& e);
  23146. /** @internal */
  23147. void mouseDrag (const MouseEvent& e);
  23148. /** @internal */
  23149. void mouseUp (const MouseEvent& e);
  23150. /** @internal */
  23151. void paint (Graphics& g);
  23152. /** @internal */
  23153. void resized();
  23154. juce_UseDebuggingNewOperator
  23155. private:
  23156. double minimum, maximum;
  23157. double rangeStart, rangeSize;
  23158. double singleStepSize, dragStartRange;
  23159. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  23160. int dragStartMousePos, lastMousePos;
  23161. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  23162. bool vertical, isDraggingThumb, alwaysVisible;
  23163. Button* upButton;
  23164. Button* downButton;
  23165. SortedSet <void*> listeners;
  23166. void updateThumbPosition() throw();
  23167. void timerCallback();
  23168. ScrollBar (const ScrollBar&);
  23169. const ScrollBar& operator= (const ScrollBar&);
  23170. };
  23171. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  23172. /********* End of inlined file: juce_ScrollBar.h *********/
  23173. /**
  23174. A Viewport is used to contain a larger child component, and allows the child
  23175. to be automatically scrolled around.
  23176. To use a Viewport, just create one and set the component that goes inside it
  23177. using the setViewedComponent() method. When the child component changes size,
  23178. the Viewport will adjust its scrollbars accordingly.
  23179. A subclass of the viewport can be created which will receive calls to its
  23180. visibleAreaChanged() method when the subcomponent changes position or size.
  23181. */
  23182. class JUCE_API Viewport : public Component,
  23183. private ComponentListener,
  23184. private ScrollBarListener
  23185. {
  23186. public:
  23187. /** Creates a Viewport.
  23188. The viewport is initially empty - use the setViewedComponent() method to
  23189. add a child component for it to manage.
  23190. */
  23191. Viewport (const String& componentName = String::empty);
  23192. /** Destructor. */
  23193. ~Viewport();
  23194. /** Sets the component that this viewport will contain and scroll around.
  23195. This will add the given component to this Viewport and position it at
  23196. (0, 0).
  23197. (Don't add or remove any child components directly using the normal
  23198. Component::addChildComponent() methods).
  23199. @param newViewedComponent the component to add to this viewport (this pointer
  23200. may be null). The component passed in will be deleted
  23201. by the Viewport when it's no longer needed
  23202. @see getViewedComponent
  23203. */
  23204. void setViewedComponent (Component* const newViewedComponent);
  23205. /** Returns the component that's currently being used inside the Viewport.
  23206. @see setViewedComponent
  23207. */
  23208. Component* getViewedComponent() const throw() { return contentComp; }
  23209. /** Changes the position of the viewed component.
  23210. The inner component will be moved so that the pixel at the top left of
  23211. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  23212. within the inner component.
  23213. This will update the scrollbars and might cause a call to visibleAreaChanged().
  23214. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  23215. */
  23216. void setViewPosition (const int xPixelsOffset,
  23217. const int yPixelsOffset);
  23218. /** Changes the view position as a proportion of the distance it can move.
  23219. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  23220. visible area in the top-left, and (1, 1) would put it as far down and
  23221. to the right as it's possible to go whilst keeping the child component
  23222. on-screen.
  23223. */
  23224. void setViewPositionProportionately (const double proportionX,
  23225. const double proportionY);
  23226. /** Returns the position within the child component of the top-left of its visible area.
  23227. @see getViewWidth, setViewPosition
  23228. */
  23229. int getViewPositionX() const throw() { return lastVX; }
  23230. /** Returns the position within the child component of the top-left of its visible area.
  23231. @see getViewHeight, setViewPosition
  23232. */
  23233. int getViewPositionY() const throw() { return lastVY; }
  23234. /** Returns the width of the visible area of the child component.
  23235. This may be less than the width of this Viewport if there's a vertical scrollbar
  23236. or if the child component is itself smaller.
  23237. */
  23238. int getViewWidth() const throw() { return lastVW; }
  23239. /** Returns the height of the visible area of the child component.
  23240. This may be less than the height of this Viewport if there's a horizontal scrollbar
  23241. or if the child component is itself smaller.
  23242. */
  23243. int getViewHeight() const throw() { return lastVH; }
  23244. /** Returns the width available within this component for the contents.
  23245. This will be the width of the viewport component minus the width of a
  23246. vertical scrollbar (if visible).
  23247. */
  23248. int getMaximumVisibleWidth() const throw();
  23249. /** Returns the height available within this component for the contents.
  23250. This will be the height of the viewport component minus the space taken up
  23251. by a horizontal scrollbar (if visible).
  23252. */
  23253. int getMaximumVisibleHeight() const throw();
  23254. /** Callback method that is called when the visible area changes.
  23255. This will be called when the visible area is moved either be scrolling or
  23256. by calls to setViewPosition(), etc.
  23257. */
  23258. virtual void visibleAreaChanged (int visibleX, int visibleY,
  23259. int visibleW, int visibleH);
  23260. /** Turns scrollbars on or off.
  23261. If set to false, the scrollbars won't ever appear. When true (the default)
  23262. they will appear only when needed.
  23263. */
  23264. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  23265. const bool showHorizontalScrollbarIfNeeded);
  23266. /** True if the vertical scrollbar is enabled.
  23267. @see setScrollBarsShown
  23268. */
  23269. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  23270. /** True if the horizontal scrollbar is enabled.
  23271. @see setScrollBarsShown
  23272. */
  23273. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  23274. /** Changes the width of the scrollbars.
  23275. If this isn't specified, the default width from the LookAndFeel class will be used.
  23276. @see LookAndFeel::getDefaultScrollbarWidth
  23277. */
  23278. void setScrollBarThickness (const int thickness);
  23279. /** Returns the thickness of the scrollbars.
  23280. @see setScrollBarThickness
  23281. */
  23282. int getScrollBarThickness() const throw();
  23283. /** Changes the distance that a single-step click on a scrollbar button
  23284. will move the viewport.
  23285. */
  23286. void setSingleStepSizes (const int stepX, const int stepY);
  23287. /** Shows or hides the buttons on any scrollbars that are used.
  23288. @see ScrollBar::setButtonVisibility
  23289. */
  23290. void setScrollBarButtonVisibility (const bool buttonsVisible);
  23291. /** Returns a pointer to the scrollbar component being used.
  23292. Handy if you need to customise the bar somehow.
  23293. */
  23294. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  23295. /** Returns a pointer to the scrollbar component being used.
  23296. Handy if you need to customise the bar somehow.
  23297. */
  23298. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  23299. juce_UseDebuggingNewOperator
  23300. /** @internal */
  23301. void resized();
  23302. /** @internal */
  23303. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  23304. /** @internal */
  23305. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23306. /** @internal */
  23307. bool keyPressed (const KeyPress& key);
  23308. /** @internal */
  23309. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  23310. /** @internal */
  23311. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23312. private:
  23313. Component* contentComp;
  23314. int lastVX, lastVY, lastVW, lastVH;
  23315. int scrollBarThickness;
  23316. int singleStepX, singleStepY;
  23317. bool showHScrollbar, showVScrollbar;
  23318. Component* contentHolder;
  23319. ScrollBar* verticalScrollBar;
  23320. ScrollBar* horizontalScrollBar;
  23321. void updateVisibleRegion();
  23322. Viewport (const Viewport&);
  23323. const Viewport& operator= (const Viewport&);
  23324. };
  23325. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  23326. /********* End of inlined file: juce_Viewport.h *********/
  23327. /**
  23328. A panel that holds a list of PropertyComponent objects.
  23329. This panel displays a list of PropertyComponents, and allows them to be organised
  23330. into collapsible sections.
  23331. To use, simply create one of these and add your properties to it with addProperties()
  23332. or addSection().
  23333. @see PropertyComponent
  23334. */
  23335. class JUCE_API PropertyPanel : public Component
  23336. {
  23337. public:
  23338. /** Creates an empty property panel. */
  23339. PropertyPanel();
  23340. /** Destructor. */
  23341. ~PropertyPanel();
  23342. /** Deletes all property components from the panel.
  23343. */
  23344. void clear();
  23345. /** Adds a set of properties to the panel.
  23346. The components in the list will be owned by this object and will be automatically
  23347. deleted later on when no longer needed.
  23348. These properties are added without them being inside a named section. If you
  23349. want them to be kept together in a collapsible section, use addSection() instead.
  23350. */
  23351. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  23352. /** Adds a set of properties to the panel.
  23353. These properties are added at the bottom of the list, under a section heading with
  23354. a plus/minus button that allows it to be opened and closed.
  23355. The components in the list will be owned by this object and will be automatically
  23356. deleted later on when no longer needed.
  23357. To add properies without them being in a section, use addProperties().
  23358. */
  23359. void addSection (const String& sectionTitle,
  23360. const Array <PropertyComponent*>& newPropertyComponents,
  23361. const bool shouldSectionInitiallyBeOpen = true);
  23362. /** Calls the refresh() method of all PropertyComponents in the panel */
  23363. void refreshAll() const;
  23364. /** Returns a list of all the names of sections in the panel.
  23365. These are the sections that have been added with addSection().
  23366. */
  23367. const StringArray getSectionNames() const;
  23368. /** Returns true if the section at this index is currently open.
  23369. The index is from 0 up to the number of items returned by getSectionNames().
  23370. */
  23371. bool isSectionOpen (const int sectionIndex) const;
  23372. /** Opens or closes one of the sections.
  23373. The index is from 0 up to the number of items returned by getSectionNames().
  23374. */
  23375. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  23376. /** Enables or disables one of the sections.
  23377. The index is from 0 up to the number of items returned by getSectionNames().
  23378. */
  23379. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  23380. /** Saves the current state of open/closed sections so it can be restored later.
  23381. The caller is responsible for deleting the object that is returned.
  23382. To restore this state, use restoreOpennessState().
  23383. @see restoreOpennessState
  23384. */
  23385. XmlElement* getOpennessState() const;
  23386. /** Restores a previously saved arrangement of open/closed sections.
  23387. This will try to restore a snapshot of the panel's state that was created by
  23388. the getOpennessState() method. If any of the sections named in the original
  23389. XML aren't present, they will be ignored.
  23390. @see getOpennessState
  23391. */
  23392. void restoreOpennessState (const XmlElement& newState);
  23393. /** Sets a message to be displayed when there are no properties in the panel.
  23394. The default message is "nothing selected".
  23395. */
  23396. void setMessageWhenEmpty (const String& newMessage);
  23397. /** Returns the message that is displayed when there are no properties.
  23398. @see setMessageWhenEmpty
  23399. */
  23400. const String& getMessageWhenEmpty() const throw();
  23401. /** @internal */
  23402. void paint (Graphics& g);
  23403. /** @internal */
  23404. void resized();
  23405. juce_UseDebuggingNewOperator
  23406. private:
  23407. Viewport* viewport;
  23408. Component* propertyHolderComponent;
  23409. String messageWhenEmpty;
  23410. void updatePropHolderLayout() const;
  23411. void updatePropHolderLayout (const int width) const;
  23412. };
  23413. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  23414. /********* End of inlined file: juce_PropertyPanel.h *********/
  23415. /**
  23416. A type of UI component that displays the parameters of an AudioProcessor as
  23417. a simple list of sliders.
  23418. This can be used for showing an editor for a processor that doesn't supply
  23419. its own custom editor.
  23420. @see AudioProcessor
  23421. */
  23422. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  23423. {
  23424. public:
  23425. GenericAudioProcessorEditor (AudioProcessor* const owner);
  23426. ~GenericAudioProcessorEditor();
  23427. void paint (Graphics& g);
  23428. void resized();
  23429. juce_UseDebuggingNewOperator
  23430. private:
  23431. PropertyPanel* panel;
  23432. };
  23433. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23434. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  23435. #endif
  23436. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23437. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  23438. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23439. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23440. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  23441. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23442. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23443. /********* Start of inlined file: juce_AudioSource.h *********/
  23444. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23445. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  23446. /**
  23447. Used by AudioSource::getNextAudioBlock().
  23448. */
  23449. struct JUCE_API AudioSourceChannelInfo
  23450. {
  23451. /** The destination buffer to fill with audio data.
  23452. When the AudioSource::getNextAudioBlock() method is called, the active section
  23453. of this buffer should be filled with whatever output the source produces.
  23454. Only the samples specified by the startSample and numSamples members of this structure
  23455. should be affected by the call.
  23456. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  23457. method can be treated as the input if the source is performing some kind of filter operation,
  23458. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  23459. a handy way of doing this.
  23460. The number of channels in the buffer could be anything, so the AudioSource
  23461. must cope with this in whatever way is appropriate for its function.
  23462. */
  23463. AudioSampleBuffer* buffer;
  23464. /** The first sample in the buffer from which the callback is expected
  23465. to write data. */
  23466. int startSample;
  23467. /** The number of samples in the buffer which the callback is expected to
  23468. fill with data. */
  23469. int numSamples;
  23470. /** Convenient method to clear the buffer if the source is not producing any data. */
  23471. void clearActiveBufferRegion() const
  23472. {
  23473. if (buffer != 0)
  23474. buffer->clear (startSample, numSamples);
  23475. }
  23476. };
  23477. /**
  23478. Base class for objects that can produce a continuous stream of audio.
  23479. @see AudioFormatReaderSource, ResamplingAudioSource
  23480. */
  23481. class JUCE_API AudioSource
  23482. {
  23483. protected:
  23484. /** Creates an AudioSource. */
  23485. AudioSource() throw() {}
  23486. public:
  23487. /** Destructor. */
  23488. virtual ~AudioSource() {}
  23489. /** Tells the source to prepare for playing.
  23490. The source can use this opportunity to initialise anything it needs to.
  23491. Note that this method could be called more than once in succession without
  23492. a matching call to releaseResources(), so make sure your code is robust and
  23493. can handle that kind of situation.
  23494. @param samplesPerBlockExpected the number of samples that the source
  23495. will be expected to supply each time its
  23496. getNextAudioBlock() method is called. This
  23497. number may vary slightly, because it will be dependent
  23498. on audio hardware callbacks, and these aren't
  23499. guaranteed to always use a constant block size, so
  23500. the source should be able to cope with small variations.
  23501. @param sampleRate the sample rate that the output will be used at - this
  23502. is needed by sources such as tone generators.
  23503. @see releaseResources, getNextAudioBlock
  23504. */
  23505. virtual void prepareToPlay (int samplesPerBlockExpected,
  23506. double sampleRate) = 0;
  23507. /** Allows the source to release anything it no longer needs after playback has stopped.
  23508. This will be called when the source is no longer going to have its getNextAudioBlock()
  23509. method called, so it should release any spare memory, etc. that it might have
  23510. allocated during the prepareToPlay() call.
  23511. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23512. releaseResources(), and it may be called more than once in succession, so make sure your
  23513. code is robust and doesn't make any assumptions about when it will be called.
  23514. @see prepareToPlay, getNextAudioBlock
  23515. */
  23516. virtual void releaseResources() = 0;
  23517. /** Called repeatedly to fetch subsequent blocks of audio data.
  23518. After calling the prepareToPlay() method, this callback will be made each
  23519. time the audio playback hardware (or whatever other destination the audio
  23520. data is going to) needs another block of data.
  23521. It will generally be called on a high-priority system thread, or possibly even
  23522. an interrupt, so be careful not to do too much work here, as that will cause
  23523. audio glitches!
  23524. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23525. */
  23526. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23527. };
  23528. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23529. /********* End of inlined file: juce_AudioSource.h *********/
  23530. /**
  23531. A type of AudioSource which can be repositioned.
  23532. The basic AudioSource just streams continuously with no idea of a current
  23533. time or length, so the PositionableAudioSource is used for a finite stream
  23534. that has a current read position.
  23535. @see AudioSource, AudioTransportSource
  23536. */
  23537. class JUCE_API PositionableAudioSource : public AudioSource
  23538. {
  23539. protected:
  23540. /** Creates the PositionableAudioSource. */
  23541. PositionableAudioSource() throw() {}
  23542. public:
  23543. /** Destructor */
  23544. ~PositionableAudioSource() {}
  23545. /** Tells the stream to move to a new position.
  23546. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23547. should return samples from this position.
  23548. Note that this may be called on a different thread to getNextAudioBlock(),
  23549. so the subclass should make sure it's synchronised.
  23550. */
  23551. virtual void setNextReadPosition (int newPosition) = 0;
  23552. /** Returns the position from which the next block will be returned.
  23553. @see setNextReadPosition
  23554. */
  23555. virtual int getNextReadPosition() const = 0;
  23556. /** Returns the total length of the stream (in samples). */
  23557. virtual int getTotalLength() const = 0;
  23558. /** Returns true if this source is actually playing in a loop. */
  23559. virtual bool isLooping() const = 0;
  23560. };
  23561. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23562. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23563. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23564. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23565. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23566. class AudioFormat;
  23567. /**
  23568. Reads samples from an audio file stream.
  23569. A subclass that reads a specific type of audio format will be created by
  23570. an AudioFormat object.
  23571. @see AudioFormat, AudioFormatWriter
  23572. */
  23573. class JUCE_API AudioFormatReader
  23574. {
  23575. protected:
  23576. /** Creates an AudioFormatReader object.
  23577. @param sourceStream the stream to read from - this will be deleted
  23578. by this object when it is no longer needed. (Some
  23579. specialised readers might not use this parameter and
  23580. can leave it as 0).
  23581. @param formatName the description that will be returned by the getFormatName()
  23582. method
  23583. */
  23584. AudioFormatReader (InputStream* const sourceStream,
  23585. const String& formatName);
  23586. public:
  23587. /** Destructor. */
  23588. virtual ~AudioFormatReader();
  23589. /** Returns a description of what type of format this is.
  23590. E.g. "AIFF"
  23591. */
  23592. const String getFormatName() const throw() { return formatName; }
  23593. /** Reads samples from the stream.
  23594. @param destSamples an array of buffers into which the sample data for each
  23595. channel will be written.
  23596. If the format is fixed-point, each channel will be written
  23597. as an array of 32-bit signed integers using the full
  23598. range -0x80000000 to 0x7fffffff, regardless of the source's
  23599. bit-depth. If it is a floating-point format, you should cast
  23600. the resulting array to a (float**) to get the values (in the
  23601. range -1.0 to 1.0 or beyond)
  23602. If the format is stereo, then destSamples[0] is the left channel
  23603. data, and destSamples[1] is the right channel.
  23604. The numDestChannels parameter indicates how many pointers this array
  23605. contains, but some of these pointers can be null if you don't want to
  23606. read data for some of the channels
  23607. @param numDestChannels the number of array elements in the destChannels array
  23608. @param startSampleInSource the position in the audio file or stream at which the samples
  23609. should be read, as a number of samples from the start of the
  23610. stream. It's ok for this to be beyond the start or end of the
  23611. available data - any samples that are out-of-range will be returned
  23612. as zeros.
  23613. @param numSamplesToRead the number of samples to read. If this is greater than the number
  23614. of samples that the file or stream contains. the result will be padded
  23615. with zeros
  23616. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  23617. for some of the channels that you pass in, then they should be filled with
  23618. copies of valid source channels.
  23619. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  23620. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  23621. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  23622. was false, then only the first channel would be filled with the file's contents, and
  23623. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  23624. from a stereo file, then the last 3 would all end up with copies of the same data.
  23625. @returns true if the operation succeeded, false if there was an error. Note
  23626. that reading sections of data beyond the extent of the stream isn't an
  23627. error - the reader should just return zeros for these regions
  23628. @see readMaxLevels
  23629. */
  23630. bool read (int** destSamples,
  23631. int numDestChannels,
  23632. int64 startSampleInSource,
  23633. int numSamplesToRead,
  23634. const bool fillLeftoverChannelsWithCopies);
  23635. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23636. This will read a block of samples from the stream, and measure the
  23637. highest and lowest sample levels from the channels in that section, returning
  23638. these as normalised floating-point levels.
  23639. @param startSample the offset into the audio stream to start reading from. It's
  23640. ok for this to be beyond the start or end of the stream.
  23641. @param numSamples how many samples to read
  23642. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23643. @param highestLeft on return, this is the highest absolute sample from the left channel
  23644. @param lowestRight on return, this is the lowest absolute sample from the right
  23645. channel (if there is one)
  23646. @param highestRight on return, this is the highest absolute sample from the right
  23647. channel (if there is one)
  23648. @see read
  23649. */
  23650. virtual void readMaxLevels (int64 startSample,
  23651. int64 numSamples,
  23652. float& lowestLeft,
  23653. float& highestLeft,
  23654. float& lowestRight,
  23655. float& highestRight);
  23656. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23657. This will read from the source, either forwards or backwards between two sample
  23658. positions, until it finds a sample whose magnitude lies between two specified levels.
  23659. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23660. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23661. points when you're searching for a continuous range of samples
  23662. @param startSample the first sample to look at
  23663. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23664. the search will go backwards
  23665. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23666. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23667. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23668. of this many consecutive samples, all of which lie
  23669. within the target range. When it finds such a sequence,
  23670. it returns the position of the first in-range sample
  23671. it found (i.e. the earliest one if scanning forwards, the
  23672. latest one if scanning backwards)
  23673. */
  23674. int64 searchForLevel (int64 startSample,
  23675. int64 numSamplesToSearch,
  23676. const double magnitudeRangeMinimum,
  23677. const double magnitudeRangeMaximum,
  23678. const int minimumConsecutiveSamples);
  23679. /** The sample-rate of the stream. */
  23680. double sampleRate;
  23681. /** The number of bits per sample, e.g. 16, 24, 32. */
  23682. unsigned int bitsPerSample;
  23683. /** The total number of samples in the audio stream. */
  23684. int64 lengthInSamples;
  23685. /** The total number of channels in the audio stream. */
  23686. unsigned int numChannels;
  23687. /** Indicates whether the data is floating-point or fixed. */
  23688. bool usesFloatingPointData;
  23689. /** A set of metadata values that the reader has pulled out of the stream.
  23690. Exactly what these values are depends on the format, so you can
  23691. check out the format implementation code to see what kind of stuff
  23692. they understand.
  23693. */
  23694. StringPairArray metadataValues;
  23695. /** The input stream, for use by subclasses. */
  23696. InputStream* input;
  23697. /** Subclasses must implement this method to perform the low-level read operation.
  23698. Callers should use read() instead of calling this directly.
  23699. @param destSamples the array of destination buffers to fill. Some of these
  23700. pointers may be null
  23701. @param numDestChannels the number of items in the destSamples array. This
  23702. value is guaranteed not to be greater than the number of
  23703. channels that this reader object contains
  23704. @param startOffsetInDestBuffer the number of samples from the start of the
  23705. dest data at which to begin writing
  23706. @param startSampleInFile the number of samples into the source data at which
  23707. to begin reading. This value is guaranteed to be >= 0.
  23708. @param numSamples the number of samples to read
  23709. */
  23710. virtual bool readSamples (int** destSamples,
  23711. int numDestChannels,
  23712. int startOffsetInDestBuffer,
  23713. int64 startSampleInFile,
  23714. int numSamples) = 0;
  23715. juce_UseDebuggingNewOperator
  23716. private:
  23717. String formatName;
  23718. AudioFormatReader (const AudioFormatReader&);
  23719. const AudioFormatReader& operator= (const AudioFormatReader&);
  23720. };
  23721. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23722. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23723. /**
  23724. A type of AudioSource that will read from an AudioFormatReader.
  23725. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23726. */
  23727. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23728. {
  23729. public:
  23730. /** Creates an AudioFormatReaderSource for a given reader.
  23731. @param sourceReader the reader to use as the data source
  23732. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23733. when this object is deleted; if false it will be
  23734. left up to the caller to manage its lifetime
  23735. */
  23736. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23737. const bool deleteReaderWhenThisIsDeleted);
  23738. /** Destructor. */
  23739. ~AudioFormatReaderSource();
  23740. /** Toggles loop-mode.
  23741. If set to true, it will continuously loop the input source. If false,
  23742. it will just emit silence after the source has finished.
  23743. @see isLooping
  23744. */
  23745. void setLooping (const bool shouldLoop) throw();
  23746. /** Returns whether loop-mode is turned on or not. */
  23747. bool isLooping() const { return looping; }
  23748. /** Returns the reader that's being used. */
  23749. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23750. /** Implementation of the AudioSource method. */
  23751. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23752. /** Implementation of the AudioSource method. */
  23753. void releaseResources();
  23754. /** Implementation of the AudioSource method. */
  23755. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23756. /** Implements the PositionableAudioSource method. */
  23757. void setNextReadPosition (int newPosition);
  23758. /** Implements the PositionableAudioSource method. */
  23759. int getNextReadPosition() const;
  23760. /** Implements the PositionableAudioSource method. */
  23761. int getTotalLength() const;
  23762. juce_UseDebuggingNewOperator
  23763. private:
  23764. AudioFormatReader* reader;
  23765. bool deleteReader;
  23766. int volatile nextPlayPos;
  23767. bool volatile looping;
  23768. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23769. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23770. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23771. };
  23772. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23773. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23774. #endif
  23775. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23776. #endif
  23777. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23778. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23779. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23780. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23781. /**
  23782. Wrapper class to continuously stream audio from an audio source to an
  23783. AudioIODevice.
  23784. This object acts as an AudioIODeviceCallback, so can be attached to an
  23785. output device, and will stream audio from an AudioSource.
  23786. */
  23787. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23788. {
  23789. public:
  23790. /** Creates an empty AudioSourcePlayer. */
  23791. AudioSourcePlayer();
  23792. /** Destructor.
  23793. Make sure this object isn't still being used by an AudioIODevice before
  23794. deleting it!
  23795. */
  23796. virtual ~AudioSourcePlayer();
  23797. /** Changes the current audio source to play from.
  23798. If the source passed in is already being used, this method will do nothing.
  23799. If the source is not null, its prepareToPlay() method will be called
  23800. before it starts being used for playback.
  23801. If there's another source currently playing, its releaseResources() method
  23802. will be called after it has been swapped for the new one.
  23803. @param newSource the new source to use - this will NOT be deleted
  23804. by this object when no longer needed, so it's the
  23805. caller's responsibility to manage it.
  23806. */
  23807. void setSource (AudioSource* newSource);
  23808. /** Returns the source that's playing.
  23809. May return 0 if there's no source.
  23810. */
  23811. AudioSource* getCurrentSource() const throw() { return source; }
  23812. /** Sets a gain to apply to the audio data. */
  23813. void setGain (const float newGain) throw();
  23814. /** Implementation of the AudioIODeviceCallback method. */
  23815. void audioDeviceIOCallback (const float** inputChannelData,
  23816. int totalNumInputChannels,
  23817. float** outputChannelData,
  23818. int totalNumOutputChannels,
  23819. int numSamples);
  23820. /** Implementation of the AudioIODeviceCallback method. */
  23821. void audioDeviceAboutToStart (AudioIODevice* device);
  23822. /** Implementation of the AudioIODeviceCallback method. */
  23823. void audioDeviceStopped();
  23824. juce_UseDebuggingNewOperator
  23825. private:
  23826. CriticalSection readLock;
  23827. AudioSource* source;
  23828. double sampleRate;
  23829. int bufferSize;
  23830. float* channels [128];
  23831. float* outputChans [128];
  23832. const float* inputChans [128];
  23833. AudioSampleBuffer tempBuffer;
  23834. float lastGain, gain;
  23835. AudioSourcePlayer (const AudioSourcePlayer&);
  23836. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23837. };
  23838. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23839. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23840. #endif
  23841. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23842. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23843. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23844. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23845. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23846. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23847. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23848. /**
  23849. An AudioSource which takes another source as input, and buffers it using a thread.
  23850. Create this as a wrapper around another thread, and it will read-ahead with
  23851. a background thread to smooth out playback. You can either create one of these
  23852. directly, or use it indirectly using an AudioTransportSource.
  23853. @see PositionableAudioSource, AudioTransportSource
  23854. */
  23855. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23856. {
  23857. public:
  23858. /** Creates a BufferingAudioSource.
  23859. @param source the input source to read from
  23860. @param deleteSourceWhenDeleted if true, then the input source object will
  23861. be deleted when this object is deleted
  23862. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23863. */
  23864. BufferingAudioSource (PositionableAudioSource* source,
  23865. const bool deleteSourceWhenDeleted,
  23866. int numberOfSamplesToBuffer);
  23867. /** Destructor.
  23868. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23869. flag was set in the constructor.
  23870. */
  23871. ~BufferingAudioSource();
  23872. /** Implementation of the AudioSource method. */
  23873. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23874. /** Implementation of the AudioSource method. */
  23875. void releaseResources();
  23876. /** Implementation of the AudioSource method. */
  23877. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23878. /** Implements the PositionableAudioSource method. */
  23879. void setNextReadPosition (int newPosition);
  23880. /** Implements the PositionableAudioSource method. */
  23881. int getNextReadPosition() const;
  23882. /** Implements the PositionableAudioSource method. */
  23883. int getTotalLength() const { return source->getTotalLength(); }
  23884. /** Implements the PositionableAudioSource method. */
  23885. bool isLooping() const { return source->isLooping(); }
  23886. juce_UseDebuggingNewOperator
  23887. private:
  23888. PositionableAudioSource* source;
  23889. bool deleteSourceWhenDeleted;
  23890. int numberOfSamplesToBuffer;
  23891. AudioSampleBuffer buffer;
  23892. CriticalSection bufferStartPosLock;
  23893. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23894. bool wasSourceLooping;
  23895. double volatile sampleRate;
  23896. friend class SharedBufferingAudioSourceThread;
  23897. bool readNextBufferChunk();
  23898. void readBufferSection (int start, int length, int bufferOffset);
  23899. BufferingAudioSource (const BufferingAudioSource&);
  23900. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23901. };
  23902. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23903. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23904. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23905. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23906. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23907. /**
  23908. A type of AudioSource that takes an input source and changes its sample rate.
  23909. @see AudioSource
  23910. */
  23911. class JUCE_API ResamplingAudioSource : public AudioSource
  23912. {
  23913. public:
  23914. /** Creates a ResamplingAudioSource for a given input source.
  23915. @param inputSource the input source to read from
  23916. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23917. this object is deleted
  23918. */
  23919. ResamplingAudioSource (AudioSource* const inputSource,
  23920. const bool deleteInputWhenDeleted);
  23921. /** Destructor. */
  23922. ~ResamplingAudioSource();
  23923. /** Changes the resampling ratio.
  23924. (This value can be changed at any time, even while the source is running).
  23925. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23926. values will speed it up; lower values will slow it
  23927. down. The ratio must be greater than 0
  23928. */
  23929. void setResamplingRatio (const double samplesInPerOutputSample);
  23930. /** Returns the current resampling ratio.
  23931. This is the value that was set by setResamplingRatio().
  23932. */
  23933. double getResamplingRatio() const throw() { return ratio; }
  23934. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23935. void releaseResources();
  23936. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23937. juce_UseDebuggingNewOperator
  23938. private:
  23939. AudioSource* const input;
  23940. const bool deleteInputWhenDeleted;
  23941. double ratio, lastRatio;
  23942. AudioSampleBuffer buffer;
  23943. int bufferPos, sampsInBuffer;
  23944. double subSampleOffset;
  23945. double coefficients[6];
  23946. CriticalSection ratioLock;
  23947. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23948. void createLowPass (const double proportionalRate);
  23949. struct FilterState
  23950. {
  23951. double x1, x2, y1, y2;
  23952. };
  23953. FilterState filterStates[2];
  23954. void resetFilters();
  23955. void applyFilter (float* samples, int num, FilterState& fs);
  23956. ResamplingAudioSource (const ResamplingAudioSource&);
  23957. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23958. };
  23959. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23960. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23961. /**
  23962. An AudioSource that takes a PositionableAudioSource and allows it to be
  23963. played, stopped, started, etc.
  23964. This can also be told use a buffer and background thread to read ahead, and
  23965. if can correct for different sample-rates.
  23966. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23967. to control playback of an audio file.
  23968. @see AudioSource, AudioSourcePlayer
  23969. */
  23970. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23971. public ChangeBroadcaster
  23972. {
  23973. public:
  23974. /** Creates an AudioTransportSource.
  23975. After creating one of these, use the setSource() method to select an input source.
  23976. */
  23977. AudioTransportSource();
  23978. /** Destructor. */
  23979. ~AudioTransportSource();
  23980. /** Sets the reader that is being used as the input source.
  23981. This will stop playback, reset the position to 0 and change to the new reader.
  23982. The source passed in will not be deleted by this object, so must be managed by
  23983. the caller.
  23984. @param newSource the new input source to use. This may be zero
  23985. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23986. is zero, no reading ahead will be done; if it's
  23987. greater than zero, a BufferingAudioSource will be used
  23988. to do the reading-ahead
  23989. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23990. rate of the source, and playback will be sample-rate
  23991. adjusted to maintain playback at the correct pitch. If
  23992. this is 0, no sample-rate adjustment will be performed
  23993. */
  23994. void setSource (PositionableAudioSource* const newSource,
  23995. int readAheadBufferSize = 0,
  23996. double sourceSampleRateToCorrectFor = 0.0);
  23997. /** Changes the current playback position in the source stream.
  23998. The next time the getNextAudioBlock() method is called, this
  23999. is the time from which it'll read data.
  24000. @see getPosition
  24001. */
  24002. void setPosition (double newPosition);
  24003. /** Returns the position that the next data block will be read from
  24004. This is a time in seconds.
  24005. */
  24006. double getCurrentPosition() const;
  24007. /** Returns true if the player has stopped because its input stream ran out of data.
  24008. */
  24009. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  24010. /** Starts playing (if a source has been selected).
  24011. If it starts playing, this will send a message to any ChangeListeners
  24012. that are registered with this object.
  24013. */
  24014. void start();
  24015. /** Stops playing.
  24016. If it's actually playing, this will send a message to any ChangeListeners
  24017. that are registered with this object.
  24018. */
  24019. void stop();
  24020. /** Returns true if it's currently playing. */
  24021. bool isPlaying() const throw() { return playing; }
  24022. /** Changes the gain to apply to the output.
  24023. @param newGain a factor by which to multiply the outgoing samples,
  24024. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  24025. */
  24026. void setGain (const float newGain) throw();
  24027. /** Returns the current gain setting.
  24028. @see setGain
  24029. */
  24030. float getGain() const throw() { return gain; }
  24031. /** Implementation of the AudioSource method. */
  24032. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24033. /** Implementation of the AudioSource method. */
  24034. void releaseResources();
  24035. /** Implementation of the AudioSource method. */
  24036. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24037. /** Implements the PositionableAudioSource method. */
  24038. void setNextReadPosition (int newPosition);
  24039. /** Implements the PositionableAudioSource method. */
  24040. int getNextReadPosition() const;
  24041. /** Implements the PositionableAudioSource method. */
  24042. int getTotalLength() const;
  24043. /** Implements the PositionableAudioSource method. */
  24044. bool isLooping() const;
  24045. juce_UseDebuggingNewOperator
  24046. private:
  24047. PositionableAudioSource* source;
  24048. ResamplingAudioSource* resamplerSource;
  24049. BufferingAudioSource* bufferingSource;
  24050. PositionableAudioSource* positionableSource;
  24051. AudioSource* masterSource;
  24052. CriticalSection callbackLock;
  24053. float volatile gain, lastGain;
  24054. bool volatile playing, stopped;
  24055. double sampleRate, sourceSampleRate;
  24056. int blockSize, readAheadBufferSize;
  24057. bool isPrepared, inputStreamEOF;
  24058. AudioTransportSource (const AudioTransportSource&);
  24059. const AudioTransportSource& operator= (const AudioTransportSource&);
  24060. };
  24061. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24062. /********* End of inlined file: juce_AudioTransportSource.h *********/
  24063. #endif
  24064. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24065. #endif
  24066. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24067. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  24068. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24069. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24070. /**
  24071. An AudioSource that takes the audio from another source, and re-maps its
  24072. input and output channels to a different arrangement.
  24073. You can use this to increase or decrease the number of channels that an
  24074. audio source uses, or to re-order those channels.
  24075. Call the reset() method before using it to set up a default mapping, and then
  24076. the setInputChannelMapping() and setOutputChannelMapping() methods to
  24077. create an appropriate mapping, otherwise no channels will be connected and
  24078. it'll produce silence.
  24079. @see AudioSource
  24080. */
  24081. class ChannelRemappingAudioSource : public AudioSource
  24082. {
  24083. public:
  24084. /** Creates a remapping source that will pass on audio from the given input.
  24085. @param source the input source to use. Make sure that this doesn't
  24086. get deleted before the ChannelRemappingAudioSource object
  24087. @param deleteSourceWhenDeleted if true, the input source will be deleted
  24088. when this object is deleted, if false, the caller is
  24089. responsible for its deletion
  24090. */
  24091. ChannelRemappingAudioSource (AudioSource* const source,
  24092. const bool deleteSourceWhenDeleted);
  24093. /** Destructor. */
  24094. ~ChannelRemappingAudioSource();
  24095. /** Specifies a number of channels that this audio source must produce from its
  24096. getNextAudioBlock() callback.
  24097. */
  24098. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  24099. /** Clears any mapped channels.
  24100. After this, no channels are mapped, so this object will produce silence. Create
  24101. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  24102. */
  24103. void clearAllMappings() throw();
  24104. /** Creates an input channel mapping.
  24105. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  24106. data will be sent to destChannelIndex of our input source.
  24107. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  24108. source specified when this object was created).
  24109. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  24110. during our getNextAudioBlock() callback
  24111. */
  24112. void setInputChannelMapping (const int destChannelIndex,
  24113. const int sourceChannelIndex) throw();
  24114. /** Creates an output channel mapping.
  24115. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  24116. our input audio source will be copied to channel destChannelIndex of the final buffer.
  24117. @param sourceChannelIndex the index of an output channel coming from our input audio source
  24118. (i.e. the source specified when this object was created).
  24119. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  24120. during our getNextAudioBlock() callback
  24121. */
  24122. void setOutputChannelMapping (const int sourceChannelIndex,
  24123. const int destChannelIndex) throw();
  24124. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  24125. our input audio source.
  24126. */
  24127. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  24128. /** Returns the output channel to which channel outputChannelIndex of our input audio
  24129. source will be sent to.
  24130. */
  24131. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  24132. /** Returns an XML object to encapsulate the state of the mappings.
  24133. @see restoreFromXml
  24134. */
  24135. XmlElement* createXml() const throw();
  24136. /** Restores the mappings from an XML object created by createXML().
  24137. @see createXml
  24138. */
  24139. void restoreFromXml (const XmlElement& e) throw();
  24140. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24141. void releaseResources();
  24142. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24143. juce_UseDebuggingNewOperator
  24144. private:
  24145. int requiredNumberOfChannels;
  24146. Array <int> remappedInputs, remappedOutputs;
  24147. AudioSource* const source;
  24148. const bool deleteSourceWhenDeleted;
  24149. AudioSampleBuffer buffer;
  24150. AudioSourceChannelInfo remappedInfo;
  24151. CriticalSection lock;
  24152. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  24153. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  24154. };
  24155. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24156. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  24157. #endif
  24158. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24159. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  24160. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24161. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24162. /**
  24163. An AudioSource that performs an IIR filter on another source.
  24164. */
  24165. class JUCE_API IIRFilterAudioSource : public AudioSource
  24166. {
  24167. public:
  24168. /** Creates a IIRFilterAudioSource for a given input source.
  24169. @param inputSource the input source to read from
  24170. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24171. this object is deleted
  24172. */
  24173. IIRFilterAudioSource (AudioSource* const inputSource,
  24174. const bool deleteInputWhenDeleted);
  24175. /** Destructor. */
  24176. ~IIRFilterAudioSource();
  24177. /** Changes the filter to use the same parameters as the one being passed in.
  24178. */
  24179. void setFilterParameters (const IIRFilter& newSettings);
  24180. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24181. void releaseResources();
  24182. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24183. juce_UseDebuggingNewOperator
  24184. private:
  24185. AudioSource* const input;
  24186. const bool deleteInputWhenDeleted;
  24187. OwnedArray <IIRFilter> iirFilters;
  24188. IIRFilterAudioSource (const IIRFilterAudioSource&);
  24189. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  24190. };
  24191. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24192. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  24193. #endif
  24194. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24195. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  24196. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24197. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24198. /**
  24199. An AudioSource that mixes together the output of a set of other AudioSources.
  24200. Input sources can be added and removed while the mixer is running as long as their
  24201. prepareToPlay() and releaseResources() methods are called before and after adding
  24202. them to the mixer.
  24203. */
  24204. class JUCE_API MixerAudioSource : public AudioSource
  24205. {
  24206. public:
  24207. /** Creates a MixerAudioSource.
  24208. */
  24209. MixerAudioSource();
  24210. /** Destructor. */
  24211. ~MixerAudioSource();
  24212. /** Adds an input source to the mixer.
  24213. If the mixer is running you'll need to make sure that the input source
  24214. is ready to play by calling its prepareToPlay() method before adding it.
  24215. If the mixer is stopped, then its input sources will be automatically
  24216. prepared when the mixer's prepareToPlay() method is called.
  24217. @param newInput the source to add to the mixer
  24218. @param deleteWhenRemoved if true, then this source will be deleted when
  24219. the mixer is deleted or when removeAllInputs() is
  24220. called (unless the source is previously removed
  24221. with the removeInputSource method)
  24222. */
  24223. void addInputSource (AudioSource* newInput,
  24224. const bool deleteWhenRemoved);
  24225. /** Removes an input source.
  24226. If the mixer is running, this will remove the source but not call its
  24227. releaseResources() method, so the caller might want to do this manually.
  24228. @param input the source to remove
  24229. @param deleteSource whether to delete this source after it's been removed
  24230. */
  24231. void removeInputSource (AudioSource* input,
  24232. const bool deleteSource);
  24233. /** Removes all the input sources.
  24234. If the mixer is running, this will remove the sources but not call their
  24235. releaseResources() method, so the caller might want to do this manually.
  24236. Any sources which were added with the deleteWhenRemoved flag set will be
  24237. deleted by this method.
  24238. */
  24239. void removeAllInputs();
  24240. /** Implementation of the AudioSource method.
  24241. This will call prepareToPlay() on all its input sources.
  24242. */
  24243. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24244. /** Implementation of the AudioSource method.
  24245. This will call releaseResources() on all its input sources.
  24246. */
  24247. void releaseResources();
  24248. /** Implementation of the AudioSource method. */
  24249. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24250. juce_UseDebuggingNewOperator
  24251. private:
  24252. VoidArray inputs;
  24253. BitArray inputsToDelete;
  24254. CriticalSection lock;
  24255. AudioSampleBuffer tempBuffer;
  24256. double currentSampleRate;
  24257. int bufferSizeExpected;
  24258. MixerAudioSource (const MixerAudioSource&);
  24259. const MixerAudioSource& operator= (const MixerAudioSource&);
  24260. };
  24261. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24262. /********* End of inlined file: juce_MixerAudioSource.h *********/
  24263. #endif
  24264. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24265. #endif
  24266. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24267. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24268. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24269. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24270. /**
  24271. A simple AudioSource that generates a sine wave.
  24272. */
  24273. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24274. {
  24275. public:
  24276. /** Creates a ToneGeneratorAudioSource. */
  24277. ToneGeneratorAudioSource();
  24278. /** Destructor. */
  24279. ~ToneGeneratorAudioSource();
  24280. /** Sets the signal's amplitude. */
  24281. void setAmplitude (const float newAmplitude);
  24282. /** Sets the signal's frequency. */
  24283. void setFrequency (const double newFrequencyHz);
  24284. /** Implementation of the AudioSource method. */
  24285. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24286. /** Implementation of the AudioSource method. */
  24287. void releaseResources();
  24288. /** Implementation of the AudioSource method. */
  24289. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24290. juce_UseDebuggingNewOperator
  24291. private:
  24292. double frequency, sampleRate;
  24293. double currentPhase, phasePerSample;
  24294. float amplitude;
  24295. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24296. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24297. };
  24298. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24299. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24300. #endif
  24301. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24302. #endif
  24303. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24304. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  24305. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24306. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24307. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  24308. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24309. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24310. class AudioDeviceManager;
  24311. class Component;
  24312. /**
  24313. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24314. To get a list of available audio driver types, use the createDeviceTypes()
  24315. method. Each of the objects returned can then be used to list the available
  24316. devices of that type. E.g.
  24317. @code
  24318. OwnedArray <AudioIODeviceType> types;
  24319. AudioIODeviceType::createDeviceTypes (types);
  24320. for (int i = 0; i < types.size(); ++i)
  24321. {
  24322. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24323. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24324. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24325. for (int j = 0; j < deviceNames.size(); ++j)
  24326. {
  24327. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24328. ...
  24329. }
  24330. }
  24331. @endcode
  24332. For an easier way of managing audio devices and their settings, have a look at the
  24333. AudioDeviceManager class.
  24334. @see AudioIODevice, AudioDeviceManager
  24335. */
  24336. class JUCE_API AudioIODeviceType
  24337. {
  24338. public:
  24339. /** Returns the name of this type of driver that this object manages.
  24340. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24341. */
  24342. const String& getTypeName() const throw() { return typeName; }
  24343. /** Refreshes the object's cached list of known devices.
  24344. This must be called at least once before calling getDeviceNames() or any of
  24345. the other device creation methods.
  24346. */
  24347. virtual void scanForDevices() = 0;
  24348. /** Returns the list of available devices of this type.
  24349. The scanForDevices() method must have been called to create this list.
  24350. @param wantInputNames only really used by DirectSound where devices are split up
  24351. into inputs and outputs, this indicates whether to use
  24352. the input or output name to refer to a pair of devices.
  24353. */
  24354. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  24355. /** Returns the name of the default device.
  24356. This will be one of the names from the getDeviceNames() list.
  24357. @param forInput if true, this means that a default input device should be
  24358. returned; if false, it should return the default output
  24359. */
  24360. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  24361. /** Returns the index of a given device in the list of device names.
  24362. If asInput is true, it shows the index in the inputs list, otherwise it
  24363. looks for it in the outputs list.
  24364. */
  24365. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  24366. /** Returns true if two different devices can be used for the input and output.
  24367. */
  24368. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24369. /** Creates one of the devices of this type.
  24370. The deviceName must be one of the strings returned by getDeviceNames(), and
  24371. scanForDevices() must have been called before this method is used.
  24372. */
  24373. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24374. const String& inputDeviceName) = 0;
  24375. struct DeviceSetupDetails
  24376. {
  24377. AudioDeviceManager* manager;
  24378. int minNumInputChannels, maxNumInputChannels;
  24379. int minNumOutputChannels, maxNumOutputChannels;
  24380. bool useStereoPairs;
  24381. };
  24382. /** Destructor. */
  24383. virtual ~AudioIODeviceType();
  24384. protected:
  24385. AudioIODeviceType (const tchar* const typeName);
  24386. private:
  24387. String typeName;
  24388. AudioIODeviceType (const AudioIODeviceType&);
  24389. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  24390. };
  24391. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24392. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  24393. /********* Start of inlined file: juce_MidiOutput.h *********/
  24394. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24395. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24396. /**
  24397. Represents a midi output device.
  24398. To create one of these, use the static getDevices() method to find out what
  24399. outputs are available, then use the openDevice() method to try to open one.
  24400. @see MidiInput
  24401. */
  24402. class JUCE_API MidiOutput : private Thread
  24403. {
  24404. public:
  24405. /** Returns a list of the available midi output devices.
  24406. You can open one of the devices by passing its index into the
  24407. openDevice() method.
  24408. @see getDefaultDeviceIndex, openDevice
  24409. */
  24410. static const StringArray getDevices();
  24411. /** Returns the index of the default midi output device to use.
  24412. This refers to the index in the list returned by getDevices().
  24413. */
  24414. static int getDefaultDeviceIndex();
  24415. /** Tries to open one of the midi output devices.
  24416. This will return a MidiOutput object if it manages to open it. You can then
  24417. send messages to this device, and delete it when no longer needed.
  24418. If the device can't be opened, this will return a null pointer.
  24419. @param deviceIndex the index of a device from the list returned by getDevices()
  24420. @see getDevices
  24421. */
  24422. static MidiOutput* openDevice (int deviceIndex);
  24423. #if JUCE_LINUX || DOXYGEN
  24424. /** LINUX ONLY - This will try to create a new midi output device.
  24425. This will attempt to create a new midi output device that other apps can connect
  24426. to and use as their midi input.
  24427. Returns 0 if a device can't be created.
  24428. @param deviceName the name to use for the new device
  24429. */
  24430. static MidiOutput* createNewDevice (const String& deviceName);
  24431. #endif
  24432. /** Destructor. */
  24433. virtual ~MidiOutput();
  24434. /** Makes this device output a midi message.
  24435. @see MidiMessage
  24436. */
  24437. virtual void sendMessageNow (const MidiMessage& message);
  24438. /** Sends a midi reset to the device. */
  24439. virtual void reset();
  24440. /** Returns the current volume setting for this device. */
  24441. virtual bool getVolume (float& leftVol,
  24442. float& rightVol);
  24443. /** Changes the overall volume for this device. */
  24444. virtual void setVolume (float leftVol,
  24445. float rightVol);
  24446. /** This lets you supply a block of messages that will be sent out at some point
  24447. in the future.
  24448. The MidiOutput class has an internal thread that can send out timestamped
  24449. messages - this appends a set of messages to its internal buffer, ready for
  24450. sending.
  24451. This will only work if you've already started the thread with startBackgroundThread().
  24452. A time is supplied, at which the block of messages should be sent. This time uses
  24453. the same time base as Time::getMillisecondCounter(), and must be in the future.
  24454. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  24455. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  24456. samplesPerSecondForBuffer value is needed to convert this sample position to a
  24457. real time.
  24458. */
  24459. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  24460. const double millisecondCounterToStartAt,
  24461. double samplesPerSecondForBuffer) throw();
  24462. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  24463. */
  24464. virtual void clearAllPendingMessages() throw();
  24465. /** Starts up a background thread so that the device can send blocks of data.
  24466. Call this to get the device ready, before using sendBlockOfMessages().
  24467. */
  24468. virtual void startBackgroundThread() throw();
  24469. /** Stops the background thread, and clears any pending midi events.
  24470. @see startBackgroundThread
  24471. */
  24472. virtual void stopBackgroundThread() throw();
  24473. juce_UseDebuggingNewOperator
  24474. protected:
  24475. void* internal;
  24476. struct PendingMessage
  24477. {
  24478. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  24479. MidiMessage message;
  24480. PendingMessage* next;
  24481. juce_UseDebuggingNewOperator
  24482. };
  24483. CriticalSection lock;
  24484. PendingMessage* firstMessage;
  24485. MidiOutput() throw();
  24486. MidiOutput (const MidiOutput&);
  24487. void run();
  24488. };
  24489. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24490. /********* End of inlined file: juce_MidiOutput.h *********/
  24491. /********* Start of inlined file: juce_ComboBox.h *********/
  24492. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24493. #define __JUCE_COMBOBOX_JUCEHEADER__
  24494. /********* Start of inlined file: juce_Label.h *********/
  24495. #ifndef __JUCE_LABEL_JUCEHEADER__
  24496. #define __JUCE_LABEL_JUCEHEADER__
  24497. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  24498. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24499. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24500. /**
  24501. Object for monitoring a component, and later testing whether it's still valid.
  24502. Slightly obscure, this one, but it's used internally for making sure that
  24503. after some callbacks, a component hasn't been deleted. It's more reliable than
  24504. just using isValidComponent(), which can provide false-positives if a new
  24505. component is created at the same memory location as an old one.
  24506. */
  24507. class JUCE_API ComponentDeletionWatcher
  24508. {
  24509. public:
  24510. /** Creates a watcher for a given component.
  24511. The component must be valid at the time it's passed in.
  24512. */
  24513. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  24514. /** Destructor. */
  24515. ~ComponentDeletionWatcher() throw();
  24516. /** Returns true if the component has been deleted since the time that this
  24517. object was created.
  24518. */
  24519. bool hasBeenDeleted() const throw();
  24520. /** Returns the component that's being watched, or null if it has been deleted. */
  24521. const Component* getComponent() const throw();
  24522. juce_UseDebuggingNewOperator
  24523. private:
  24524. const Component* const componentToWatch;
  24525. const uint32 componentUID;
  24526. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  24527. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  24528. };
  24529. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24530. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24531. /********* Start of inlined file: juce_TextEditor.h *********/
  24532. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24533. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24534. /********* Start of inlined file: juce_UndoManager.h *********/
  24535. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24536. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24537. /********* Start of inlined file: juce_UndoableAction.h *********/
  24538. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24539. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24540. /**
  24541. Used by the UndoManager class to store an action which can be done
  24542. and undone.
  24543. @see UndoManager
  24544. */
  24545. class JUCE_API UndoableAction
  24546. {
  24547. protected:
  24548. /** Creates an action. */
  24549. UndoableAction() throw() {}
  24550. public:
  24551. /** Destructor. */
  24552. virtual ~UndoableAction() {}
  24553. /** Overridden by a subclass to perform the action.
  24554. This method is called by the UndoManager, and shouldn't be used directly by
  24555. applications.
  24556. Be careful not to make any calls in a perform() method that could call
  24557. recursively back into the UndoManager::perform() method
  24558. @returns true if the action could be performed.
  24559. @see UndoManager::perform
  24560. */
  24561. virtual bool perform() = 0;
  24562. /** Overridden by a subclass to undo the action.
  24563. This method is called by the UndoManager, and shouldn't be used directly by
  24564. applications.
  24565. Be careful not to make any calls in an undo() method that could call
  24566. recursively back into the UndoManager::perform() method
  24567. @returns true if the action could be undone without any errors.
  24568. @see UndoManager::perform
  24569. */
  24570. virtual bool undo() = 0;
  24571. /** Returns a value to indicate how much memory this object takes up.
  24572. Because the UndoManager keeps a list of UndoableActions, this is used
  24573. to work out how much space each one will take up, so that the UndoManager
  24574. can work out how many to keep.
  24575. The default value returned here is 10 - units are arbitrary and
  24576. don't have to be accurate.
  24577. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24578. UndoManager::setMaxNumberOfStoredUnits
  24579. */
  24580. virtual int getSizeInUnits() { return 10; }
  24581. };
  24582. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24583. /********* End of inlined file: juce_UndoableAction.h *********/
  24584. /**
  24585. Manages a list of undo/redo commands.
  24586. An UndoManager object keeps a list of past actions and can use these actions
  24587. to move backwards and forwards through an undo history.
  24588. To use it, create subclasses of UndoableAction which perform all the
  24589. actions you need, then when you need to actually perform an action, create one
  24590. and pass it to the UndoManager's perform() method.
  24591. The manager also uses the concept of 'transactions' to group the actions
  24592. together - all actions performed between calls to beginNewTransaction() are
  24593. grouped together and are all undone/redone as a group.
  24594. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24595. when actions are performed or undone.
  24596. @see UndoableAction
  24597. */
  24598. class JUCE_API UndoManager : public ChangeBroadcaster
  24599. {
  24600. public:
  24601. /** Creates an UndoManager.
  24602. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24603. to indicate how much storage it takes up
  24604. (UndoableAction::getSizeInUnits()), so this
  24605. lets you specify the maximum total number of
  24606. units that the undomanager is allowed to
  24607. keep in memory before letting the older actions
  24608. drop off the end of the list.
  24609. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24610. that will be kept, even if this involves exceeding
  24611. the amount of space specified in maxNumberOfUnitsToKeep
  24612. */
  24613. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24614. const int minimumTransactionsToKeep = 30);
  24615. /** Destructor. */
  24616. ~UndoManager();
  24617. /** Deletes all stored actions in the list. */
  24618. void clearUndoHistory();
  24619. /** Returns the current amount of space to use for storing UndoableAction objects.
  24620. @see setMaxNumberOfStoredUnits
  24621. */
  24622. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24623. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24624. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24625. to indicate how much storage it takes up
  24626. (UndoableAction::getSizeInUnits()), so this
  24627. lets you specify the maximum total number of
  24628. units that the undomanager is allowed to
  24629. keep in memory before letting the older actions
  24630. drop off the end of the list.
  24631. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24632. that will be kept, even if this involves exceeding
  24633. the amount of space specified in maxNumberOfUnitsToKeep
  24634. @see getNumberOfUnitsTakenUpByStoredCommands
  24635. */
  24636. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24637. const int minimumTransactionsToKeep);
  24638. /** Performs an action and adds it to the undo history list.
  24639. @param action the action to perform - this will be deleted by the UndoManager
  24640. when no longer needed
  24641. @param actionName if this string is non-empty, the current transaction will be
  24642. given this name; if it's empty, the current transaction name will
  24643. be left unchanged. See setCurrentTransactionName()
  24644. @returns true if the command succeeds - see UndoableAction::perform
  24645. @see beginNewTransaction
  24646. */
  24647. bool perform (UndoableAction* const action,
  24648. const String& actionName = String::empty);
  24649. /** Starts a new group of actions that together will be treated as a single transaction.
  24650. All actions that are passed to the perform() method between calls to this
  24651. method are grouped together and undone/redone together by a single call to
  24652. undo() or redo().
  24653. @param actionName a description of the transaction that is about to be
  24654. performed
  24655. */
  24656. void beginNewTransaction (const String& actionName = String::empty);
  24657. /** Changes the name stored for the current transaction.
  24658. Each transaction is given a name when the beginNewTransaction() method is
  24659. called, but this can be used to change that name without starting a new
  24660. transaction.
  24661. */
  24662. void setCurrentTransactionName (const String& newName);
  24663. /** Returns true if there's at least one action in the list to undo.
  24664. @see getUndoDescription, undo, canRedo
  24665. */
  24666. bool canUndo() const;
  24667. /** Returns the description of the transaction that would be next to get undone.
  24668. The description returned is the one that was passed into beginNewTransaction
  24669. before the set of actions was performed.
  24670. @see undo
  24671. */
  24672. const String getUndoDescription() const;
  24673. /** Tries to roll-back the last transaction.
  24674. @returns true if the transaction can be undone, and false if it fails, or
  24675. if there aren't any transactions to undo
  24676. */
  24677. bool undo();
  24678. /** Tries to roll-back any actions that were added to the current transaction.
  24679. This will perform an undo() only if there are some actions in the undo list
  24680. that were added after the last call to beginNewTransaction().
  24681. This is useful because it lets you call beginNewTransaction(), then
  24682. perform an operation which may or may not actually perform some actions, and
  24683. then call this method to get rid of any actions that might have been done
  24684. without it rolling back the previous transaction if nothing was actually
  24685. done.
  24686. @returns true if any actions were undone.
  24687. */
  24688. bool undoCurrentTransactionOnly();
  24689. /** Returns a list of the UndoableAction objects that have been performed during the
  24690. transaction that is currently open.
  24691. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24692. were to be called now.
  24693. The first item in the list is the earliest action performed.
  24694. */
  24695. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24696. /** Returns true if there's at least one action in the list to redo.
  24697. @see getRedoDescription, redo, canUndo
  24698. */
  24699. bool canRedo() const;
  24700. /** Returns the description of the transaction that would be next to get redone.
  24701. The description returned is the one that was passed into beginNewTransaction
  24702. before the set of actions was performed.
  24703. @see redo
  24704. */
  24705. const String getRedoDescription() const;
  24706. /** Tries to redo the last transaction that was undone.
  24707. @returns true if the transaction can be redone, and false if it fails, or
  24708. if there aren't any transactions to redo
  24709. */
  24710. bool redo();
  24711. juce_UseDebuggingNewOperator
  24712. private:
  24713. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24714. StringArray transactionNames;
  24715. String currentTransactionName;
  24716. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24717. bool newTransaction, reentrancyCheck;
  24718. // disallow copy constructor
  24719. UndoManager (const UndoManager&);
  24720. const UndoManager& operator= (const UndoManager&);
  24721. };
  24722. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24723. /********* End of inlined file: juce_UndoManager.h *********/
  24724. class TextEditor;
  24725. class TextHolderComponent;
  24726. /**
  24727. Receives callbacks from a TextEditor component when it changes.
  24728. @see TextEditor::addListener
  24729. */
  24730. class JUCE_API TextEditorListener
  24731. {
  24732. public:
  24733. /** Destructor. */
  24734. virtual ~TextEditorListener() {}
  24735. /** Called when the user changes the text in some way. */
  24736. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24737. /** Called when the user presses the return key. */
  24738. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24739. /** Called when the user presses the escape key. */
  24740. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24741. /** Called when the text editor loses focus. */
  24742. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24743. };
  24744. /**
  24745. A component containing text that can be edited.
  24746. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24747. fonts and colours.
  24748. @see TextEditorListener, Label
  24749. */
  24750. class JUCE_API TextEditor : public Component,
  24751. public SettableTooltipClient
  24752. {
  24753. public:
  24754. /** Creates a new, empty text editor.
  24755. @param componentName the name to pass to the component for it to use as its name
  24756. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24757. for all characters that are drawn on screen - e.g. to create
  24758. a password-style textbox containing circular blobs instead of text,
  24759. you could set this value to 0x25cf, which is the unicode character
  24760. for a black splodge (not all fonts include this, though), or 0x2022,
  24761. which is a bullet (probably the best choice for linux).
  24762. */
  24763. TextEditor (const String& componentName = String::empty,
  24764. const tchar passwordCharacter = 0);
  24765. /** Destructor. */
  24766. virtual ~TextEditor();
  24767. /** Puts the editor into either multi- or single-line mode.
  24768. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24769. editor.
  24770. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24771. on if you want a multi-line editor with line-breaks.
  24772. @see isMultiLine, setReturnKeyStartsNewLine
  24773. */
  24774. void setMultiLine (const bool shouldBeMultiLine,
  24775. const bool shouldWordWrap = true);
  24776. /** Returns true if the editor is in multi-line mode.
  24777. */
  24778. bool isMultiLine() const throw();
  24779. /** Changes the behaviour of the return key.
  24780. If set to true, the return key will insert a new-line into the text; if false
  24781. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24782. method. By default this is set to false, and when true it will only insert
  24783. new-lines when in multi-line mode (see setMultiLine()).
  24784. */
  24785. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24786. /** Returns the value set by setReturnKeyStartsNewLine().
  24787. See setReturnKeyStartsNewLine() for more info.
  24788. */
  24789. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24790. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24791. or whether it gets ignored.
  24792. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24793. between components.
  24794. */
  24795. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24796. /** Returns true if the tab key is being used for input.
  24797. @see setTabKeyUsedAsCharacter
  24798. */
  24799. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24800. /** Changes the editor to read-only mode.
  24801. By default, the text editor is not read-only. If you're making it read-only, you
  24802. might also want to call setCaretVisible (false) to get rid of the caret.
  24803. The text can still be highlighted and copied when in read-only mode.
  24804. @see isReadOnly, setCaretVisible
  24805. */
  24806. void setReadOnly (const bool shouldBeReadOnly);
  24807. /** Returns true if the editor is in read-only mode.
  24808. */
  24809. bool isReadOnly() const throw();
  24810. /** Makes the caret visible or invisible.
  24811. By default the caret is visible.
  24812. @see setCaretColour, setCaretPosition
  24813. */
  24814. void setCaretVisible (const bool shouldBeVisible) throw();
  24815. /** Returns true if the caret is enabled.
  24816. @see setCaretVisible
  24817. */
  24818. bool isCaretVisible() const throw() { return caretVisible; }
  24819. /** Enables/disables a vertical scrollbar.
  24820. (This only applies when in multi-line mode). When the text gets too long to fit
  24821. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24822. this is enabled, the scrollbar will be hidden unless it's needed.
  24823. By default the scrollbar is enabled.
  24824. */
  24825. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24826. /** Returns true if scrollbars are enabled.
  24827. @see setScrollbarsShown
  24828. */
  24829. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24830. /** Changes the password character used to disguise the text.
  24831. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24832. for all characters that are drawn on screen - e.g. to create
  24833. a password-style textbox containing circular blobs instead of text,
  24834. you could set this value to 0x25cf, which is the unicode character
  24835. for a black splodge (not all fonts include this, though), or 0x2022,
  24836. which is a bullet (probably the best choice for linux).
  24837. */
  24838. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24839. /** Returns the current password character.
  24840. @see setPasswordCharacter
  24841. l */
  24842. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24843. /** Allows a right-click menu to appear for the editor.
  24844. (This defaults to being enabled).
  24845. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24846. of options such as cut/copy/paste, undo/redo, etc.
  24847. */
  24848. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24849. /** Returns true if the right-click menu is enabled.
  24850. @see setPopupMenuEnabled
  24851. */
  24852. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24853. /** Returns true if a popup-menu is currently being displayed.
  24854. */
  24855. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24856. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24857. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24858. methods.
  24859. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24860. */
  24861. enum ColourIds
  24862. {
  24863. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24864. transparent if necessary. */
  24865. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24866. that because the editor can contain multiple colours, calling this
  24867. method won't change the colour of existing text - to do that, call
  24868. applyFontToAllText() after calling this method.*/
  24869. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24870. the text - this can be transparent if you don't want to show any
  24871. highlighting.*/
  24872. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24873. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24874. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24875. the edge of the component. */
  24876. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24877. the edge of the component when it has focus. */
  24878. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24879. around the edge of the editor. */
  24880. };
  24881. /** Sets the font to use for newly added text.
  24882. This will change the font that will be used next time any text is added or entered
  24883. into the editor. It won't change the font of any existing text - to do that, use
  24884. applyFontToAllText() instead.
  24885. @see applyFontToAllText
  24886. */
  24887. void setFont (const Font& newFont) throw();
  24888. /** Applies a font to all the text in the editor.
  24889. This will also set the current font to use for any new text that's added.
  24890. @see setFont
  24891. */
  24892. void applyFontToAllText (const Font& newFont);
  24893. /** Returns the font that's currently being used for new text.
  24894. @see setFont
  24895. */
  24896. const Font getFont() const throw();
  24897. /** If set to true, focusing on the editor will highlight all its text.
  24898. (Set to false by default).
  24899. This is useful for boxes where you expect the user to re-enter all the
  24900. text when they focus on the component, rather than editing what's already there.
  24901. */
  24902. void setSelectAllWhenFocused (const bool b) throw();
  24903. /** Sets limits on the characters that can be entered.
  24904. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24905. limit is set
  24906. @param allowedCharacters if this is non-empty, then only characters that occur in
  24907. this string are allowed to be entered into the editor.
  24908. */
  24909. void setInputRestrictions (const int maxTextLength,
  24910. const String& allowedCharacters = String::empty) throw();
  24911. /** When the text editor is empty, it can be set to display a message.
  24912. This is handy for things like telling the user what to type in the box - the
  24913. string is only displayed, it's not taken to actually be the contents of
  24914. the editor.
  24915. */
  24916. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24917. /** Changes the size of the scrollbars that are used.
  24918. Handy if you need smaller scrollbars for a small text box.
  24919. */
  24920. void setScrollBarThickness (const int newThicknessPixels);
  24921. /** Shows or hides the buttons on any scrollbars that are used.
  24922. @see ScrollBar::setButtonVisibility
  24923. */
  24924. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24925. /** Registers a listener to be told when things happen to the text.
  24926. @see removeListener
  24927. */
  24928. void addListener (TextEditorListener* const newListener) throw();
  24929. /** Deregisters a listener.
  24930. @see addListener
  24931. */
  24932. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24933. /** Returns the entire contents of the editor. */
  24934. const String getText() const throw();
  24935. /** Returns a section of the contents of the editor. */
  24936. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24937. /** Returns true if there are no characters in the editor.
  24938. This is more efficient than calling getText().isEmpty().
  24939. */
  24940. bool isEmpty() const throw();
  24941. /** Sets the entire content of the editor.
  24942. This will clear the editor and insert the given text (using the current text colour
  24943. and font). You can set the current text colour using
  24944. @code setColour (TextEditor::textColourId, ...);
  24945. @endcode
  24946. @param newText the text to add
  24947. @param sendTextChangeMessage if true, this will cause a change message to
  24948. be sent to all the listeners.
  24949. @see insertText
  24950. */
  24951. void setText (const String& newText,
  24952. const bool sendTextChangeMessage = true);
  24953. /** Inserts some text at the current cursor position.
  24954. If a section of the text is highlighted, it will be replaced by
  24955. this string, otherwise it will be inserted.
  24956. To delete a section of text, you can use setHighlightedRegion() to
  24957. highlight it, and call insertTextAtCursor (String::empty).
  24958. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24959. */
  24960. void insertTextAtCursor (String textToInsert);
  24961. /** Deletes all the text from the editor. */
  24962. void clear();
  24963. /** Deletes the currently selected region, and puts it on the clipboard.
  24964. @see copy, paste, SystemClipboard
  24965. */
  24966. void cut();
  24967. /** Copies any currently selected region to the clipboard.
  24968. @see cut, paste, SystemClipboard
  24969. */
  24970. void copy();
  24971. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24972. @see cut, copy, SystemClipboard
  24973. */
  24974. void paste();
  24975. /** Moves the caret to be in front of a given character.
  24976. @see getCaretPosition
  24977. */
  24978. void setCaretPosition (const int newIndex) throw();
  24979. /** Returns the current index of the caret.
  24980. @see setCaretPosition
  24981. */
  24982. int getCaretPosition() const throw();
  24983. /** Attempts to scroll the text editor so that the caret ends up at
  24984. a specified position.
  24985. This won't affect the caret's position within the text, it tries to scroll
  24986. the entire editor vertically and horizontally so that the caret is sitting
  24987. at the given position (relative to the top-left of this component).
  24988. Depending on the amount of text available, it might not be possible to
  24989. scroll far enough for the caret to reach this exact position, but it
  24990. will go as far as it can in that direction.
  24991. */
  24992. void scrollEditorToPositionCaret (const int desiredCaretX,
  24993. const int desiredCaretY) throw();
  24994. /** Get the graphical position of the caret.
  24995. The rectangle returned is relative to the component's top-left corner.
  24996. @see scrollEditorToPositionCaret
  24997. */
  24998. const Rectangle getCaretRectangle() throw();
  24999. /** Selects a section of the text.
  25000. */
  25001. void setHighlightedRegion (int startIndex,
  25002. int numberOfCharactersToHighlight) throw();
  25003. /** Returns the first character that is selected.
  25004. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  25005. will return 0.
  25006. @see setHighlightedRegion, getHighlightedRegionLength
  25007. */
  25008. int getHighlightedRegionStart() const throw() { return selectionStart; }
  25009. /** Returns the number of characters that are selected.
  25010. @see setHighlightedRegion, getHighlightedRegionStart
  25011. */
  25012. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  25013. /** Returns the section of text that is currently selected. */
  25014. const String getHighlightedText() const throw();
  25015. /** Finds the index of the character at a given position.
  25016. The co-ordinates are relative to the component's top-left.
  25017. */
  25018. int getTextIndexAt (const int x, const int y) throw();
  25019. /** Counts the number of characters in the text.
  25020. This is quicker than getting the text as a string if you just need to know
  25021. the length.
  25022. */
  25023. int getTotalNumChars() throw();
  25024. /** Returns the total width of the text, as it is currently laid-out.
  25025. This may be larger than the size of the TextEditor, and can change when
  25026. the TextEditor is resized or the text changes.
  25027. */
  25028. int getTextWidth() const throw();
  25029. /** Returns the maximum height of the text, as it is currently laid-out.
  25030. This may be larger than the size of the TextEditor, and can change when
  25031. the TextEditor is resized or the text changes.
  25032. */
  25033. int getTextHeight() const throw();
  25034. /** Changes the size of the gap at the top and left-edge of the editor.
  25035. By default there's a gap of 4 pixels.
  25036. */
  25037. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  25038. /** Changes the size of border left around the edge of the component.
  25039. @see getBorder
  25040. */
  25041. void setBorder (const BorderSize& border) throw();
  25042. /** Returns the size of border around the edge of the component.
  25043. @see setBorder
  25044. */
  25045. const BorderSize getBorder() const throw();
  25046. /** Used to disable the auto-scrolling which keeps the cursor visible.
  25047. If true (the default), the editor will scroll when the cursor moves offscreen. If
  25048. set to false, it won't.
  25049. */
  25050. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  25051. /** @internal */
  25052. void paint (Graphics& g);
  25053. /** @internal */
  25054. void paintOverChildren (Graphics& g);
  25055. /** @internal */
  25056. void mouseDown (const MouseEvent& e);
  25057. /** @internal */
  25058. void mouseUp (const MouseEvent& e);
  25059. /** @internal */
  25060. void mouseDrag (const MouseEvent& e);
  25061. /** @internal */
  25062. void mouseDoubleClick (const MouseEvent& e);
  25063. /** @internal */
  25064. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25065. /** @internal */
  25066. bool keyPressed (const KeyPress& key);
  25067. /** @internal */
  25068. bool keyStateChanged (const bool isKeyDown);
  25069. /** @internal */
  25070. void focusGained (FocusChangeType cause);
  25071. /** @internal */
  25072. void focusLost (FocusChangeType cause);
  25073. /** @internal */
  25074. void resized();
  25075. /** @internal */
  25076. void enablementChanged();
  25077. /** @internal */
  25078. void colourChanged();
  25079. juce_UseDebuggingNewOperator
  25080. protected:
  25081. /** This adds the items to the popup menu.
  25082. By default it adds the cut/copy/paste items, but you can override this if
  25083. you need to replace these with your own items.
  25084. If you want to add your own items to the existing ones, you can override this,
  25085. call the base class's addPopupMenuItems() method, then append your own items.
  25086. When the menu has been shown, performPopupMenuAction() will be called to
  25087. perform the item that the user has chosen.
  25088. The default menu items will be added using item IDs in the range
  25089. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  25090. menu IDs.
  25091. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  25092. a pointer to the info about it, or may be null if the menu is being triggered
  25093. by some other means.
  25094. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  25095. */
  25096. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  25097. const MouseEvent* mouseClickEvent);
  25098. /** This is called to perform one of the items that was shown on the popup menu.
  25099. If you've overridden addPopupMenuItems(), you should also override this
  25100. to perform the actions that you've added.
  25101. If you've overridden addPopupMenuItems() but have still left the default items
  25102. on the menu, remember to call the superclass's performPopupMenuAction()
  25103. so that it can perform the default actions if that's what the user clicked on.
  25104. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  25105. */
  25106. virtual void performPopupMenuAction (const int menuItemID);
  25107. /** Scrolls the minimum distance needed to get the caret into view. */
  25108. void scrollToMakeSureCursorIsVisible() throw();
  25109. /** @internal */
  25110. void moveCaret (int newCaretPos) throw();
  25111. /** @internal */
  25112. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  25113. /** Used internally to dispatch a text-change message. */
  25114. void textChanged() throw();
  25115. /** Begins a new transaction in the UndoManager.
  25116. */
  25117. void newTransaction() throw();
  25118. /** Used internally to trigger an undo or redo. */
  25119. void doUndoRedo (const bool isRedo);
  25120. /** Can be overridden to intercept return key presses directly */
  25121. virtual void returnPressed();
  25122. /** Can be overridden to intercept escape key presses directly */
  25123. virtual void escapePressed();
  25124. /** @internal */
  25125. void handleCommandMessage (int commandId);
  25126. private:
  25127. Viewport* viewport;
  25128. TextHolderComponent* textHolder;
  25129. BorderSize borderSize;
  25130. bool readOnly : 1;
  25131. bool multiline : 1;
  25132. bool wordWrap : 1;
  25133. bool returnKeyStartsNewLine : 1;
  25134. bool caretVisible : 1;
  25135. bool popupMenuEnabled : 1;
  25136. bool selectAllTextWhenFocused : 1;
  25137. bool scrollbarVisible : 1;
  25138. bool wasFocused : 1;
  25139. bool caretFlashState : 1;
  25140. bool keepCursorOnScreen : 1;
  25141. bool tabKeyUsed : 1;
  25142. bool menuActive : 1;
  25143. UndoManager undoManager;
  25144. float cursorX, cursorY, cursorHeight;
  25145. int maxTextLength;
  25146. int selectionStart, selectionEnd;
  25147. int leftIndent, topIndent;
  25148. unsigned int lastTransactionTime;
  25149. Font currentFont;
  25150. int totalNumChars, caretPosition;
  25151. VoidArray sections;
  25152. String textToShowWhenEmpty;
  25153. Colour colourForTextWhenEmpty;
  25154. tchar passwordCharacter;
  25155. enum
  25156. {
  25157. notDragging,
  25158. draggingSelectionStart,
  25159. draggingSelectionEnd
  25160. } dragType;
  25161. String allowedCharacters;
  25162. SortedSet <void*> listeners;
  25163. friend class TextEditorInsertAction;
  25164. friend class TextEditorRemoveAction;
  25165. void coalesceSimilarSections() throw();
  25166. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  25167. void clearInternal (UndoManager* const um) throw();
  25168. void insert (const String& text,
  25169. const int insertIndex,
  25170. const Font& font,
  25171. const Colour& colour,
  25172. UndoManager* const um,
  25173. const int caretPositionToMoveTo) throw();
  25174. void reinsert (const int insertIndex,
  25175. const VoidArray& sections) throw();
  25176. void remove (const int startIndex,
  25177. int endIndex,
  25178. UndoManager* const um,
  25179. const int caretPositionToMoveTo) throw();
  25180. void getCharPosition (const int index,
  25181. float& x, float& y,
  25182. float& lineHeight) const throw();
  25183. void updateCaretPosition() throw();
  25184. int indexAtPosition (const float x,
  25185. const float y) throw();
  25186. int findWordBreakAfter (const int position) const throw();
  25187. int findWordBreakBefore (const int position) const throw();
  25188. friend class TextHolderComponent;
  25189. friend class TextEditorViewport;
  25190. void drawContent (Graphics& g);
  25191. void updateTextHolderSize() throw();
  25192. float getWordWrapWidth() const throw();
  25193. void timerCallbackInt();
  25194. void repaintCaret();
  25195. void repaintText (int textStartIndex, int textEndIndex);
  25196. TextEditor (const TextEditor&);
  25197. const TextEditor& operator= (const TextEditor&);
  25198. };
  25199. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  25200. /********* End of inlined file: juce_TextEditor.h *********/
  25201. class Label;
  25202. /**
  25203. A class for receiving events from a Label.
  25204. You can register a LabelListener with a Label using the Label::addListener()
  25205. method, and it will be called when the text of the label changes, either because
  25206. of a call to Label::setText() or by the user editing the text (if the label is
  25207. editable).
  25208. @see Label::addListener, Label::removeListener
  25209. */
  25210. class JUCE_API LabelListener
  25211. {
  25212. public:
  25213. /** Destructor. */
  25214. virtual ~LabelListener() {}
  25215. /** Called when a Label's text has changed.
  25216. */
  25217. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  25218. };
  25219. /**
  25220. A component that displays a text string, and can optionally become a text
  25221. editor when clicked.
  25222. */
  25223. class JUCE_API Label : public Component,
  25224. public SettableTooltipClient,
  25225. protected TextEditorListener,
  25226. private ComponentListener
  25227. {
  25228. public:
  25229. /** Creates a Label.
  25230. @param componentName the name to give the component
  25231. @param labelText the text to show in the label
  25232. */
  25233. Label (const String& componentName,
  25234. const String& labelText);
  25235. /** Destructor. */
  25236. ~Label();
  25237. /** Changes the label text.
  25238. If broadcastChangeMessage is true and the new text is different to the current
  25239. text, then the class will broadcast a change message to any LabelListeners that
  25240. are registered.
  25241. */
  25242. void setText (const String& newText,
  25243. const bool broadcastChangeMessage);
  25244. /** Returns the label's current text.
  25245. @param returnActiveEditorContents if this is true and the label is currently
  25246. being edited, then this method will return the
  25247. text as it's being shown in the editor. If false,
  25248. then the value returned here won't be updated until
  25249. the user has finished typing and pressed the return
  25250. key.
  25251. */
  25252. const String getText (const bool returnActiveEditorContents = false) const throw();
  25253. /** Changes the font to use to draw the text.
  25254. @see getFont
  25255. */
  25256. void setFont (const Font& newFont) throw();
  25257. /** Returns the font currently being used.
  25258. @see setFont
  25259. */
  25260. const Font& getFont() const throw();
  25261. /** A set of colour IDs to use to change the colour of various aspects of the label.
  25262. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25263. methods.
  25264. Note that you can also use the constants from TextEditor::ColourIds to change the
  25265. colour of the text editor that is opened when a label is editable.
  25266. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25267. */
  25268. enum ColourIds
  25269. {
  25270. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  25271. textColourId = 0x1000281, /**< The colour for the text. */
  25272. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  25273. Leave this transparent to not have an outline. */
  25274. };
  25275. /** Sets the style of justification to be used for positioning the text.
  25276. (The default is Justification::centredLeft)
  25277. */
  25278. void setJustificationType (const Justification& justification) throw();
  25279. /** Returns the type of justification, as set in setJustificationType(). */
  25280. const Justification getJustificationType() const throw() { return justification; }
  25281. /** Changes the gap that is left between the edge of the component and the text.
  25282. By default there's a small gap left at the sides of the component to allow for
  25283. the drawing of the border, but you can change this if necessary.
  25284. */
  25285. void setBorderSize (int horizontalBorder, int verticalBorder);
  25286. /** Returns the size of the horizontal gap being left around the text.
  25287. */
  25288. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  25289. /** Returns the size of the vertical gap being left around the text.
  25290. */
  25291. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  25292. /** Makes this label "stick to" another component.
  25293. This will cause the label to follow another component around, staying
  25294. either to its left or above it.
  25295. @param owner the component to follow
  25296. @param onLeft if true, the label will stay on the left of its component; if
  25297. false, it will stay above it.
  25298. */
  25299. void attachToComponent (Component* owner,
  25300. const bool onLeft);
  25301. /** If this label has been attached to another component using attachToComponent, this
  25302. returns the other component.
  25303. Returns 0 if the label is not attached.
  25304. */
  25305. Component* getAttachedComponent() const throw() { return ownerComponent; }
  25306. /** If the label is attached to the left of another component, this returns true.
  25307. Returns false if the label is above the other component. This is only relevent if
  25308. attachToComponent() has been called.
  25309. */
  25310. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  25311. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  25312. using ellipsis.
  25313. @see Graphics::drawFittedText
  25314. */
  25315. void setMinimumHorizontalScale (const float newScale);
  25316. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  25317. /** Registers a listener that will be called when the label's text changes. */
  25318. void addListener (LabelListener* const listener) throw();
  25319. /** Deregisters a previously-registered listener. */
  25320. void removeListener (LabelListener* const listener) throw();
  25321. /** Makes the label turn into a TextEditor when clicked.
  25322. By default this is turned off.
  25323. If turned on, then single- or double-clicking will turn the label into
  25324. an editor. If the user then changes the text, then the ChangeBroadcaster
  25325. base class will be used to send change messages to any listeners that
  25326. have registered.
  25327. If the user changes the text, the textWasEdited() method will be called
  25328. afterwards, and subclasses can override this if they need to do anything
  25329. special.
  25330. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  25331. @param editOnDoubleClick if true, a double-click is needed to start editing
  25332. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  25333. edited will discard any changes; if false, then this will
  25334. commit the changes.
  25335. @see showEditor, setEditorColours, TextEditor
  25336. */
  25337. void setEditable (const bool editOnSingleClick,
  25338. const bool editOnDoubleClick = false,
  25339. const bool lossOfFocusDiscardsChanges = false) throw();
  25340. /** Returns true if this option was set using setEditable(). */
  25341. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  25342. /** Returns true if this option was set using setEditable(). */
  25343. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  25344. /** Returns true if this option has been set in a call to setEditable(). */
  25345. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  25346. /** Returns true if the user can edit this label's text. */
  25347. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  25348. /** Makes the editor appear as if the label had been clicked by the user.
  25349. @see textWasEdited, setEditable
  25350. */
  25351. void showEditor();
  25352. /** Hides the editor if it was being shown.
  25353. @param discardCurrentEditorContents if true, the label's text will be
  25354. reset to whatever it was before the editor
  25355. was shown; if false, the current contents of the
  25356. editor will be used to set the label's text
  25357. before it is hidden.
  25358. */
  25359. void hideEditor (const bool discardCurrentEditorContents);
  25360. /** Returns true if the editor is currently focused and active. */
  25361. bool isBeingEdited() const throw();
  25362. juce_UseDebuggingNewOperator
  25363. protected:
  25364. /** @internal */
  25365. void paint (Graphics& g);
  25366. /** @internal */
  25367. void resized();
  25368. /** @internal */
  25369. void mouseUp (const MouseEvent& e);
  25370. /** @internal */
  25371. void mouseDoubleClick (const MouseEvent& e);
  25372. /** @internal */
  25373. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  25374. /** @internal */
  25375. void componentParentHierarchyChanged (Component& component);
  25376. /** @internal */
  25377. void componentVisibilityChanged (Component& component);
  25378. /** @internal */
  25379. void inputAttemptWhenModal();
  25380. /** @internal */
  25381. void focusGained (FocusChangeType);
  25382. /** @internal */
  25383. void enablementChanged();
  25384. /** @internal */
  25385. KeyboardFocusTraverser* createFocusTraverser();
  25386. /** @internal */
  25387. void textEditorTextChanged (TextEditor& editor);
  25388. /** @internal */
  25389. void textEditorReturnKeyPressed (TextEditor& editor);
  25390. /** @internal */
  25391. void textEditorEscapeKeyPressed (TextEditor& editor);
  25392. /** @internal */
  25393. void textEditorFocusLost (TextEditor& editor);
  25394. /** @internal */
  25395. void colourChanged();
  25396. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  25397. Subclasses can override this if they need to customise this component in some way.
  25398. */
  25399. virtual TextEditor* createEditorComponent();
  25400. /** Called after the user changes the text.
  25401. */
  25402. virtual void textWasEdited();
  25403. /** Called when the text has been altered.
  25404. */
  25405. virtual void textWasChanged();
  25406. /** Called when the text editor has just appeared, due to a user click or other
  25407. focus change.
  25408. */
  25409. virtual void editorShown (TextEditor* editorComponent);
  25410. /** Called when the text editor is going to be deleted, after editing has finished.
  25411. */
  25412. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  25413. private:
  25414. String text;
  25415. Font font;
  25416. Justification justification;
  25417. TextEditor* editor;
  25418. SortedSet <void*> listeners;
  25419. Component* ownerComponent;
  25420. ComponentDeletionWatcher* deletionWatcher;
  25421. int horizontalBorderSize, verticalBorderSize;
  25422. float minimumHorizontalScale;
  25423. bool editSingleClick : 1;
  25424. bool editDoubleClick : 1;
  25425. bool lossOfFocusDiscardsChanges : 1;
  25426. bool leftOfOwnerComp : 1;
  25427. bool updateFromTextEditorContents();
  25428. void callChangeListeners();
  25429. Label (const Label&);
  25430. const Label& operator= (const Label&);
  25431. };
  25432. #endif // __JUCE_LABEL_JUCEHEADER__
  25433. /********* End of inlined file: juce_Label.h *********/
  25434. class ComboBox;
  25435. /**
  25436. A class for receiving events from a ComboBox.
  25437. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  25438. method, and it will be called when the selected item in the box changes.
  25439. @see ComboBox::addListener, ComboBox::removeListener
  25440. */
  25441. class JUCE_API ComboBoxListener
  25442. {
  25443. public:
  25444. /** Destructor. */
  25445. virtual ~ComboBoxListener() {}
  25446. /** Called when a ComboBox has its selected item changed.
  25447. */
  25448. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  25449. };
  25450. /**
  25451. A component that lets the user choose from a drop-down list of choices.
  25452. The combo-box has a list of text strings, each with an associated id number,
  25453. that will be shown in the drop-down list when the user clicks on the component.
  25454. The currently selected choice is displayed in the combo-box, and this can
  25455. either be read-only text, or editable.
  25456. To find out when the user selects a different item or edits the text, you
  25457. can register a ComboBoxListener to receive callbacks.
  25458. @see ComboBoxListener
  25459. */
  25460. class JUCE_API ComboBox : public Component,
  25461. public SettableTooltipClient,
  25462. private LabelListener,
  25463. private AsyncUpdater
  25464. {
  25465. public:
  25466. /** Creates a combo-box.
  25467. On construction, the text field will be empty, so you should call the
  25468. setSelectedId() or setText() method to choose the initial value before
  25469. displaying it.
  25470. @param componentName the name to set for the component (see Component::setName())
  25471. */
  25472. ComboBox (const String& componentName);
  25473. /** Destructor. */
  25474. ~ComboBox();
  25475. /** Sets whether the test in the combo-box is editable.
  25476. The default state for a new ComboBox is non-editable, and can only be changed
  25477. by choosing from the drop-down list.
  25478. */
  25479. void setEditableText (const bool isEditable);
  25480. /** Returns true if the text is directly editable.
  25481. @see setEditableText
  25482. */
  25483. bool isTextEditable() const throw();
  25484. /** Sets the style of justification to be used for positioning the text.
  25485. The default is Justification::centredLeft. The text is displayed using a
  25486. Label component inside the ComboBox.
  25487. */
  25488. void setJustificationType (const Justification& justification) throw();
  25489. /** Returns the current justification for the text box.
  25490. @see setJustificationType
  25491. */
  25492. const Justification getJustificationType() const throw();
  25493. /** Adds an item to be shown in the drop-down list.
  25494. @param newItemText the text of the item to show in the list
  25495. @param newItemId an associated ID number that can be set or retrieved - see
  25496. getSelectedId() and setSelectedId()
  25497. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25498. */
  25499. void addItem (const String& newItemText,
  25500. const int newItemId) throw();
  25501. /** Adds a separator line to the drop-down list.
  25502. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25503. */
  25504. void addSeparator() throw();
  25505. /** Adds a heading to the drop-down list, so that you can group the items into
  25506. different sections.
  25507. The headings are indented slightly differently to set them apart from the
  25508. items on the list, and obviously can't be selected. You might want to add
  25509. separators between your sections too.
  25510. @see addItem, addSeparator
  25511. */
  25512. void addSectionHeading (const String& headingName) throw();
  25513. /** This allows items in the drop-down list to be selectively disabled.
  25514. When you add an item, it's enabled by default, but you can call this
  25515. method to change its status.
  25516. If you disable an item which is already selected, this won't change the
  25517. current selection - it just stops the user choosing that item from the list.
  25518. */
  25519. void setItemEnabled (const int itemId,
  25520. const bool isEnabled) throw();
  25521. /** Changes the text for an existing item.
  25522. */
  25523. void changeItemText (const int itemId,
  25524. const String& newText) throw();
  25525. /** Removes all the items from the drop-down list.
  25526. If this call causes the content to be cleared, then a change-message
  25527. will be broadcast unless dontSendChangeMessage is true.
  25528. @see addItem, removeItem, getNumItems
  25529. */
  25530. void clear (const bool dontSendChangeMessage = false);
  25531. /** Returns the number of items that have been added to the list.
  25532. Note that this doesn't include headers or separators.
  25533. */
  25534. int getNumItems() const throw();
  25535. /** Returns the text for one of the items in the list.
  25536. Note that this doesn't include headers or separators.
  25537. @param index the item's index from 0 to (getNumItems() - 1)
  25538. */
  25539. const String getItemText (const int index) const throw();
  25540. /** Returns the ID for one of the items in the list.
  25541. Note that this doesn't include headers or separators.
  25542. @param index the item's index from 0 to (getNumItems() - 1)
  25543. */
  25544. int getItemId (const int index) const throw();
  25545. /** Returns the ID of the item that's currently shown in the box.
  25546. If no item is selected, or if the text is editable and the user
  25547. has entered something which isn't one of the items in the list, then
  25548. this will return 0.
  25549. @see setSelectedId, getSelectedItemIndex, getText
  25550. */
  25551. int getSelectedId() const throw();
  25552. /** Sets one of the items to be the current selection.
  25553. This will set the ComboBox's text to that of the item that matches
  25554. this ID.
  25555. @param newItemId the new item to select
  25556. @param dontSendChangeMessage if set to true, this method won't trigger a
  25557. change notification
  25558. @see getSelectedId, setSelectedItemIndex, setText
  25559. */
  25560. void setSelectedId (const int newItemId,
  25561. const bool dontSendChangeMessage = false) throw();
  25562. /** Returns the index of the item that's currently shown in the box.
  25563. If no item is selected, or if the text is editable and the user
  25564. has entered something which isn't one of the items in the list, then
  25565. this will return -1.
  25566. @see setSelectedItemIndex, getSelectedId, getText
  25567. */
  25568. int getSelectedItemIndex() const throw();
  25569. /** Sets one of the items to be the current selection.
  25570. This will set the ComboBox's text to that of the item at the given
  25571. index in the list.
  25572. @param newItemIndex the new item to select
  25573. @param dontSendChangeMessage if set to true, this method won't trigger a
  25574. change notification
  25575. @see getSelectedItemIndex, setSelectedId, setText
  25576. */
  25577. void setSelectedItemIndex (const int newItemIndex,
  25578. const bool dontSendChangeMessage = false) throw();
  25579. /** Returns the text that is currently shown in the combo-box's text field.
  25580. If the ComboBox has editable text, then this text may have been edited
  25581. by the user; otherwise it will be one of the items from the list, or
  25582. possibly an empty string if nothing was selected.
  25583. @see setText, getSelectedId, getSelectedItemIndex
  25584. */
  25585. const String getText() const throw();
  25586. /** Sets the contents of the combo-box's text field.
  25587. The text passed-in will be set as the current text regardless of whether
  25588. it is one of the items in the list. If the current text isn't one of the
  25589. items, then getSelectedId() will return -1, otherwise it wil return
  25590. the approriate ID.
  25591. @param newText the text to select
  25592. @param dontSendChangeMessage if set to true, this method won't trigger a
  25593. change notification
  25594. @see getText
  25595. */
  25596. void setText (const String& newText,
  25597. const bool dontSendChangeMessage = false) throw();
  25598. /** Programmatically opens the text editor to allow the user to edit the current item.
  25599. This is the same effect as when the box is clicked-on.
  25600. @see Label::showEditor();
  25601. */
  25602. void showEditor();
  25603. /** Registers a listener that will be called when the box's content changes. */
  25604. void addListener (ComboBoxListener* const listener) throw();
  25605. /** Deregisters a previously-registered listener. */
  25606. void removeListener (ComboBoxListener* const listener) throw();
  25607. /** Sets a message to display when there is no item currently selected.
  25608. @see getTextWhenNothingSelected
  25609. */
  25610. void setTextWhenNothingSelected (const String& newMessage) throw();
  25611. /** Returns the text that is shown when no item is selected.
  25612. @see setTextWhenNothingSelected
  25613. */
  25614. const String getTextWhenNothingSelected() const throw();
  25615. /** Sets the message to show when there are no items in the list, and the user clicks
  25616. on the drop-down box.
  25617. By default it just says "no choices", but this lets you change it to something more
  25618. meaningful.
  25619. */
  25620. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25621. /** Returns the text shown when no items have been added to the list.
  25622. @see setTextWhenNoChoicesAvailable
  25623. */
  25624. const String getTextWhenNoChoicesAvailable() const throw();
  25625. /** Gives the ComboBox a tooltip. */
  25626. void setTooltip (const String& newTooltip);
  25627. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25628. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25629. methods.
  25630. To change the colours of the menu that pops up
  25631. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25632. */
  25633. enum ColourIds
  25634. {
  25635. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25636. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25637. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25638. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25639. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25640. };
  25641. /** @internal */
  25642. void labelTextChanged (Label*);
  25643. /** @internal */
  25644. void enablementChanged();
  25645. /** @internal */
  25646. void colourChanged();
  25647. /** @internal */
  25648. void focusGained (Component::FocusChangeType cause);
  25649. /** @internal */
  25650. void focusLost (Component::FocusChangeType cause);
  25651. /** @internal */
  25652. void handleAsyncUpdate();
  25653. /** @internal */
  25654. const String getTooltip() { return label->getTooltip(); }
  25655. /** @internal */
  25656. void mouseDown (const MouseEvent&);
  25657. /** @internal */
  25658. void mouseDrag (const MouseEvent&);
  25659. /** @internal */
  25660. void mouseUp (const MouseEvent&);
  25661. /** @internal */
  25662. void lookAndFeelChanged();
  25663. /** @internal */
  25664. void paint (Graphics&);
  25665. /** @internal */
  25666. void resized();
  25667. /** @internal */
  25668. bool keyStateChanged (const bool isKeyDown);
  25669. /** @internal */
  25670. bool keyPressed (const KeyPress&);
  25671. juce_UseDebuggingNewOperator
  25672. private:
  25673. struct ItemInfo
  25674. {
  25675. String name;
  25676. int itemId;
  25677. bool isEnabled : 1, isHeading : 1;
  25678. bool isSeparator() const throw();
  25679. bool isRealItem() const throw();
  25680. };
  25681. OwnedArray <ItemInfo> items;
  25682. int currentIndex;
  25683. bool isButtonDown;
  25684. bool separatorPending;
  25685. bool menuActive;
  25686. SortedSet <void*> listeners;
  25687. Label* label;
  25688. String textWhenNothingSelected, noChoicesMessage;
  25689. void showPopup();
  25690. ItemInfo* getItemForId (const int itemId) const throw();
  25691. ItemInfo* getItemForIndex (const int index) const throw();
  25692. ComboBox (const ComboBox&);
  25693. const ComboBox& operator= (const ComboBox&);
  25694. };
  25695. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25696. /********* End of inlined file: juce_ComboBox.h *********/
  25697. /**
  25698. Manages the state of some audio and midi i/o devices.
  25699. This class keeps tracks of a currently-selected audio device, through
  25700. with which it continuously streams data from an audio callback, as well as
  25701. one or more midi inputs.
  25702. The idea is that your application will create one global instance of this object,
  25703. and let it take care of creating and deleting specific types of audio devices
  25704. internally. So when the device is changed, your callbacks will just keep running
  25705. without having to worry about this.
  25706. The manager can save and reload all of its device settings as XML, which
  25707. makes it very easy for you to save and reload the audio setup of your
  25708. application.
  25709. And to make it easy to let the user change its settings, there's a component
  25710. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25711. device selection/sample-rate/latency controls.
  25712. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25713. call addAudioCallback() to register your audio callback with it, and use that to process
  25714. your audio data.
  25715. The manager also acts as a handy hub for incoming midi messages, allowing a
  25716. listener to register for messages from either a specific midi device, or from whatever
  25717. the current default midi input device is. The listener then doesn't have to worry about
  25718. re-registering with different midi devices if they are changed or deleted.
  25719. And yet another neat trick is that amount of CPU time being used is measured and
  25720. available with the getCpuUsage() method.
  25721. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25722. listeners whenever one of its settings is changed.
  25723. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25724. */
  25725. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25726. {
  25727. public:
  25728. /** Creates a default AudioDeviceManager.
  25729. Initially no audio device will be selected. You should call the initialise() method
  25730. and register an audio callback with setAudioCallback() before it'll be able to
  25731. actually make any noise.
  25732. */
  25733. AudioDeviceManager();
  25734. /** Destructor. */
  25735. ~AudioDeviceManager();
  25736. /**
  25737. This structure holds a set of properties describing the current audio setup.
  25738. @see AudioDeviceManager::setAudioDeviceSetup()
  25739. */
  25740. struct JUCE_API AudioDeviceSetup
  25741. {
  25742. AudioDeviceSetup();
  25743. bool operator== (const AudioDeviceSetup& other) const;
  25744. /** The name of the audio device used for output.
  25745. The name has to be one of the ones listed by the AudioDeviceManager's currently
  25746. selected device type.
  25747. This may be the same as the input device.
  25748. */
  25749. String outputDeviceName;
  25750. /** The name of the audio device used for input.
  25751. This may be the same as the output device.
  25752. */
  25753. String inputDeviceName;
  25754. /** The current sample rate.
  25755. This rate is used for both the input and output devices.
  25756. */
  25757. double sampleRate;
  25758. /** The buffer size, in samples.
  25759. This buffer size is used for both the input and output devices.
  25760. */
  25761. int bufferSize;
  25762. /** The set of active input channels.
  25763. The bits that are set in this array indicate the channels of the
  25764. input device that are active.
  25765. */
  25766. BitArray inputChannels;
  25767. /** If this is true, it indicates that the inputChannels array
  25768. should be ignored, and instead, the device's default channels
  25769. should be used.
  25770. */
  25771. bool useDefaultInputChannels;
  25772. /** The set of active output channels.
  25773. The bits that are set in this array indicate the channels of the
  25774. input device that are active.
  25775. */
  25776. BitArray outputChannels;
  25777. /** If this is true, it indicates that the outputChannels array
  25778. should be ignored, and instead, the device's default channels
  25779. should be used.
  25780. */
  25781. bool useDefaultOutputChannels;
  25782. };
  25783. /** Opens a set of audio devices ready for use.
  25784. This will attempt to open either a default audio device, or one that was
  25785. previously saved as XML.
  25786. @param numInputChannelsNeeded a minimum number of input channels needed
  25787. by your app.
  25788. @param numOutputChannelsNeeded a minimum number of output channels to open
  25789. @param savedState either a previously-saved state that was produced
  25790. by createStateXml(), or 0 if you want the manager
  25791. to choose the best device to open.
  25792. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25793. fails to open, then a default device will be used
  25794. instead. If false, then on failure, no device is
  25795. opened.
  25796. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25797. name, then that will be used as the default device
  25798. (assuming that there wasn't one specified in the XML).
  25799. The string can actually be a simple wildcard, containing "*"
  25800. and "?" characters
  25801. @param preferredSetupOptions if this is non-null, the structure will be used as the
  25802. set of preferred settings when opening the device. If you
  25803. use this parameter, the preferredDefaultDeviceName
  25804. field will be ignored
  25805. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25806. */
  25807. const String initialise (const int numInputChannelsNeeded,
  25808. const int numOutputChannelsNeeded,
  25809. const XmlElement* const savedState,
  25810. const bool selectDefaultDeviceOnFailure,
  25811. const String& preferredDefaultDeviceName = String::empty,
  25812. const AudioDeviceSetup* preferredSetupOptions = 0);
  25813. /** Returns some XML representing the current state of the manager.
  25814. This stores the current device, its samplerate, block size, etc, and
  25815. can be restored later with initialise().
  25816. */
  25817. XmlElement* createStateXml() const;
  25818. /** Returns the current device properties that are in use.
  25819. @see setAudioDeviceSetup
  25820. */
  25821. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25822. /** Changes the current device or its settings.
  25823. If you want to change a device property, like the current sample rate or
  25824. block size, you can call getAudioDeviceSetup() to retrieve the current
  25825. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  25826. and pass it back into this method to apply the new settings.
  25827. @param newSetup the settings that you'd like to use
  25828. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25829. settings will be taken as having been explicitly chosen by the
  25830. user, and the next time createStateXml() is called, these settings
  25831. will be returned. If it's false, then the device is treated as a
  25832. temporary or default device, and a call to createStateXml() will
  25833. return either the last settings that were made with treatAsChosenDevice
  25834. as true, or the last XML settings that were passed into initialise().
  25835. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25836. @see getAudioDeviceSetup
  25837. */
  25838. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25839. const bool treatAsChosenDevice);
  25840. /** Returns the currently-active audio device. */
  25841. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25842. /** Returns the type of audio device currently in use.
  25843. @see setCurrentAudioDeviceType
  25844. */
  25845. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25846. /** Returns the currently active audio device type object.
  25847. Don't keep a copy of this pointer - it's owned by the device manager and could
  25848. change at any time.
  25849. */
  25850. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25851. /** Changes the class of audio device being used.
  25852. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  25853. this because there's only one type: CoreAudio.
  25854. For a list of types, see getAvailableDeviceTypes().
  25855. */
  25856. void setCurrentAudioDeviceType (const String& type,
  25857. const bool treatAsChosenDevice);
  25858. /** Closes the currently-open device.
  25859. You can call restartLastAudioDevice() later to reopen it in the same state
  25860. that it was just in.
  25861. */
  25862. void closeAudioDevice();
  25863. /** Tries to reload the last audio device that was running.
  25864. Note that this only reloads the last device that was running before
  25865. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25866. and can only be called after a device has been opened with SetAudioDevice().
  25867. If a device is already open, this call will do nothing.
  25868. */
  25869. void restartLastAudioDevice();
  25870. /** Registers an audio callback to be used.
  25871. The manager will redirect callbacks from whatever audio device is currently
  25872. in use to all registered callback objects. If more than one callback is
  25873. active, they will all be given the same input data, and their outputs will
  25874. be summed.
  25875. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  25876. object before returning.
  25877. To remove a callback, use removeAudioCallback().
  25878. */
  25879. void addAudioCallback (AudioIODeviceCallback* newCallback);
  25880. /** Deregisters a previously added callback.
  25881. If necessary, this method will invoke audioDeviceStopped() on the callback
  25882. object before returning.
  25883. @see addAudioCallback
  25884. */
  25885. void removeAudioCallback (AudioIODeviceCallback* callback);
  25886. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25887. Returns a value between 0 and 1.0
  25888. */
  25889. double getCpuUsage() const;
  25890. /** Enables or disables a midi input device.
  25891. The list of devices can be obtained with the MidiInput::getDevices() method.
  25892. Any incoming messages from enabled input devices will be forwarded on to all the
  25893. listeners that have been registered with the addMidiInputCallback() method. They
  25894. can either register for messages from a particular device, or from just the
  25895. "default" midi input.
  25896. Routing the midi input via an AudioDeviceManager means that when a listener
  25897. registers for the default midi input, this default device can be changed by the
  25898. manager without the listeners having to know about it or re-register.
  25899. It also means that a listener can stay registered for a midi input that is disabled
  25900. or not present, so that when the input is re-enabled, the listener will start
  25901. receiving messages again.
  25902. @see addMidiInputCallback, isMidiInputEnabled
  25903. */
  25904. void setMidiInputEnabled (const String& midiInputDeviceName,
  25905. const bool enabled);
  25906. /** Returns true if a given midi input device is being used.
  25907. @see setMidiInputEnabled
  25908. */
  25909. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25910. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25911. The device name can be empty to indicate that it wants events from whatever the
  25912. current "default" device is. Or it can be the name of one of the midi input devices
  25913. (see MidiInput::getDevices() for the names).
  25914. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25915. events forwarded on to listeners.
  25916. */
  25917. void addMidiInputCallback (const String& midiInputDeviceName,
  25918. MidiInputCallback* callback);
  25919. /** Removes a listener that was previously registered with addMidiInputCallback().
  25920. */
  25921. void removeMidiInputCallback (const String& midiInputDeviceName,
  25922. MidiInputCallback* callback);
  25923. /** Sets a midi output device to use as the default.
  25924. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25925. The specified device will be opened automatically and can be retrieved with the
  25926. getDefaultMidiOutput() method.
  25927. Pass in an empty string to deselect all devices. For the default device, you
  25928. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25929. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25930. */
  25931. void setDefaultMidiOutput (const String& deviceName);
  25932. /** Returns the name of the default midi output.
  25933. @see setDefaultMidiOutput, getDefaultMidiOutput
  25934. */
  25935. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25936. /** Returns the current default midi output device.
  25937. If no device has been selected, or the device can't be opened, this will
  25938. return 0.
  25939. @see getDefaultMidiOutputName
  25940. */
  25941. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25942. /** Returns a list of the types of device supported.
  25943. */
  25944. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25945. /** Creates a list of available types.
  25946. This will add a set of new AudioIODeviceType objects to the specified list, to
  25947. represent each available types of device.
  25948. You can override this if your app needs to do something specific, like avoid
  25949. using DirectSound devices, etc.
  25950. */
  25951. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25952. /** Plays a beep through the current audio device.
  25953. This is here to allow the audio setup UI panels to easily include a "test"
  25954. button so that the user can check where the audio is coming from.
  25955. */
  25956. void playTestSound();
  25957. /** Turns on level-measuring.
  25958. When enabled, the device manager will measure the peak input level
  25959. across all channels, and you can get this level by calling getCurrentInputLevel().
  25960. This is mainly intended for audio setup UI panels to use to create a mic
  25961. level display, so that the user can check that they've selected the right
  25962. device.
  25963. A simple filter is used to make the level decay smoothly, but this is
  25964. only intended for giving rough feedback, and not for any kind of accurate
  25965. measurement.
  25966. */
  25967. void enableInputLevelMeasurement (const bool enableMeasurement);
  25968. /** Returns the current input level.
  25969. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25970. See enableInputLevelMeasurement() for more info.
  25971. */
  25972. double getCurrentInputLevel() const;
  25973. juce_UseDebuggingNewOperator
  25974. private:
  25975. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25976. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25977. AudioDeviceSetup currentSetup;
  25978. AudioIODevice* currentAudioDevice;
  25979. SortedSet <AudioIODeviceCallback*> callbacks;
  25980. int numInputChansNeeded, numOutputChansNeeded;
  25981. String currentDeviceType;
  25982. BitArray inputChannels, outputChannels;
  25983. XmlElement* lastExplicitSettings;
  25984. mutable bool listNeedsScanning;
  25985. bool useInputNames;
  25986. int inputLevelMeasurementEnabledCount;
  25987. double inputLevel;
  25988. AudioSampleBuffer* testSound;
  25989. int testSoundPosition;
  25990. AudioSampleBuffer tempBuffer;
  25991. StringArray midiInsFromXml;
  25992. OwnedArray <MidiInput> enabledMidiInputs;
  25993. Array <MidiInputCallback*> midiCallbacks;
  25994. Array <MidiInput*> midiCallbackDevices;
  25995. String defaultMidiOutputName;
  25996. MidiOutput* defaultMidiOutput;
  25997. CriticalSection audioCallbackLock, midiCallbackLock;
  25998. double cpuUsageMs, timeToCpuScale;
  25999. class CallbackHandler : public AudioIODeviceCallback,
  26000. public MidiInputCallback
  26001. {
  26002. public:
  26003. AudioDeviceManager* owner;
  26004. void audioDeviceIOCallback (const float** inputChannelData,
  26005. int totalNumInputChannels,
  26006. float** outputChannelData,
  26007. int totalNumOutputChannels,
  26008. int numSamples);
  26009. void audioDeviceAboutToStart (AudioIODevice*);
  26010. void audioDeviceStopped();
  26011. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  26012. };
  26013. CallbackHandler callbackHandler;
  26014. friend class CallbackHandler;
  26015. void audioDeviceIOCallbackInt (const float** inputChannelData,
  26016. int totalNumInputChannels,
  26017. float** outputChannelData,
  26018. int totalNumOutputChannels,
  26019. int numSamples);
  26020. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  26021. void audioDeviceStoppedInt();
  26022. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  26023. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  26024. const BitArray& ins, const BitArray& outs);
  26025. void stopDevice();
  26026. void updateXml();
  26027. void createDeviceTypesIfNeeded();
  26028. void scanDevicesIfNeeded();
  26029. void deleteCurrentDevice();
  26030. double chooseBestSampleRate (double preferred) const;
  26031. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  26032. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  26033. AudioDeviceManager (const AudioDeviceManager&);
  26034. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  26035. };
  26036. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26037. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  26038. #endif
  26039. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  26040. #endif
  26041. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26042. #endif
  26043. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  26044. #endif
  26045. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  26046. #endif
  26047. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  26048. /********* Start of inlined file: juce_Sampler.h *********/
  26049. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  26050. #define __JUCE_SAMPLER_JUCEHEADER__
  26051. /********* Start of inlined file: juce_Synthesiser.h *********/
  26052. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26053. #define __JUCE_SYNTHESISER_JUCEHEADER__
  26054. /**
  26055. Describes one of the sounds that a Synthesiser can play.
  26056. A synthesiser can contain one or more sounds, and a sound can choose which
  26057. midi notes and channels can trigger it.
  26058. The SynthesiserSound is a passive class that just describes what the sound is -
  26059. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  26060. more than one SynthesiserVoice to play the same sound at the same time.
  26061. @see Synthesiser, SynthesiserVoice
  26062. */
  26063. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  26064. {
  26065. protected:
  26066. SynthesiserSound();
  26067. public:
  26068. /** Destructor. */
  26069. virtual ~SynthesiserSound();
  26070. /** Returns true if this sound should be played when a given midi note is pressed.
  26071. The Synthesiser will use this information when deciding which sounds to trigger
  26072. for a given note.
  26073. */
  26074. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  26075. /** Returns true if the sound should be triggered by midi events on a given channel.
  26076. The Synthesiser will use this information when deciding which sounds to trigger
  26077. for a given note.
  26078. */
  26079. virtual bool appliesToChannel (const int midiChannel) = 0;
  26080. /**
  26081. */
  26082. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  26083. juce_UseDebuggingNewOperator
  26084. };
  26085. /**
  26086. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  26087. A voice plays a single sound at a time, and a synthesiser holds an array of
  26088. voices so that it can play polyphonically.
  26089. @see Synthesiser, SynthesiserSound
  26090. */
  26091. class JUCE_API SynthesiserVoice
  26092. {
  26093. public:
  26094. /** Creates a voice. */
  26095. SynthesiserVoice();
  26096. /** Destructor. */
  26097. virtual ~SynthesiserVoice();
  26098. /** Returns the midi note that this voice is currently playing.
  26099. Returns a value less than 0 if no note is playing.
  26100. */
  26101. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  26102. /** Returns the sound that this voice is currently playing.
  26103. Returns 0 if it's not playing.
  26104. */
  26105. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  26106. /** Must return true if this voice object is capable of playing the given sound.
  26107. If there are different classes of sound, and different classes of voice, a voice can
  26108. choose which ones it wants to take on.
  26109. A typical implementation of this method may just return true if there's only one type
  26110. of voice and sound, or it might check the type of the sound object passed-in and
  26111. see if it's one that it understands.
  26112. */
  26113. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  26114. /** Called to start a new note.
  26115. This will be called during the rendering callback, so must be fast and thread-safe.
  26116. */
  26117. virtual void startNote (const int midiNoteNumber,
  26118. const float velocity,
  26119. SynthesiserSound* sound,
  26120. const int currentPitchWheelPosition) = 0;
  26121. /** Called to stop a note.
  26122. This will be called during the rendering callback, so must be fast and thread-safe.
  26123. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  26124. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  26125. and allow the synth to reassign it another sound.
  26126. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  26127. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  26128. finishes playing (during the rendering callback), it must make sure that it calls
  26129. clearCurrentNote().
  26130. */
  26131. virtual void stopNote (const bool allowTailOff) = 0;
  26132. /** Called to let the voice know that the pitch wheel has been moved.
  26133. This will be called during the rendering callback, so must be fast and thread-safe.
  26134. */
  26135. virtual void pitchWheelMoved (const int newValue) = 0;
  26136. /** Called to let the voice know that a midi controller has been moved.
  26137. This will be called during the rendering callback, so must be fast and thread-safe.
  26138. */
  26139. virtual void controllerMoved (const int controllerNumber,
  26140. const int newValue) = 0;
  26141. /** Renders the next block of data for this voice.
  26142. The output audio data must be added to the current contents of the buffer provided.
  26143. Only the region of the buffer between startSample and (startSample + numSamples)
  26144. should be altered by this method.
  26145. If the voice is currently silent, it should just return without doing anything.
  26146. If the sound that the voice is playing finishes during the course of this rendered
  26147. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  26148. The size of the blocks that are rendered can change each time it is called, and may
  26149. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  26150. the voice's methods will be called to tell it about note and controller events.
  26151. */
  26152. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  26153. int startSample,
  26154. int numSamples) = 0;
  26155. /** Returns true if the voice is currently playing a sound which is mapped to the given
  26156. midi channel.
  26157. If it's not currently playing, this will return false.
  26158. */
  26159. bool isPlayingChannel (const int midiChannel) const;
  26160. /** Changes the voice's reference sample rate.
  26161. The rate is set so that subclasses know the output rate and can set their pitch
  26162. accordingly.
  26163. This method is called by the synth, and subclasses can access the current rate with
  26164. the currentSampleRate member.
  26165. */
  26166. void setCurrentPlaybackSampleRate (const double newRate);
  26167. juce_UseDebuggingNewOperator
  26168. protected:
  26169. /** Returns the current target sample rate at which rendering is being done.
  26170. This is available for subclasses so they can pitch things correctly.
  26171. */
  26172. double getSampleRate() const throw() { return currentSampleRate; }
  26173. /** Resets the state of this voice after a sound has finished playing.
  26174. The subclass must call this when it finishes playing a note and becomes available
  26175. to play new ones.
  26176. It must either call it in the stopNote() method, or if the voice is tailing off,
  26177. then it should call it later during the renderNextBlock method, as soon as it
  26178. finishes its tail-off.
  26179. It can also be called at any time during the render callback if the sound happens
  26180. to have finished, e.g. if it's playing a sample and the sample finishes.
  26181. */
  26182. void clearCurrentNote();
  26183. private:
  26184. friend class Synthesiser;
  26185. double currentSampleRate;
  26186. int currentlyPlayingNote;
  26187. uint32 noteOnTime;
  26188. SynthesiserSound::Ptr currentlyPlayingSound;
  26189. };
  26190. /**
  26191. Base class for a musical device that can play sounds.
  26192. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  26193. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  26194. which can play back one of these sounds.
  26195. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  26196. set of sounds, and a set of voices it can use to play them. If you only give it
  26197. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  26198. have available.
  26199. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  26200. events that go in will be scanned for note on/off messages, and these are used to
  26201. start and stop the voices playing the appropriate sounds.
  26202. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  26203. noteOff() and other controller methods.
  26204. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  26205. what the target playback rate is. This value is passed on to the voices so that
  26206. they can pitch their output correctly.
  26207. */
  26208. class JUCE_API Synthesiser
  26209. {
  26210. public:
  26211. /** Creates a new synthesiser.
  26212. You'll need to add some sounds and voices before it'll make any sound..
  26213. */
  26214. Synthesiser();
  26215. /** Destructor. */
  26216. virtual ~Synthesiser();
  26217. /** Deletes all voices. */
  26218. void clearVoices();
  26219. /** Returns the number of voices that have been added. */
  26220. int getNumVoices() const throw() { return voices.size(); }
  26221. /** Returns one of the voices that have been added. */
  26222. SynthesiserVoice* getVoice (const int index) const throw();
  26223. /** Adds a new voice to the synth.
  26224. All the voices should be the same class of object and are treated equally.
  26225. The object passed in will be managed by the synthesiser, which will delete
  26226. it later on when no longer needed. The caller should not retain a pointer to the
  26227. voice.
  26228. */
  26229. void addVoice (SynthesiserVoice* const newVoice);
  26230. /** Deletes one of the voices. */
  26231. void removeVoice (const int index);
  26232. /** Deletes all sounds. */
  26233. void clearSounds();
  26234. /** Returns the number of sounds that have been added to the synth. */
  26235. int getNumSounds() const throw() { return sounds.size(); }
  26236. /** Returns one of the sounds. */
  26237. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  26238. /** Adds a new sound to the synthesiser.
  26239. The object passed in is reference counted, so will be deleted when it is removed
  26240. from the synthesiser, and when no voices are still using it.
  26241. */
  26242. void addSound (const SynthesiserSound::Ptr& newSound);
  26243. /** Removes and deletes one of the sounds. */
  26244. void removeSound (const int index);
  26245. /** If set to true, then the synth will try to take over an existing voice if
  26246. it runs out and needs to play another note.
  26247. The value of this boolean is passed into findFreeVoice(), so the result will
  26248. depend on the implementation of this method.
  26249. */
  26250. void setNoteStealingEnabled (const bool shouldStealNotes);
  26251. /** Returns true if note-stealing is enabled.
  26252. @see setNoteStealingEnabled
  26253. */
  26254. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  26255. /** Triggers a note-on event.
  26256. The default method here will find all the sounds that want to be triggered by
  26257. this note/channel. For each sound, it'll try to find a free voice, and use the
  26258. voice to start playing the sound.
  26259. Subclasses might want to override this if they need a more complex algorithm.
  26260. This method will be called automatically according to the midi data passed into
  26261. renderNextBlock(), but may be called explicitly too.
  26262. */
  26263. virtual void noteOn (const int midiChannel,
  26264. const int midiNoteNumber,
  26265. const float velocity);
  26266. /** Triggers a note-off event.
  26267. This will turn off any voices that are playing a sound for the given note/channel.
  26268. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  26269. (if they can do). If this is false, the notes will all be cut off immediately.
  26270. This method will be called automatically according to the midi data passed into
  26271. renderNextBlock(), but may be called explicitly too.
  26272. */
  26273. virtual void noteOff (const int midiChannel,
  26274. const int midiNoteNumber,
  26275. const bool allowTailOff);
  26276. /** Turns off all notes.
  26277. This will turn off any voices that are playing a sound on the given midi channel.
  26278. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  26279. which channel they're playing.
  26280. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  26281. (if they can do). If this is false, the notes will all be cut off immediately.
  26282. This method will be called automatically according to the midi data passed into
  26283. renderNextBlock(), but may be called explicitly too.
  26284. */
  26285. virtual void allNotesOff (const int midiChannel,
  26286. const bool allowTailOff);
  26287. /** Sends a pitch-wheel message.
  26288. This will send a pitch-wheel message to any voices that are playing sounds on
  26289. the given midi channel.
  26290. This method will be called automatically according to the midi data passed into
  26291. renderNextBlock(), but may be called explicitly too.
  26292. @param midiChannel the midi channel for the event
  26293. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  26294. */
  26295. virtual void handlePitchWheel (const int midiChannel,
  26296. const int wheelValue);
  26297. /** Sends a midi controller message.
  26298. This will send a midi controller message to any voices that are playing sounds on
  26299. the given midi channel.
  26300. This method will be called automatically according to the midi data passed into
  26301. renderNextBlock(), but may be called explicitly too.
  26302. @param midiChannel the midi channel for the event
  26303. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  26304. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  26305. */
  26306. virtual void handleController (const int midiChannel,
  26307. const int controllerNumber,
  26308. const int controllerValue);
  26309. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  26310. render.
  26311. This value is propagated to the voices so that they can use it to render the correct
  26312. pitches.
  26313. */
  26314. void setCurrentPlaybackSampleRate (const double sampleRate);
  26315. /** Creates the next block of audio output.
  26316. This will process the next numSamples of data from all the voices, and add that output
  26317. to the audio block supplied, starting from the offset specified. Note that the
  26318. data will be added to the current contents of the buffer, so you should clear it
  26319. before calling this method if necessary.
  26320. The midi events in the inputMidi buffer are parsed for note and controller events,
  26321. and these are used to trigger the voices. Note that the startSample offset applies
  26322. both to the audio output buffer and the midi input buffer, so any midi events
  26323. with timestamps outside the specified region will be ignored.
  26324. */
  26325. void renderNextBlock (AudioSampleBuffer& outputAudio,
  26326. const MidiBuffer& inputMidi,
  26327. int startSample,
  26328. int numSamples);
  26329. juce_UseDebuggingNewOperator
  26330. protected:
  26331. /** This is used to control access to the rendering callback and the note trigger methods. */
  26332. CriticalSection lock;
  26333. OwnedArray <SynthesiserVoice> voices;
  26334. ReferenceCountedArray <SynthesiserSound> sounds;
  26335. /** The last pitch-wheel values for each midi channel. */
  26336. int lastPitchWheelValues [16];
  26337. /** Searches through the voices to find one that's not currently playing, and which
  26338. can play the given sound.
  26339. Returns 0 if all voices are busy and stealing isn't enabled.
  26340. This can be overridden to implement custom voice-stealing algorithms.
  26341. */
  26342. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  26343. const bool stealIfNoneAvailable) const;
  26344. /** Starts a specified voice playing a particular sound.
  26345. You'll probably never need to call this, it's used internally by noteOn(), but
  26346. may be needed by subclasses for custom behaviours.
  26347. */
  26348. void startVoice (SynthesiserVoice* const voice,
  26349. SynthesiserSound* const sound,
  26350. const int midiChannel,
  26351. const int midiNoteNumber,
  26352. const float velocity);
  26353. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  26354. int findFreeVoice (const bool) const { return 0; }
  26355. private:
  26356. double sampleRate;
  26357. uint32 lastNoteOnCounter;
  26358. bool shouldStealNotes;
  26359. Synthesiser (const Synthesiser&);
  26360. const Synthesiser& operator= (const Synthesiser&);
  26361. };
  26362. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  26363. /********* End of inlined file: juce_Synthesiser.h *********/
  26364. /**
  26365. A subclass of SynthesiserSound that represents a sampled audio clip.
  26366. This is a pretty basic sampler, and just attempts to load the whole audio stream
  26367. into memory.
  26368. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26369. give it some SampledSound objects to play.
  26370. @see SamplerVoice, Synthesiser, SynthesiserSound
  26371. */
  26372. class JUCE_API SamplerSound : public SynthesiserSound
  26373. {
  26374. public:
  26375. /** Creates a sampled sound from an audio reader.
  26376. This will attempt to load the audio from the source into memory and store
  26377. it in this object.
  26378. @param name a name for the sample
  26379. @param source the audio to load. This object can be safely deleted by the
  26380. caller after this constructor returns
  26381. @param midiNotes the set of midi keys that this sound should be played on. This
  26382. is used by the SynthesiserSound::appliesToNote() method
  26383. @param midiNoteForNormalPitch the midi note at which the sample should be played
  26384. with its natural rate. All other notes will be pitched
  26385. up or down relative to this one
  26386. @param attackTimeSecs the attack (fade-in) time, in seconds
  26387. @param releaseTimeSecs the decay (fade-out) time, in seconds
  26388. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  26389. source, in seconds
  26390. */
  26391. SamplerSound (const String& name,
  26392. AudioFormatReader& source,
  26393. const BitArray& midiNotes,
  26394. const int midiNoteForNormalPitch,
  26395. const double attackTimeSecs,
  26396. const double releaseTimeSecs,
  26397. const double maxSampleLengthSeconds);
  26398. /** Destructor. */
  26399. ~SamplerSound();
  26400. /** Returns the sample's name */
  26401. const String& getName() const throw() { return name; }
  26402. /** Returns the audio sample data.
  26403. This could be 0 if there was a problem loading it.
  26404. */
  26405. AudioSampleBuffer* getAudioData() const throw() { return data; }
  26406. bool appliesToNote (const int midiNoteNumber);
  26407. bool appliesToChannel (const int midiChannel);
  26408. juce_UseDebuggingNewOperator
  26409. private:
  26410. friend class SamplerVoice;
  26411. String name;
  26412. AudioSampleBuffer* data;
  26413. double sourceSampleRate;
  26414. BitArray midiNotes;
  26415. int length, attackSamples, releaseSamples;
  26416. int midiRootNote;
  26417. };
  26418. /**
  26419. A subclass of SynthesiserVoice that can play a SamplerSound.
  26420. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26421. give it some SampledSound objects to play.
  26422. @see SamplerSound, Synthesiser, SynthesiserVoice
  26423. */
  26424. class JUCE_API SamplerVoice : public SynthesiserVoice
  26425. {
  26426. public:
  26427. /** Creates a SamplerVoice.
  26428. */
  26429. SamplerVoice();
  26430. /** Destructor. */
  26431. ~SamplerVoice();
  26432. bool canPlaySound (SynthesiserSound* sound);
  26433. void startNote (const int midiNoteNumber,
  26434. const float velocity,
  26435. SynthesiserSound* sound,
  26436. const int currentPitchWheelPosition);
  26437. void stopNote (const bool allowTailOff);
  26438. void pitchWheelMoved (const int newValue);
  26439. void controllerMoved (const int controllerNumber,
  26440. const int newValue);
  26441. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  26442. juce_UseDebuggingNewOperator
  26443. private:
  26444. double pitchRatio;
  26445. double sourceSamplePosition;
  26446. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  26447. bool isInAttack, isInRelease;
  26448. };
  26449. #endif // __JUCE_SAMPLER_JUCEHEADER__
  26450. /********* End of inlined file: juce_Sampler.h *********/
  26451. #endif
  26452. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26453. #endif
  26454. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26455. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  26456. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26457. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26458. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  26459. /**
  26460. Implements a plugin format manager for AudioUnits.
  26461. */
  26462. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  26463. {
  26464. public:
  26465. AudioUnitPluginFormat();
  26466. ~AudioUnitPluginFormat();
  26467. const String getName() const { return "AudioUnit"; }
  26468. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26469. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26470. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26471. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26472. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26473. bool doesPluginStillExist (const PluginDescription& desc);
  26474. const FileSearchPath getDefaultLocationsToSearch();
  26475. juce_UseDebuggingNewOperator
  26476. private:
  26477. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  26478. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  26479. };
  26480. #endif
  26481. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26482. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  26483. #endif
  26484. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26485. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  26486. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26487. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26488. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  26489. // Sorry, this file is just a placeholder at the moment!...
  26490. /**
  26491. Implements a plugin format manager for DirectX plugins.
  26492. */
  26493. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  26494. {
  26495. public:
  26496. DirectXPluginFormat();
  26497. ~DirectXPluginFormat();
  26498. const String getName() const { return "DirectX"; }
  26499. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26500. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26501. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26502. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26503. const FileSearchPath getDefaultLocationsToSearch();
  26504. juce_UseDebuggingNewOperator
  26505. private:
  26506. DirectXPluginFormat (const DirectXPluginFormat&);
  26507. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  26508. };
  26509. #endif
  26510. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26511. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  26512. #endif
  26513. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26514. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  26515. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26516. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26517. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  26518. // Sorry, this file is just a placeholder at the moment!...
  26519. /**
  26520. Implements a plugin format manager for DirectX plugins.
  26521. */
  26522. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  26523. {
  26524. public:
  26525. LADSPAPluginFormat();
  26526. ~LADSPAPluginFormat();
  26527. const String getName() const { return "LADSPA"; }
  26528. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26529. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26530. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26531. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26532. const FileSearchPath getDefaultLocationsToSearch();
  26533. juce_UseDebuggingNewOperator
  26534. private:
  26535. LADSPAPluginFormat (const LADSPAPluginFormat&);
  26536. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  26537. };
  26538. #endif
  26539. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26540. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  26541. #endif
  26542. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26543. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  26544. #ifdef __aeffect__
  26545. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26546. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26547. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26548. events to the list.
  26549. This is used by both the VST hosting code and the plugin wrapper.
  26550. */
  26551. class VSTMidiEventList
  26552. {
  26553. public:
  26554. VSTMidiEventList()
  26555. : events (0), numEventsUsed (0), numEventsAllocated (0)
  26556. {
  26557. }
  26558. ~VSTMidiEventList()
  26559. {
  26560. freeEvents();
  26561. }
  26562. void clear()
  26563. {
  26564. numEventsUsed = 0;
  26565. if (events != 0)
  26566. events->numEvents = 0;
  26567. }
  26568. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26569. {
  26570. ensureSize (numEventsUsed + 1);
  26571. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26572. events->numEvents = ++numEventsUsed;
  26573. if (numBytes <= 4)
  26574. {
  26575. if (e->type == kVstSysExType)
  26576. {
  26577. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26578. e->type = kVstMidiType;
  26579. e->byteSize = sizeof (VstMidiEvent);
  26580. e->noteLength = 0;
  26581. e->noteOffset = 0;
  26582. e->detune = 0;
  26583. e->noteOffVelocity = 0;
  26584. }
  26585. e->deltaFrames = frameOffset;
  26586. memcpy (e->midiData, midiData, numBytes);
  26587. }
  26588. else
  26589. {
  26590. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26591. if (se->type == kVstSysExType)
  26592. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26593. else
  26594. se->sysexDump = (char*) juce_malloc (numBytes);
  26595. memcpy (se->sysexDump, midiData, numBytes);
  26596. se->type = kVstSysExType;
  26597. se->byteSize = sizeof (VstMidiSysexEvent);
  26598. se->deltaFrames = frameOffset;
  26599. se->flags = 0;
  26600. se->dumpBytes = numBytes;
  26601. se->resvd1 = 0;
  26602. se->resvd2 = 0;
  26603. }
  26604. }
  26605. // Handy method to pull the events out of an event buffer supplied by the host
  26606. // or plugin.
  26607. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26608. {
  26609. for (int i = 0; i < events->numEvents; ++i)
  26610. {
  26611. const VstEvent* const e = events->events[i];
  26612. if (e != 0)
  26613. {
  26614. if (e->type == kVstMidiType)
  26615. {
  26616. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26617. 4, e->deltaFrames);
  26618. }
  26619. else if (e->type == kVstSysExType)
  26620. {
  26621. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26622. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26623. e->deltaFrames);
  26624. }
  26625. }
  26626. }
  26627. }
  26628. void ensureSize (int numEventsNeeded)
  26629. {
  26630. if (numEventsNeeded > numEventsAllocated)
  26631. {
  26632. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26633. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26634. if (events == 0)
  26635. events = (VstEvents*) juce_calloc (size);
  26636. else
  26637. events = (VstEvents*) juce_realloc (events, size);
  26638. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26639. {
  26640. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26641. (int) sizeof (VstMidiSysexEvent)));
  26642. e->type = kVstMidiType;
  26643. e->byteSize = sizeof (VstMidiEvent);
  26644. events->events[i] = (VstEvent*) e;
  26645. }
  26646. numEventsAllocated = numEventsNeeded;
  26647. }
  26648. }
  26649. void freeEvents()
  26650. {
  26651. if (events != 0)
  26652. {
  26653. for (int i = numEventsAllocated; --i >= 0;)
  26654. {
  26655. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26656. if (e->type == kVstSysExType)
  26657. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26658. juce_free (e);
  26659. }
  26660. juce_free (events);
  26661. events = 0;
  26662. numEventsUsed = 0;
  26663. numEventsAllocated = 0;
  26664. }
  26665. }
  26666. VstEvents* events;
  26667. private:
  26668. int numEventsUsed, numEventsAllocated;
  26669. };
  26670. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26671. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26672. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  26673. #endif
  26674. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26675. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  26676. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26677. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26678. #if JUCE_PLUGINHOST_VST
  26679. /**
  26680. Implements a plugin format manager for VSTs.
  26681. */
  26682. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  26683. {
  26684. public:
  26685. VSTPluginFormat();
  26686. ~VSTPluginFormat();
  26687. const String getName() const { return "VST"; }
  26688. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26689. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26690. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26691. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26692. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26693. bool doesPluginStillExist (const PluginDescription& desc);
  26694. const FileSearchPath getDefaultLocationsToSearch();
  26695. juce_UseDebuggingNewOperator
  26696. private:
  26697. VSTPluginFormat (const VSTPluginFormat&);
  26698. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  26699. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  26700. };
  26701. #endif
  26702. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26703. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  26704. #endif
  26705. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26706. #endif
  26707. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  26708. #endif
  26709. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26710. #endif
  26711. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  26712. #endif
  26713. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  26714. #endif
  26715. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26716. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  26717. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26718. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26719. /**
  26720. Scans a directory for plugins, and adds them to a KnownPluginList.
  26721. To use one of these, create it and call scanNextFile() repeatedly, until
  26722. it returns false.
  26723. */
  26724. class JUCE_API PluginDirectoryScanner
  26725. {
  26726. public:
  26727. /**
  26728. Creates a scanner.
  26729. @param listToAddResultsTo this will get the new types added to it.
  26730. @param formatToLookFor this is the type of format that you want to look for
  26731. @param directoriesToSearch the path to search
  26732. @param searchRecursively true to search recursively
  26733. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  26734. be used as a file to store the names of any plugins
  26735. that crash during initialisation. If there are
  26736. any plugins listed in it, then these will always
  26737. be scanned after all other possible files have
  26738. been tried - in this way, even if there's a few
  26739. dodgy plugins in your path, then a couple of rescans
  26740. will still manage to find all the proper plugins.
  26741. It's probably best to choose a file in the user's
  26742. application data directory (alongside your app's
  26743. settings file) for this. The file format it uses
  26744. is just a list of filenames of the modules that
  26745. failed.
  26746. */
  26747. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  26748. AudioPluginFormat& formatToLookFor,
  26749. FileSearchPath directoriesToSearch,
  26750. const bool searchRecursively,
  26751. const File& deadMansPedalFile);
  26752. /** Destructor. */
  26753. ~PluginDirectoryScanner();
  26754. /** Tries the next likely-looking file.
  26755. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26756. re-tested if it's not already in the list, or if the file's modification
  26757. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26758. false, the file will always be reloaded and tested.
  26759. Returns false when there are no more files to try.
  26760. */
  26761. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26762. /** Returns the description of the plugin that will be scanned during the next
  26763. call to scanNextFile().
  26764. This is handy if you want to show the user which file is currently getting
  26765. scanned.
  26766. */
  26767. const String getNextPluginFileThatWillBeScanned() const throw();
  26768. /** Returns the estimated progress, between 0 and 1.
  26769. */
  26770. float getProgress() const { return progress; }
  26771. /** This returns a list of all the filenames of things that looked like being
  26772. a plugin file, but which failed to open for some reason.
  26773. */
  26774. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26775. juce_UseDebuggingNewOperator
  26776. private:
  26777. KnownPluginList& list;
  26778. AudioPluginFormat& format;
  26779. StringArray filesOrIdentifiersToScan;
  26780. File deadMansPedalFile;
  26781. StringArray failedFiles;
  26782. int nextIndex;
  26783. float progress;
  26784. const StringArray getDeadMansPedalFile() throw();
  26785. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26786. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26787. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26788. };
  26789. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26790. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26791. #endif
  26792. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26793. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26794. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26795. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26796. /********* Start of inlined file: juce_ListBox.h *********/
  26797. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26798. #define __JUCE_LISTBOX_JUCEHEADER__
  26799. class ListViewport;
  26800. /**
  26801. A subclass of this is used to drive a ListBox.
  26802. @see ListBox
  26803. */
  26804. class JUCE_API ListBoxModel
  26805. {
  26806. public:
  26807. /** Destructor. */
  26808. virtual ~ListBoxModel() {}
  26809. /** This has to return the number of items in the list.
  26810. @see ListBox::getNumRows()
  26811. */
  26812. virtual int getNumRows() = 0;
  26813. /** This method must be implemented to draw a row of the list.
  26814. */
  26815. virtual void paintListBoxItem (int rowNumber,
  26816. Graphics& g,
  26817. int width, int height,
  26818. bool rowIsSelected) = 0;
  26819. /** This is used to create or update a custom component to go in a row of the list.
  26820. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26821. and handle mouse clicks with listBoxItemClicked().
  26822. This method will be called whenever a custom component might need to be updated - e.g.
  26823. when the table is changed, or TableListBox::updateContent() is called.
  26824. If you don't need a custom component for the specified row, then return 0.
  26825. If you do want a custom component, and the existingComponentToUpdate is null, then
  26826. this method must create a suitable new component and return it.
  26827. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26828. by this method. In this case, the method must either update it to make sure it's correctly representing
  26829. the given row (which may be different from the one that the component was created for), or it can
  26830. delete this component and return a new one.
  26831. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26832. */
  26833. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26834. Component* existingComponentToUpdate);
  26835. /** This can be overridden to react to the user clicking on a row.
  26836. @see listBoxItemDoubleClicked
  26837. */
  26838. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26839. /** This can be overridden to react to the user double-clicking on a row.
  26840. @see listBoxItemClicked
  26841. */
  26842. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26843. /** This can be overridden to react to the user double-clicking on a part of the list where
  26844. there are no rows.
  26845. @see listBoxItemClicked
  26846. */
  26847. virtual void backgroundClicked();
  26848. /** Override this to be informed when rows are selected or deselected.
  26849. This will be called whenever a row is selected or deselected. If a range of
  26850. rows is selected all at once, this will just be called once for that event.
  26851. @param lastRowSelected the last row that the user selected. If no
  26852. rows are currently selected, this may be -1.
  26853. */
  26854. virtual void selectedRowsChanged (int lastRowSelected);
  26855. /** Override this to be informed when the delete key is pressed.
  26856. If no rows are selected when they press the key, this won't be called.
  26857. @param lastRowSelected the last row that had been selected when they pressed the
  26858. key - if there are multiple selections, this might not be
  26859. very useful
  26860. */
  26861. virtual void deleteKeyPressed (int lastRowSelected);
  26862. /** Override this to be informed when the return key is pressed.
  26863. If no rows are selected when they press the key, this won't be called.
  26864. @param lastRowSelected the last row that had been selected when they pressed the
  26865. key - if there are multiple selections, this might not be
  26866. very useful
  26867. */
  26868. virtual void returnKeyPressed (int lastRowSelected);
  26869. /** Override this to be informed when the list is scrolled.
  26870. This might be caused by the user moving the scrollbar, or by programmatic changes
  26871. to the list position.
  26872. */
  26873. virtual void listWasScrolled();
  26874. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26875. If this returns a non-empty name then when the user drags a row, the listbox will
  26876. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26877. a drag-and-drop operation, using this string as the source description, with the listbox
  26878. itself as the source component.
  26879. @see DragAndDropContainer::startDragging
  26880. */
  26881. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26882. };
  26883. /**
  26884. A list of items that can be scrolled vertically.
  26885. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26886. either paint each row of the list and respond to events via callbacks, or for
  26887. more specialised tasks, it can supply a custom component to fill each row.
  26888. @see ComboBox, TableListBox
  26889. */
  26890. class JUCE_API ListBox : public Component,
  26891. public SettableTooltipClient
  26892. {
  26893. public:
  26894. /** Creates a ListBox.
  26895. The model pointer passed-in can be null, in which case you can set it later
  26896. with setModel().
  26897. */
  26898. ListBox (const String& componentName,
  26899. ListBoxModel* const model);
  26900. /** Destructor. */
  26901. ~ListBox();
  26902. /** Changes the current data model to display. */
  26903. void setModel (ListBoxModel* const newModel);
  26904. /** Returns the current list model. */
  26905. ListBoxModel* getModel() const throw() { return model; }
  26906. /** Causes the list to refresh its content.
  26907. Call this when the number of rows in the list changes, or if you want it
  26908. to call refreshComponentForRow() on all the row components.
  26909. Be careful not to call it from a different thread, though, as it's not
  26910. thread-safe.
  26911. */
  26912. void updateContent();
  26913. /** Turns on multiple-selection of rows.
  26914. By default this is disabled.
  26915. When your row component gets clicked you'll need to call the
  26916. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26917. clicked and to get it to do the appropriate selection based on whether
  26918. the ctrl/shift keys are held down.
  26919. */
  26920. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26921. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26922. This function is here primarily for the ComboBox class to use, but might be
  26923. useful for some other purpose too.
  26924. */
  26925. void setMouseMoveSelectsRows (bool shouldSelect);
  26926. /** Selects a row.
  26927. If the row is already selected, this won't do anything.
  26928. @param rowNumber the row to select
  26929. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26930. the selected row is off-screen, it'll scroll to make
  26931. sure that row is on-screen
  26932. @param deselectOthersFirst if true and there are multiple selections, these will
  26933. first be deselected before this item is selected
  26934. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26935. deselectAllRows, selectRangeOfRows
  26936. */
  26937. void selectRow (const int rowNumber,
  26938. bool dontScrollToShowThisRow = false,
  26939. bool deselectOthersFirst = true);
  26940. /** Selects a set of rows.
  26941. This will add these rows to the current selection, so you might need to
  26942. clear the current selection first with deselectAllRows()
  26943. @param firstRow the first row to select (inclusive)
  26944. @param lastRow the last row to select (inclusive)
  26945. */
  26946. void selectRangeOfRows (int firstRow,
  26947. int lastRow);
  26948. /** Deselects a row.
  26949. If it's not currently selected, this will do nothing.
  26950. @see selectRow, deselectAllRows
  26951. */
  26952. void deselectRow (const int rowNumber);
  26953. /** Deselects any currently selected rows.
  26954. @see deselectRow
  26955. */
  26956. void deselectAllRows();
  26957. /** Selects or deselects a row.
  26958. If the row's currently selected, this deselects it, and vice-versa.
  26959. */
  26960. void flipRowSelection (const int rowNumber);
  26961. /** Returns a sparse set indicating the rows that are currently selected.
  26962. @see setSelectedRows
  26963. */
  26964. const SparseSet<int> getSelectedRows() const;
  26965. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26966. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26967. method will be called. If it's false, no notification will be sent to the model.
  26968. @see getSelectedRows
  26969. */
  26970. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26971. const bool sendNotificationEventToModel = true);
  26972. /** Checks whether a row is selected.
  26973. */
  26974. bool isRowSelected (const int rowNumber) const;
  26975. /** Returns the number of rows that are currently selected.
  26976. @see getSelectedRow, isRowSelected, getLastRowSelected
  26977. */
  26978. int getNumSelectedRows() const;
  26979. /** Returns the row number of a selected row.
  26980. This will return the row number of the Nth selected row. The row numbers returned will
  26981. be sorted in order from low to high.
  26982. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26983. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26984. selected
  26985. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26986. */
  26987. int getSelectedRow (const int index = 0) const;
  26988. /** Returns the last row that the user selected.
  26989. This isn't the same as the highest row number that is currently selected - if the user
  26990. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26991. If nothing is selected, it will return -1.
  26992. */
  26993. int getLastRowSelected() const;
  26994. /** Multiply-selects rows based on the modifier keys.
  26995. If no modifier keys are down, this will select the given row and
  26996. deselect any others.
  26997. If the ctrl (or command on the Mac) key is down, it'll flip the
  26998. state of the selected row.
  26999. If the shift key is down, it'll select up to the given row from the
  27000. last row selected.
  27001. @see selectRow
  27002. */
  27003. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  27004. const ModifierKeys& modifiers);
  27005. /** Scrolls the list to a particular position.
  27006. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  27007. 1.0 scrolls to the bottom.
  27008. If the total number of rows all fit onto the screen at once, then this
  27009. method won't do anything.
  27010. @see getVerticalPosition
  27011. */
  27012. void setVerticalPosition (const double newProportion);
  27013. /** Returns the current vertical position as a proportion of the total.
  27014. This can be used in conjunction with setVerticalPosition() to save and restore
  27015. the list's position. It returns a value in the range 0 to 1.
  27016. @see setVerticalPosition
  27017. */
  27018. double getVerticalPosition() const;
  27019. /** Scrolls if necessary to make sure that a particular row is visible.
  27020. */
  27021. void scrollToEnsureRowIsOnscreen (const int row);
  27022. /** Returns a pointer to the scrollbar.
  27023. (Unlikely to be useful for most people).
  27024. */
  27025. ScrollBar* getVerticalScrollBar() const throw();
  27026. /** Returns a pointer to the scrollbar.
  27027. (Unlikely to be useful for most people).
  27028. */
  27029. ScrollBar* getHorizontalScrollBar() const throw();
  27030. /** Finds the row index that contains a given x,y position.
  27031. The position is relative to the ListBox's top-left.
  27032. If no row exists at this position, the method will return -1.
  27033. @see getComponentForRowNumber
  27034. */
  27035. int getRowContainingPosition (const int x, const int y) const throw();
  27036. /** Finds a row index that would be the most suitable place to insert a new
  27037. item for a given position.
  27038. This is useful when the user is e.g. dragging and dropping onto the listbox,
  27039. because it lets you easily choose the best position to insert the item that
  27040. they drop, based on where they drop it.
  27041. If the position is out of range, this will return -1. If the position is
  27042. beyond the end of the list, it will return getNumRows() to indicate the end
  27043. of the list.
  27044. @see getComponentForRowNumber
  27045. */
  27046. int getInsertionIndexForPosition (const int x, const int y) const throw();
  27047. /** Returns the position of one of the rows, relative to the top-left of
  27048. the listbox.
  27049. This may be off-screen, and the range of the row number that is passed-in is
  27050. not checked to see if it's a valid row.
  27051. */
  27052. const Rectangle getRowPosition (const int rowNumber,
  27053. const bool relativeToComponentTopLeft) const throw();
  27054. /** Finds the row component for a given row in the list.
  27055. The component returned will have been created using createRowComponent().
  27056. If the component for this row is off-screen or if the row is out-of-range,
  27057. this will return 0.
  27058. @see getRowContainingPosition
  27059. */
  27060. Component* getComponentForRowNumber (const int rowNumber) const throw();
  27061. /** Returns the row number that the given component represents.
  27062. If the component isn't one of the list's rows, this will return -1.
  27063. */
  27064. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  27065. /** Returns the width of a row (which may be less than the width of this component
  27066. if there's a scrollbar).
  27067. */
  27068. int getVisibleRowWidth() const throw();
  27069. /** Sets the height of each row in the list.
  27070. The default height is 22 pixels.
  27071. @see getRowHeight
  27072. */
  27073. void setRowHeight (const int newHeight);
  27074. /** Returns the height of a row in the list.
  27075. @see setRowHeight
  27076. */
  27077. int getRowHeight() const throw() { return rowHeight; }
  27078. /** Returns the number of rows actually visible.
  27079. This is the number of whole rows which will fit on-screen, so the value might
  27080. be more than the actual number of rows in the list.
  27081. */
  27082. int getNumRowsOnScreen() const throw();
  27083. /** A set of colour IDs to use to change the colour of various aspects of the label.
  27084. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27085. methods.
  27086. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27087. */
  27088. enum ColourIds
  27089. {
  27090. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  27091. Make this transparent if you don't want the background to be filled. */
  27092. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  27093. Make this transparent to not have an outline. */
  27094. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  27095. };
  27096. /** Sets the thickness of a border that will be drawn around the box.
  27097. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  27098. @see outlineColourId
  27099. */
  27100. void setOutlineThickness (const int outlineThickness);
  27101. /** Returns the thickness of outline that will be drawn around the listbox.
  27102. @see setOutlineColour
  27103. */
  27104. int getOutlineThickness() const throw() { return outlineThickness; }
  27105. /** Sets a component that the list should use as a header.
  27106. This will position the given component at the top of the list, maintaining the
  27107. height of the component passed-in, but rescaling it horizontally to match the
  27108. width of the items in the listbox.
  27109. The component will be deleted when setHeaderComponent() is called with a
  27110. different component, or when the listbox is deleted.
  27111. */
  27112. void setHeaderComponent (Component* const newHeaderComponent);
  27113. /** Changes the width of the rows in the list.
  27114. This can be used to make the list's row components wider than the list itself - the
  27115. width of the rows will be either the width of the list or this value, whichever is
  27116. greater, and if the rows become wider than the list, a horizontal scrollbar will
  27117. appear.
  27118. The default value for this is 0, which means that the rows will always
  27119. be the same width as the list.
  27120. */
  27121. void setMinimumContentWidth (const int newMinimumWidth);
  27122. /** Returns the space currently available for the row items, taking into account
  27123. borders, scrollbars, etc.
  27124. */
  27125. int getVisibleContentWidth() const throw();
  27126. /** Repaints one of the rows.
  27127. This is a lightweight alternative to calling updateContent, and just causes a
  27128. repaint of the row's area.
  27129. */
  27130. void repaintRow (const int rowNumber) throw();
  27131. /** This fairly obscure method creates an image that just shows the currently
  27132. selected row components.
  27133. It's a handy method for doing drag-and-drop, as it can be passed to the
  27134. DragAndDropContainer for use as the drag image.
  27135. Note that it will make the row components temporarily invisible, so if you're
  27136. using custom components this could affect them if they're sensitive to that
  27137. sort of thing.
  27138. @see Component::createComponentSnapshot
  27139. */
  27140. Image* createSnapshotOfSelectedRows();
  27141. /** Returns the viewport that this ListBox uses.
  27142. You may need to use this to change parameters such as whether scrollbars
  27143. are shown, etc.
  27144. */
  27145. Viewport* getViewport() const throw();
  27146. /** @internal */
  27147. bool keyPressed (const KeyPress& key);
  27148. /** @internal */
  27149. bool keyStateChanged (const bool isKeyDown);
  27150. /** @internal */
  27151. void paint (Graphics& g);
  27152. /** @internal */
  27153. void paintOverChildren (Graphics& g);
  27154. /** @internal */
  27155. void resized();
  27156. /** @internal */
  27157. void visibilityChanged();
  27158. /** @internal */
  27159. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  27160. /** @internal */
  27161. void mouseMove (const MouseEvent&);
  27162. /** @internal */
  27163. void mouseExit (const MouseEvent&);
  27164. /** @internal */
  27165. void mouseUp (const MouseEvent&);
  27166. /** @internal */
  27167. void colourChanged();
  27168. juce_UseDebuggingNewOperator
  27169. private:
  27170. friend class ListViewport;
  27171. friend class TableListBox;
  27172. ListBoxModel* model;
  27173. ListViewport* viewport;
  27174. Component* headerComponent;
  27175. int totalItems, rowHeight, minimumRowWidth;
  27176. int outlineThickness;
  27177. int lastMouseX, lastMouseY, lastRowSelected;
  27178. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  27179. SparseSet <int> selected;
  27180. void selectRowInternal (const int rowNumber,
  27181. bool dontScrollToShowThisRow,
  27182. bool deselectOthersFirst,
  27183. bool isMouseClick);
  27184. ListBox (const ListBox&);
  27185. const ListBox& operator= (const ListBox&);
  27186. };
  27187. #endif // __JUCE_LISTBOX_JUCEHEADER__
  27188. /********* End of inlined file: juce_ListBox.h *********/
  27189. /********* Start of inlined file: juce_TextButton.h *********/
  27190. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  27191. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  27192. /**
  27193. A button that uses the standard lozenge-shaped background with a line of
  27194. text on it.
  27195. @see Button, DrawableButton
  27196. */
  27197. class JUCE_API TextButton : public Button
  27198. {
  27199. public:
  27200. /** Creates a TextButton.
  27201. @param buttonName the text to put in the button (the component's name is also
  27202. initially set to this string, but these can be changed later
  27203. using the setName() and setButtonText() methods)
  27204. @param toolTip an optional string to use as a toolip
  27205. @see Button
  27206. */
  27207. TextButton (const String& buttonName,
  27208. const String& toolTip = String::empty);
  27209. /** Destructor. */
  27210. ~TextButton();
  27211. /** A set of colour IDs to use to change the colour of various aspects of the button.
  27212. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27213. methods.
  27214. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27215. */
  27216. enum ColourIds
  27217. {
  27218. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  27219. 'off'). The look-and-feel class might re-interpret this to add
  27220. effects, etc. */
  27221. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  27222. 'on'). The look-and-feel class might re-interpret this to add
  27223. effects, etc. */
  27224. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  27225. };
  27226. /** Resizes the button to fit neatly around its current text.
  27227. If newHeight is >= 0, the button's height will be changed to this
  27228. value. If it's less than zero, its height will be unaffected.
  27229. */
  27230. void changeWidthToFitText (const int newHeight = -1);
  27231. /** This can be overridden to use different fonts than the default one.
  27232. Note that you'll need to set the font's size appropriately, too.
  27233. */
  27234. virtual const Font getFont();
  27235. juce_UseDebuggingNewOperator
  27236. protected:
  27237. /** @internal */
  27238. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  27239. /** @internal */
  27240. void colourChanged();
  27241. private:
  27242. TextButton (const TextButton&);
  27243. const TextButton& operator= (const TextButton&);
  27244. };
  27245. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  27246. /********* End of inlined file: juce_TextButton.h *********/
  27247. /**
  27248. A component displaying a list of plugins, with options to scan for them,
  27249. add, remove and sort them.
  27250. */
  27251. class JUCE_API PluginListComponent : public Component,
  27252. public ListBoxModel,
  27253. public ChangeListener,
  27254. public ButtonListener,
  27255. public Timer
  27256. {
  27257. public:
  27258. /**
  27259. Creates the list component.
  27260. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  27261. The properties file, if supplied, is used to store the user's last search paths.
  27262. */
  27263. PluginListComponent (KnownPluginList& listToRepresent,
  27264. const File& deadMansPedalFile,
  27265. PropertiesFile* const propertiesToUse);
  27266. /** Destructor. */
  27267. ~PluginListComponent();
  27268. /** @internal */
  27269. void resized();
  27270. /** @internal */
  27271. bool isInterestedInFileDrag (const StringArray& files);
  27272. /** @internal */
  27273. void filesDropped (const StringArray& files, int, int);
  27274. /** @internal */
  27275. int getNumRows();
  27276. /** @internal */
  27277. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  27278. /** @internal */
  27279. void deleteKeyPressed (int lastRowSelected);
  27280. /** @internal */
  27281. void buttonClicked (Button* b);
  27282. /** @internal */
  27283. void changeListenerCallback (void*);
  27284. /** @internal */
  27285. void timerCallback();
  27286. juce_UseDebuggingNewOperator
  27287. private:
  27288. KnownPluginList& list;
  27289. File deadMansPedalFile;
  27290. ListBox* listBox;
  27291. TextButton* optionsButton;
  27292. PropertiesFile* propertiesToUse;
  27293. int typeToScan;
  27294. void scanFor (AudioPluginFormat* format);
  27295. PluginListComponent (const PluginListComponent&);
  27296. const PluginListComponent& operator= (const PluginListComponent&);
  27297. };
  27298. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27299. /********* End of inlined file: juce_PluginListComponent.h *********/
  27300. #endif
  27301. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27302. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  27303. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27304. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27305. /********* Start of inlined file: juce_AudioFormat.h *********/
  27306. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27307. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  27308. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  27309. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27310. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27311. /**
  27312. Writes samples to an audio file stream.
  27313. A subclass that writes a specific type of audio format will be created by
  27314. an AudioFormat object.
  27315. After creating one of these with the AudioFormat::createWriterFor() method
  27316. you can call its write() method to store the samples, and then delete it.
  27317. @see AudioFormat, AudioFormatReader
  27318. */
  27319. class JUCE_API AudioFormatWriter
  27320. {
  27321. protected:
  27322. /** Creates an AudioFormatWriter object.
  27323. @param destStream the stream to write to - this will be deleted
  27324. by this object when it is no longer needed
  27325. @param formatName the description that will be returned by the getFormatName()
  27326. method
  27327. @param sampleRate the sample rate to use - the base class just stores
  27328. this value, it doesn't do anything with it
  27329. @param numberOfChannels the number of channels to write - the base class just stores
  27330. this value, it doesn't do anything with it
  27331. @param bitsPerSample the bit depth of the stream - the base class just stores
  27332. this value, it doesn't do anything with it
  27333. */
  27334. AudioFormatWriter (OutputStream* const destStream,
  27335. const String& formatName,
  27336. const double sampleRate,
  27337. const unsigned int numberOfChannels,
  27338. const unsigned int bitsPerSample);
  27339. public:
  27340. /** Destructor. */
  27341. virtual ~AudioFormatWriter();
  27342. /** Returns a description of what type of format this is.
  27343. E.g. "AIFF file"
  27344. */
  27345. const String getFormatName() const throw() { return formatName; }
  27346. /** Writes a set of samples to the audio stream.
  27347. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27348. can use AudioSampleBuffer::writeToAudioWriter().
  27349. @param samplesToWrite an array of arrays containing the sample data for
  27350. each channel to write. This is a zero-terminated
  27351. array of arrays, and can contain a different number
  27352. of channels than the actual stream uses, and the
  27353. writer should do its best to cope with this.
  27354. If the format is fixed-point, each channel will be formatted
  27355. as an array of signed integers using the full 32-bit
  27356. range -0x80000000 to 0x7fffffff, regardless of the source's
  27357. bit-depth. If it is a floating-point format, you should treat
  27358. the arrays as arrays of floats, and just cast it to an (int**)
  27359. to pass it into the method.
  27360. @param numSamples the number of samples to write
  27361. */
  27362. virtual bool write (const int** samplesToWrite,
  27363. int numSamples) = 0;
  27364. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27365. the output.
  27366. This will take care of any floating-point conversion that's required to convert
  27367. between the two formats. It won't deal with sample-rate conversion, though.
  27368. If numSamplesToRead < 0, it will write the entire length of the reader.
  27369. @returns false if it can't read or write properly during the operation
  27370. */
  27371. bool writeFromAudioReader (AudioFormatReader& reader,
  27372. int64 startSample,
  27373. int64 numSamplesToRead);
  27374. /** Reads some samples from an AudioSource, and writes these to the output.
  27375. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27376. @param source the source to read from
  27377. @param numSamplesToRead total number of samples to read and write
  27378. @param samplesPerBlock the maximum number of samples to fetch from the source
  27379. @returns false if it can't read or write properly during the operation
  27380. */
  27381. bool writeFromAudioSource (AudioSource& source,
  27382. int numSamplesToRead,
  27383. const int samplesPerBlock = 2048);
  27384. /** Returns the sample rate being used. */
  27385. double getSampleRate() const throw() { return sampleRate; }
  27386. /** Returns the number of channels being written. */
  27387. int getNumChannels() const throw() { return numChannels; }
  27388. /** Returns the bit-depth of the data being written. */
  27389. int getBitsPerSample() const throw() { return bitsPerSample; }
  27390. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27391. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  27392. juce_UseDebuggingNewOperator
  27393. protected:
  27394. /** The sample rate of the stream. */
  27395. double sampleRate;
  27396. /** The number of channels being written to the stream. */
  27397. unsigned int numChannels;
  27398. /** The bit depth of the file. */
  27399. unsigned int bitsPerSample;
  27400. /** True if it's a floating-point format, false if it's fixed-point. */
  27401. bool usesFloatingPointData;
  27402. /** The output stream for Use by subclasses. */
  27403. OutputStream* output;
  27404. private:
  27405. String formatName;
  27406. };
  27407. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27408. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  27409. /**
  27410. Subclasses of AudioFormat are used to read and write different audio
  27411. file formats.
  27412. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27413. */
  27414. class JUCE_API AudioFormat
  27415. {
  27416. public:
  27417. /** Destructor. */
  27418. virtual ~AudioFormat();
  27419. /** Returns the name of this format.
  27420. e.g. "WAV file" or "AIFF file"
  27421. */
  27422. const String& getFormatName() const;
  27423. /** Returns all the file extensions that might apply to a file of this format.
  27424. The first item will be the one that's preferred when creating a new file.
  27425. So for a wav file this might just return ".wav"; for an AIFF file it might
  27426. return two items, ".aif" and ".aiff"
  27427. */
  27428. const StringArray& getFileExtensions() const;
  27429. /** Returns true if this the given file can be read by this format.
  27430. Subclasses shouldn't do too much work here, just check the extension or
  27431. file type. The base class implementation just checks the file's extension
  27432. against one of the ones that was registered in the constructor.
  27433. */
  27434. virtual bool canHandleFile (const File& fileToTest);
  27435. /** Returns a set of sample rates that the format can read and write. */
  27436. virtual const Array <int> getPossibleSampleRates() = 0;
  27437. /** Returns a set of bit depths that the format can read and write. */
  27438. virtual const Array <int> getPossibleBitDepths() = 0;
  27439. /** Returns true if the format can do 2-channel audio. */
  27440. virtual bool canDoStereo() = 0;
  27441. /** Returns true if the format can do 1-channel audio. */
  27442. virtual bool canDoMono() = 0;
  27443. /** Returns true if the format uses compressed data. */
  27444. virtual bool isCompressed();
  27445. /** Returns a list of different qualities that can be used when writing.
  27446. Non-compressed formats will just return an empty array, but for something
  27447. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27448. When calling createWriterFor(), an index from this array is passed in to
  27449. tell the format which option is required.
  27450. */
  27451. virtual const StringArray getQualityOptions();
  27452. /** Tries to create an object that can read from a stream containing audio
  27453. data in this format.
  27454. The reader object that is returned can be used to read from the stream, and
  27455. should then be deleted by the caller.
  27456. @param sourceStream the stream to read from - the AudioFormatReader object
  27457. that is returned will delete this stream when it no longer
  27458. needs it.
  27459. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27460. should delete the stream object that was passed-in. (If a valid
  27461. reader is returned, it will always be in charge of deleting the
  27462. stream, so this parameter is ignored)
  27463. @see AudioFormatReader
  27464. */
  27465. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27466. const bool deleteStreamIfOpeningFails) = 0;
  27467. /** Tries to create an object that can write to a stream with this audio format.
  27468. The writer object that is returned can be used to write to the stream, and
  27469. should then be deleted by the caller.
  27470. If the stream can't be created for some reason (e.g. the parameters passed in
  27471. here aren't suitable), this will return 0.
  27472. @param streamToWriteTo the stream that the data will go to - this will be
  27473. deleted by the AudioFormatWriter object when it's no longer
  27474. needed. If no AudioFormatWriter can be created by this method,
  27475. the stream will NOT be deleted, so that the caller can re-use it
  27476. to try to open a different format, etc
  27477. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27478. returned by getPossibleSampleRates()
  27479. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27480. the choice will depend on the results of canDoMono() and
  27481. canDoStereo()
  27482. @param bitsPerSample the bits per sample to use - this must be one of the values
  27483. returned by getPossibleBitDepths()
  27484. @param metadataValues a set of metadata values that the writer should try to write
  27485. to the stream. Exactly what these are depends on the format,
  27486. and the subclass doesn't actually have to do anything with
  27487. them if it doesn't want to. Have a look at the specific format
  27488. implementation classes to see possible values that can be
  27489. used
  27490. @param qualityOptionIndex the index of one of compression qualities returned by the
  27491. getQualityOptions() method. If there aren't any quality options
  27492. for this format, just pass 0 in this parameter, as it'll be
  27493. ignored
  27494. @see AudioFormatWriter
  27495. */
  27496. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27497. double sampleRateToUse,
  27498. unsigned int numberOfChannels,
  27499. int bitsPerSample,
  27500. const StringPairArray& metadataValues,
  27501. int qualityOptionIndex) = 0;
  27502. protected:
  27503. /** Creates an AudioFormat object.
  27504. @param formatName this sets the value that will be returned by getFormatName()
  27505. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27506. be returned by getFileExtension()
  27507. */
  27508. AudioFormat (const String& formatName,
  27509. const tchar** const fileExtensions);
  27510. private:
  27511. String formatName;
  27512. StringArray fileExtensions;
  27513. };
  27514. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27515. /********* End of inlined file: juce_AudioFormat.h *********/
  27516. /**
  27517. Reads and Writes AIFF format audio files.
  27518. @see AudioFormat
  27519. */
  27520. class JUCE_API AiffAudioFormat : public AudioFormat
  27521. {
  27522. public:
  27523. /** Creates an format object. */
  27524. AiffAudioFormat();
  27525. /** Destructor. */
  27526. ~AiffAudioFormat();
  27527. const Array <int> getPossibleSampleRates();
  27528. const Array <int> getPossibleBitDepths();
  27529. bool canDoStereo();
  27530. bool canDoMono();
  27531. #if JUCE_MAC
  27532. bool canHandleFile (const File& fileToTest);
  27533. #endif
  27534. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27535. const bool deleteStreamIfOpeningFails);
  27536. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27537. double sampleRateToUse,
  27538. unsigned int numberOfChannels,
  27539. int bitsPerSample,
  27540. const StringPairArray& metadataValues,
  27541. int qualityOptionIndex);
  27542. juce_UseDebuggingNewOperator
  27543. };
  27544. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27545. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  27546. #endif
  27547. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27548. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  27549. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27550. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27551. /**
  27552. */
  27553. class AudioCDBurner
  27554. {
  27555. public:
  27556. /** Returns a list of available optical drives.
  27557. Use openDevice() to open one of the items from this list.
  27558. */
  27559. static const StringArray findAvailableDevices();
  27560. /** Tries to open one of the optical drives.
  27561. The deviceIndex is an index into the array returned by findAvailableDevices().
  27562. */
  27563. static AudioCDBurner* openDevice (const int deviceIndex);
  27564. /** Destructor. */
  27565. ~AudioCDBurner();
  27566. /** Returns true if there's a writable disk in the drive.
  27567. */
  27568. bool isDiskPresent() const;
  27569. /** Returns the number of free blocks on the disk.
  27570. There are 75 blocks per second, at 44100Hz.
  27571. */
  27572. int getNumAvailableAudioBlocks() const;
  27573. /** Adds a track to be written.
  27574. The source passed-in here will be kept by this object, and it will
  27575. be used and deleted at some point in the future, either during the
  27576. burn() method or when this AudioCDBurner object is deleted. Your caller
  27577. method shouldn't keep a reference to it or use it again after passing
  27578. it in here.
  27579. */
  27580. bool addAudioTrack (AudioSource* source, int numSamples);
  27581. /**
  27582. Return true to cancel the current burn operation
  27583. */
  27584. class BurnProgressListener
  27585. {
  27586. public:
  27587. BurnProgressListener() throw() {}
  27588. virtual ~BurnProgressListener() {}
  27589. /** Called at intervals to report on the progress of the AudioCDBurner.
  27590. To cancel the burn, return true from this.
  27591. */
  27592. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  27593. };
  27594. const String burn (BurnProgressListener* listener,
  27595. const bool ejectDiscAfterwards,
  27596. const bool peformFakeBurnForTesting);
  27597. juce_UseDebuggingNewOperator
  27598. private:
  27599. AudioCDBurner (const int deviceIndex);
  27600. void* internal;
  27601. };
  27602. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27603. /********* End of inlined file: juce_AudioCDBurner.h *********/
  27604. #endif
  27605. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27606. /********* Start of inlined file: juce_AudioCDReader.h *********/
  27607. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27608. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  27609. #if JUCE_MAC
  27610. #endif
  27611. /**
  27612. A type of AudioFormatReader that reads from an audio CD.
  27613. One of these can be used to read a CD as if it's one big audio stream. Use the
  27614. getPositionOfTrackStart() method to find where the individual tracks are
  27615. within the stream.
  27616. @see AudioFormatReader
  27617. */
  27618. class JUCE_API AudioCDReader : public AudioFormatReader
  27619. {
  27620. public:
  27621. /** Returns a list of names of Audio CDs currently available for reading.
  27622. If there's a CD drive but no CD in it, this might return an empty list, or
  27623. possibly a device that can be opened but which has no tracks, depending
  27624. on the platform.
  27625. @see createReaderForCD
  27626. */
  27627. static const StringArray getAvailableCDNames();
  27628. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  27629. @param index the index of one of the available CDs - use getAvailableCDNames()
  27630. to find out how many there are.
  27631. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  27632. caller will be responsible for deleting the object returned.
  27633. */
  27634. static AudioCDReader* createReaderForCD (const int index);
  27635. /** Destructor. */
  27636. ~AudioCDReader();
  27637. /** Implementation of the AudioFormatReader method. */
  27638. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27639. int64 startSampleInFile, int numSamples);
  27640. /** Checks whether the CD has been removed from the drive.
  27641. */
  27642. bool isCDStillPresent() const;
  27643. /** Returns the total number of tracks (audio + data).
  27644. */
  27645. int getNumTracks() const;
  27646. /** Finds the sample offset of the start of a track.
  27647. @param trackNum the track number, where 0 is the first track.
  27648. */
  27649. int getPositionOfTrackStart (int trackNum) const;
  27650. /** Returns true if a given track is an audio track.
  27651. @param trackNum the track number, where 0 is the first track.
  27652. */
  27653. bool isTrackAudio (int trackNum) const;
  27654. /** Refreshes the object's table of contents.
  27655. If the disc has been ejected and a different one put in since this
  27656. object was created, this will cause it to update its idea of how many tracks
  27657. there are, etc.
  27658. */
  27659. void refreshTrackLengths();
  27660. /** Enables scanning for indexes within tracks.
  27661. @see getLastIndex
  27662. */
  27663. void enableIndexScanning (bool enabled);
  27664. /** Returns the index number found during the last read() call.
  27665. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27666. Then when the read() method is called, if it comes across an index within that
  27667. block, the index number is stored and returned by this method.
  27668. Some devices might not support indexes, of course.
  27669. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27670. @see enableIndexScanning
  27671. */
  27672. int getLastIndex() const;
  27673. /** Scans a track to find the position of any indexes within it.
  27674. @param trackNumber the track to look in, where 0 is the first track on the disc
  27675. @returns an array of sample positions of any index points found (not including
  27676. the index that marks the start of the track)
  27677. */
  27678. const Array <int> findIndexesInTrack (const int trackNumber);
  27679. /** Returns the CDDB id number for the CD.
  27680. It's not a great way of identifying a disc, but it's traditional.
  27681. */
  27682. int getCDDBId();
  27683. /** Tries to eject the disk.
  27684. Of course this might not be possible, if some other process is using it.
  27685. */
  27686. void ejectDisk();
  27687. juce_UseDebuggingNewOperator
  27688. private:
  27689. #if JUCE_MAC
  27690. File volumeDir;
  27691. OwnedArray<File> tracks;
  27692. Array <int> trackStartSamples;
  27693. int currentReaderTrack;
  27694. AudioFormatReader* reader;
  27695. AudioCDReader (const File& volume);
  27696. public:
  27697. static int compareElements (const File* const, const File* const) throw();
  27698. private:
  27699. #elif JUCE_WIN32
  27700. int numTracks;
  27701. int trackStarts[100];
  27702. bool audioTracks [100];
  27703. void* handle;
  27704. bool indexingEnabled;
  27705. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27706. MemoryBlock buffer;
  27707. AudioCDReader (void* handle);
  27708. int getIndexAt (int samplePos);
  27709. #elif JUCE_LINUX
  27710. AudioCDReader();
  27711. #endif
  27712. AudioCDReader (const AudioCDReader&);
  27713. const AudioCDReader& operator= (const AudioCDReader&);
  27714. };
  27715. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27716. /********* End of inlined file: juce_AudioCDReader.h *********/
  27717. #endif
  27718. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27719. #endif
  27720. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27721. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  27722. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27723. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27724. /**
  27725. A class for keeping a list of available audio formats, and for deciding which
  27726. one to use to open a given file.
  27727. You can either use this class as a singleton object, or create instances of it
  27728. yourself. Once created, use its registerFormat() method to tell it which
  27729. formats it should use.
  27730. @see AudioFormat
  27731. */
  27732. class JUCE_API AudioFormatManager
  27733. {
  27734. public:
  27735. /** Creates an empty format manager.
  27736. Before it'll be any use, you'll need to call registerFormat() with all the
  27737. formats you want it to be able to recognise.
  27738. */
  27739. AudioFormatManager();
  27740. /** Destructor. */
  27741. ~AudioFormatManager();
  27742. juce_DeclareSingleton (AudioFormatManager, false);
  27743. /** Adds a format to the manager's list of available file types.
  27744. The object passed-in will be deleted by this object, so don't keep a pointer
  27745. to it!
  27746. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27747. return this one when called.
  27748. */
  27749. void registerFormat (AudioFormat* newFormat,
  27750. const bool makeThisTheDefaultFormat);
  27751. /** Handy method to make it easy to register the formats that come with Juce.
  27752. Currently, this will add WAV and AIFF to the list.
  27753. */
  27754. void registerBasicFormats();
  27755. /** Clears the list of known formats. */
  27756. void clearFormats();
  27757. /** Returns the number of currently registered file formats. */
  27758. int getNumKnownFormats() const;
  27759. /** Returns one of the registered file formats. */
  27760. AudioFormat* getKnownFormat (const int index) const;
  27761. /** Looks for which of the known formats is listed as being for a given file
  27762. extension.
  27763. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27764. */
  27765. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27766. /** Returns the format which has been set as the default one.
  27767. You can set a format as being the default when it is registered. It's useful
  27768. when you want to write to a file, because the best format may change between
  27769. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27770. If none has been set as the default, this method will just return the first
  27771. one in the list.
  27772. */
  27773. AudioFormat* getDefaultFormat() const;
  27774. /** Returns a set of wildcards for file-matching that contains the extensions for
  27775. all known formats.
  27776. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27777. */
  27778. const String getWildcardForAllFormats() const;
  27779. /** Searches through the known formats to try to create a suitable reader for
  27780. this file.
  27781. If none of the registered formats can open the file, it'll return 0. If it
  27782. returns a reader, it's the caller's responsibility to delete the reader.
  27783. */
  27784. AudioFormatReader* createReaderFor (const File& audioFile);
  27785. /** Searches through the known formats to try to create a suitable reader for
  27786. this stream.
  27787. The stream object that is passed-in will be deleted by this method or by the
  27788. reader that is returned, so the caller should not keep any references to it.
  27789. The stream that is passed-in must be capable of being repositioned so
  27790. that all the formats can have a go at opening it.
  27791. If none of the registered formats can open the stream, it'll return 0. If it
  27792. returns a reader, it's the caller's responsibility to delete the reader.
  27793. */
  27794. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27795. juce_UseDebuggingNewOperator
  27796. private:
  27797. VoidArray knownFormats;
  27798. int defaultFormatIndex;
  27799. };
  27800. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27801. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27802. #endif
  27803. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27804. #endif
  27805. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27806. #endif
  27807. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27808. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27809. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27810. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27811. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27812. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27813. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27814. class AudioThumbnailCache;
  27815. /**
  27816. Makes it easy to quickly draw scaled views of the waveform shape of an
  27817. audio file.
  27818. To use this class, just create an AudioThumbNail class for the file you want
  27819. to draw, call setSource to tell it which file or resource to use, then call
  27820. drawChannel() to draw it.
  27821. The class will asynchronously scan the wavefile to create its scaled-down view,
  27822. so you should make your UI repaint itself as this data comes in. To do this, the
  27823. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27824. listeners should repaint themselves.
  27825. The thumbnail stores an internal low-res version of the wave data, and this can
  27826. be loaded and saved to avoid having to scan the file again.
  27827. @see AudioThumbnailCache
  27828. */
  27829. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27830. public TimeSliceClient,
  27831. private Timer
  27832. {
  27833. public:
  27834. /** Creates an audio thumbnail.
  27835. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27836. of the audio data, this is the scale at which it should be done. (This
  27837. number is the number of original samples that will be averaged for each
  27838. low-res sample)
  27839. @param formatManagerToUse the audio format manager that is used to open the file
  27840. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27841. thread and storage that is used to by the thumbnail, and the cache
  27842. object can be shared between multiple thumbnails
  27843. */
  27844. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27845. AudioFormatManager& formatManagerToUse,
  27846. AudioThumbnailCache& cacheToUse);
  27847. /** Destructor. */
  27848. ~AudioThumbnail();
  27849. /** Specifies the file or stream that contains the audio file.
  27850. For a file, just call
  27851. @code
  27852. setSource (new FileInputSource (file))
  27853. @endcode
  27854. You can pass a zero in here to clear the thumbnail.
  27855. The source that is passed in will be deleted by this object when it is no
  27856. longer needed
  27857. */
  27858. void setSource (InputSource* const newSource);
  27859. /** Reloads the low res thumbnail data from an input stream.
  27860. The thumb will automatically attempt to reload itself from its
  27861. AudioThumbnailCache.
  27862. */
  27863. void loadFrom (InputStream& input);
  27864. /** Saves the low res thumbnail data to an output stream.
  27865. The thumb will automatically attempt to save itself to its
  27866. AudioThumbnailCache after it finishes scanning the wave file.
  27867. */
  27868. void saveTo (OutputStream& output) const;
  27869. /** Returns the number of channels in the file.
  27870. */
  27871. int getNumChannels() const throw();
  27872. /** Returns the length of the audio file, in seconds.
  27873. */
  27874. double getTotalLength() const throw();
  27875. /** Renders the waveform shape for a channel.
  27876. The waveform will be drawn within the specified rectangle, where startTime
  27877. and endTime specify the times within the audio file that should be positioned
  27878. at the left and right edges of the rectangle.
  27879. The waveform will be scaled vertically so that a full-volume sample will fill
  27880. the rectangle vertically, but you can also specify an extra vertical scale factor
  27881. with the verticalZoomFactor parameter.
  27882. */
  27883. void drawChannel (Graphics& g,
  27884. int x, int y, int w, int h,
  27885. double startTimeSeconds,
  27886. double endTimeSeconds,
  27887. int channelNum,
  27888. const float verticalZoomFactor);
  27889. /** Returns true if the low res preview is fully generated.
  27890. */
  27891. bool isFullyLoaded() const throw();
  27892. /** @internal */
  27893. bool useTimeSlice();
  27894. /** @internal */
  27895. void timerCallback();
  27896. juce_UseDebuggingNewOperator
  27897. private:
  27898. AudioFormatManager& formatManagerToUse;
  27899. AudioThumbnailCache& cache;
  27900. InputSource* source;
  27901. CriticalSection readerLock;
  27902. AudioFormatReader* reader;
  27903. MemoryBlock data, cachedLevels;
  27904. int orginalSamplesPerThumbnailSample;
  27905. int numChannelsCached, numSamplesCached;
  27906. double cachedStart, cachedTimePerPixel;
  27907. bool cacheNeedsRefilling;
  27908. void clear();
  27909. AudioFormatReader* createReader() const;
  27910. void generateSection (AudioFormatReader& reader,
  27911. int64 startSample,
  27912. int numSamples);
  27913. char* getChannelData (int channel) const;
  27914. void refillCache (const int numSamples,
  27915. double startTime,
  27916. const double timePerPixel);
  27917. friend class AudioThumbnailCache;
  27918. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27919. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27920. // returns true if more needs to be read
  27921. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27922. };
  27923. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27924. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27925. struct ThumbnailCacheEntry;
  27926. /**
  27927. An instance of this class is used to manage multiple AudioThumbnail objects.
  27928. The cache runs a single background thread that is shared by all the thumbnails
  27929. that need it, and it maintains a set of low-res previews in memory, to avoid
  27930. having to re-scan audio files too often.
  27931. @see AudioThumbnail
  27932. */
  27933. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27934. {
  27935. public:
  27936. /** Creates a cache object.
  27937. The maxNumThumbsToStore parameter lets you specify how many previews should
  27938. be kept in memory at once.
  27939. */
  27940. AudioThumbnailCache (const int maxNumThumbsToStore);
  27941. /** Destructor. */
  27942. ~AudioThumbnailCache();
  27943. /** Clears out any stored thumbnails.
  27944. */
  27945. void clear();
  27946. /** Reloads the specified thumb if this cache contains the appropriate stored
  27947. data.
  27948. This is called automatically by the AudioThumbnail class, so you shouldn't
  27949. normally need to call it directly.
  27950. */
  27951. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27952. /** Stores the cachable data from the specified thumb in this cache.
  27953. This is called automatically by the AudioThumbnail class, so you shouldn't
  27954. normally need to call it directly.
  27955. */
  27956. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27957. juce_UseDebuggingNewOperator
  27958. private:
  27959. OwnedArray <ThumbnailCacheEntry> thumbs;
  27960. int maxNumThumbsToStore;
  27961. friend class AudioThumbnail;
  27962. void addThumbnail (AudioThumbnail* const thumb);
  27963. void removeThumbnail (AudioThumbnail* const thumb);
  27964. };
  27965. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27966. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  27967. #endif
  27968. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27969. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  27970. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27971. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  27972. #if JUCE_USE_FLAC || defined (DOXYGEN)
  27973. /**
  27974. Reads and writes the lossless-compression FLAC audio format.
  27975. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  27976. and make sure your include search path and library search path are set up to find
  27977. the FLAC header files and static libraries.
  27978. @see AudioFormat
  27979. */
  27980. class JUCE_API FlacAudioFormat : public AudioFormat
  27981. {
  27982. public:
  27983. FlacAudioFormat();
  27984. ~FlacAudioFormat();
  27985. const Array <int> getPossibleSampleRates();
  27986. const Array <int> getPossibleBitDepths();
  27987. bool canDoStereo();
  27988. bool canDoMono();
  27989. bool isCompressed();
  27990. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27991. const bool deleteStreamIfOpeningFails);
  27992. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27993. double sampleRateToUse,
  27994. unsigned int numberOfChannels,
  27995. int bitsPerSample,
  27996. const StringPairArray& metadataValues,
  27997. int qualityOptionIndex);
  27998. juce_UseDebuggingNewOperator
  27999. };
  28000. #endif
  28001. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28002. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  28003. #endif
  28004. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28005. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  28006. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28007. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28008. /**
  28009. This class is used to wrap an AudioFormatReader and only read from a
  28010. subsection of the file.
  28011. So if you have a reader which can read a 1000 sample file, you could wrap it
  28012. in one of these to only access, e.g. samples 100 to 200, and any samples
  28013. outside that will come back as 0. Accessing sample 0 from this reader will
  28014. actually read the first sample from the other's subsection, which might
  28015. be at a non-zero position.
  28016. @see AudioFormatReader
  28017. */
  28018. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  28019. {
  28020. public:
  28021. /** Creates a AudioSubsectionReader for a given data source.
  28022. @param sourceReader the source reader from which we'll be taking data
  28023. @param subsectionStartSample the sample within the source reader which will be
  28024. mapped onto sample 0 for this reader.
  28025. @param subsectionLength the number of samples from the source that will
  28026. make up the subsection. If this reader is asked for
  28027. any samples beyond this region, it will return zero.
  28028. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  28029. this object is deleted.
  28030. */
  28031. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  28032. const int64 subsectionStartSample,
  28033. const int64 subsectionLength,
  28034. const bool deleteSourceWhenDeleted);
  28035. /** Destructor. */
  28036. ~AudioSubsectionReader();
  28037. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  28038. int64 startSampleInFile, int numSamples);
  28039. void readMaxLevels (int64 startSample,
  28040. int64 numSamples,
  28041. float& lowestLeft,
  28042. float& highestLeft,
  28043. float& lowestRight,
  28044. float& highestRight);
  28045. juce_UseDebuggingNewOperator
  28046. private:
  28047. AudioFormatReader* const source;
  28048. int64 startSample, length;
  28049. const bool deleteSourceWhenDeleted;
  28050. AudioSubsectionReader (const AudioSubsectionReader&);
  28051. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  28052. };
  28053. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  28054. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  28055. #endif
  28056. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28057. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  28058. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28059. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28060. /**
  28061. Reads and Writes WAV format audio files.
  28062. @see AudioFormat
  28063. */
  28064. class JUCE_API WavAudioFormat : public AudioFormat
  28065. {
  28066. public:
  28067. /** Creates a format object. */
  28068. WavAudioFormat();
  28069. /** Destructor. */
  28070. ~WavAudioFormat();
  28071. /** Metadata property name used by wav readers and writers for adding
  28072. a BWAV chunk to the file.
  28073. @see AudioFormatReader::metadataValues, createWriterFor
  28074. */
  28075. static const tchar* const bwavDescription;
  28076. /** Metadata property name used by wav readers and writers for adding
  28077. a BWAV chunk to the file.
  28078. @see AudioFormatReader::metadataValues, createWriterFor
  28079. */
  28080. static const tchar* const bwavOriginator;
  28081. /** Metadata property name used by wav readers and writers for adding
  28082. a BWAV chunk to the file.
  28083. @see AudioFormatReader::metadataValues, createWriterFor
  28084. */
  28085. static const tchar* const bwavOriginatorRef;
  28086. /** Metadata property name used by wav readers and writers for adding
  28087. a BWAV chunk to the file.
  28088. Date format is: yyyy-mm-dd
  28089. @see AudioFormatReader::metadataValues, createWriterFor
  28090. */
  28091. static const tchar* const bwavOriginationDate;
  28092. /** Metadata property name used by wav readers and writers for adding
  28093. a BWAV chunk to the file.
  28094. Time format is: hh-mm-ss
  28095. @see AudioFormatReader::metadataValues, createWriterFor
  28096. */
  28097. static const tchar* const bwavOriginationTime;
  28098. /** Metadata property name used by wav readers and writers for adding
  28099. a BWAV chunk to the file.
  28100. This is the number of samples from the start of an edit that the
  28101. file is supposed to begin at. Seems like an obvious mistake to
  28102. only allow a file to occur in an edit once, but that's the way
  28103. it is..
  28104. @see AudioFormatReader::metadataValues, createWriterFor
  28105. */
  28106. static const tchar* const bwavTimeReference;
  28107. /** Metadata property name used by wav readers and writers for adding
  28108. a BWAV chunk to the file.
  28109. This is a
  28110. @see AudioFormatReader::metadataValues, createWriterFor
  28111. */
  28112. static const tchar* const bwavCodingHistory;
  28113. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28114. This just makes it easier than using the property names directly, and it
  28115. fills out the time and date in the right format.
  28116. */
  28117. static const StringPairArray createBWAVMetadata (const String& description,
  28118. const String& originator,
  28119. const String& originatorRef,
  28120. const Time& dateAndTime,
  28121. const int64 timeReferenceSamples,
  28122. const String& codingHistory);
  28123. const Array <int> getPossibleSampleRates();
  28124. const Array <int> getPossibleBitDepths();
  28125. bool canDoStereo();
  28126. bool canDoMono();
  28127. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28128. const bool deleteStreamIfOpeningFails);
  28129. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28130. double sampleRateToUse,
  28131. unsigned int numberOfChannels,
  28132. int bitsPerSample,
  28133. const StringPairArray& metadataValues,
  28134. int qualityOptionIndex);
  28135. /** Utility function to replace the metadata in a wav file with a new set of values.
  28136. If possible, this cheats by overwriting just the metadata region of the file, rather
  28137. than by copying the whole file again.
  28138. */
  28139. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28140. juce_UseDebuggingNewOperator
  28141. };
  28142. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28143. /********* End of inlined file: juce_WavAudioFormat.h *********/
  28144. #endif
  28145. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  28146. #endif
  28147. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28148. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  28149. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28150. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28151. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28152. /**
  28153. Reads and writes the Ogg-Vorbis audio format.
  28154. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28155. and make sure your include search path and library search path are set up to find
  28156. the Vorbis and Ogg header files and static libraries.
  28157. @see AudioFormat,
  28158. */
  28159. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28160. {
  28161. public:
  28162. OggVorbisAudioFormat();
  28163. ~OggVorbisAudioFormat();
  28164. const Array <int> getPossibleSampleRates();
  28165. const Array <int> getPossibleBitDepths();
  28166. bool canDoStereo();
  28167. bool canDoMono();
  28168. bool isCompressed();
  28169. const StringArray getQualityOptions();
  28170. /** Tries to estimate the quality level of an ogg file based on its size.
  28171. If it can't read the file for some reason, this will just return 1 (medium quality),
  28172. otherwise it will return the approximate quality setting that would have been used
  28173. to create the file.
  28174. @see getQualityOptions
  28175. */
  28176. int estimateOggFileQuality (const File& source);
  28177. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28178. const bool deleteStreamIfOpeningFails);
  28179. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28180. double sampleRateToUse,
  28181. unsigned int numberOfChannels,
  28182. int bitsPerSample,
  28183. const StringPairArray& metadataValues,
  28184. int qualityOptionIndex);
  28185. juce_UseDebuggingNewOperator
  28186. };
  28187. #endif
  28188. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28189. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  28190. #endif
  28191. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28192. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  28193. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28194. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28195. #if JUCE_QUICKTIME
  28196. /**
  28197. Uses QuickTime to read the audio track a movie or media file.
  28198. As well as QuickTime movies, this should also manage to open other audio
  28199. files that quicktime can understand, like mp3, m4a, etc.
  28200. @see AudioFormat
  28201. */
  28202. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28203. {
  28204. public:
  28205. /** Creates a format object. */
  28206. QuickTimeAudioFormat();
  28207. /** Destructor. */
  28208. ~QuickTimeAudioFormat();
  28209. const Array <int> getPossibleSampleRates();
  28210. const Array <int> getPossibleBitDepths();
  28211. bool canDoStereo();
  28212. bool canDoMono();
  28213. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28214. const bool deleteStreamIfOpeningFails);
  28215. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28216. double sampleRateToUse,
  28217. unsigned int numberOfChannels,
  28218. int bitsPerSample,
  28219. const StringPairArray& metadataValues,
  28220. int qualityOptionIndex);
  28221. juce_UseDebuggingNewOperator
  28222. };
  28223. #endif
  28224. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28225. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  28226. #endif
  28227. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28228. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  28229. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28230. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28231. /********* Start of inlined file: juce_ActionListenerList.h *********/
  28232. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28233. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28234. /**
  28235. A set of ActionListeners.
  28236. Listeners can be added and removed from the list, and messages can be
  28237. broadcast to all the listeners.
  28238. @see ActionListener, ActionBroadcaster
  28239. */
  28240. class JUCE_API ActionListenerList : public MessageListener
  28241. {
  28242. public:
  28243. /** Creates an empty list. */
  28244. ActionListenerList() throw();
  28245. /** Destructor. */
  28246. ~ActionListenerList() throw();
  28247. /** Adds a listener to the list.
  28248. (Trying to add a listener that's already on the list will have no effect).
  28249. */
  28250. void addActionListener (ActionListener* const listener) throw();
  28251. /** Removes a listener from the list.
  28252. If the listener isn't on the list, this won't have any effect.
  28253. */
  28254. void removeActionListener (ActionListener* const listener) throw();
  28255. /** Removes all listeners from the list. */
  28256. void removeAllActionListeners() throw();
  28257. /** Broadcasts a message to all the registered listeners.
  28258. This sends the message asynchronously.
  28259. If a listener is on the list when this method is called but is removed from
  28260. the list before the message arrives, it won't receive the message. Similarly
  28261. listeners that are added to the list after the message is sent but before it
  28262. arrives won't get the message either.
  28263. */
  28264. void sendActionMessage (const String& message) const;
  28265. /** @internal */
  28266. void handleMessage (const Message&);
  28267. juce_UseDebuggingNewOperator
  28268. private:
  28269. SortedSet <void*> actionListeners_;
  28270. CriticalSection actionListenerLock_;
  28271. ActionListenerList (const ActionListenerList&);
  28272. const ActionListenerList& operator= (const ActionListenerList&);
  28273. };
  28274. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28275. /********* End of inlined file: juce_ActionListenerList.h *********/
  28276. /** Manages a list of ActionListeners, and can send them messages.
  28277. To quickly add methods to your class that can add/remove action
  28278. listeners and broadcast to them, you can derive from this.
  28279. @see ActionListenerList, ActionListener
  28280. */
  28281. class JUCE_API ActionBroadcaster
  28282. {
  28283. public:
  28284. /** Creates an ActionBroadcaster. */
  28285. ActionBroadcaster() throw();
  28286. /** Destructor. */
  28287. virtual ~ActionBroadcaster();
  28288. /** Adds a listener to the list.
  28289. (Trying to add a listener that's already on the list will have no effect).
  28290. */
  28291. void addActionListener (ActionListener* const listener);
  28292. /** Removes a listener from the list.
  28293. If the listener isn't on the list, this won't have any effect.
  28294. */
  28295. void removeActionListener (ActionListener* const listener);
  28296. /** Removes all listeners from the list. */
  28297. void removeAllActionListeners();
  28298. /** Broadcasts a message to all the registered listeners.
  28299. @see ActionListenerList::sendActionMessage
  28300. */
  28301. void sendActionMessage (const String& message) const;
  28302. private:
  28303. ActionListenerList actionListenerList;
  28304. ActionBroadcaster (const ActionBroadcaster&);
  28305. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  28306. };
  28307. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28308. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  28309. #endif
  28310. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  28311. #endif
  28312. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28313. #endif
  28314. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  28315. #endif
  28316. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28317. /********* Start of inlined file: juce_CallbackMessage.h *********/
  28318. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28319. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28320. /**
  28321. A message that calls a custom function when it gets delivered.
  28322. You can use this class to fire off actions that you want to be performed later
  28323. on the message thread.
  28324. Unlike other Message objects, these don't get sent to a MessageListener, you
  28325. just call the post() method to send them, and when they arrive, your
  28326. messageCallback() method will automatically be invoked.
  28327. @see MessageListener, MessageManager, ActionListener, ChangeListener
  28328. */
  28329. class JUCE_API CallbackMessage : public Message
  28330. {
  28331. public:
  28332. CallbackMessage() throw();
  28333. /** Destructor. */
  28334. ~CallbackMessage() throw();
  28335. /** Called when the message is delivered.
  28336. You should implement this method and make it do whatever action you want
  28337. to perform.
  28338. Note that like all other messages, this object will be deleted immediately
  28339. after this method has been invoked.
  28340. */
  28341. virtual void messageCallback() = 0;
  28342. /** Instead of sending this message to a MessageListener, just call this method
  28343. to post it to the event queue.
  28344. After you've called this, this object will belong to the MessageManager,
  28345. which will delete it later. So make sure you don't delete the object yourself,
  28346. call post() more than once, or call post() on a stack-based obect!
  28347. */
  28348. void post();
  28349. juce_UseDebuggingNewOperator
  28350. private:
  28351. CallbackMessage (const CallbackMessage&);
  28352. const CallbackMessage& operator= (const CallbackMessage&);
  28353. };
  28354. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28355. /********* End of inlined file: juce_CallbackMessage.h *********/
  28356. #endif
  28357. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  28358. #endif
  28359. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  28360. #endif
  28361. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  28362. #endif
  28363. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28364. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  28365. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28366. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28367. class InterprocessConnectionServer;
  28368. /**
  28369. Manages a simple two-way messaging connection to another process, using either
  28370. a socket or a named pipe as the transport medium.
  28371. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  28372. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  28373. and incoming messages will result in a callback via the messageReceived()
  28374. method.
  28375. To open a pipe and wait for another client to connect to it, use the createPipe()
  28376. method.
  28377. To act as a socket server and create connections for one or more client, see the
  28378. InterprocessConnectionServer class.
  28379. @see InterprocessConnectionServer, Socket, NamedPipe
  28380. */
  28381. class JUCE_API InterprocessConnection : public Thread,
  28382. private MessageListener
  28383. {
  28384. public:
  28385. /** Creates a connection.
  28386. Connections are created manually, connecting them with the connectToSocket()
  28387. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  28388. when a client wants to connect.
  28389. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  28390. connectionLost() and messageReceived() methods will
  28391. always be made using the message thread; if false,
  28392. these will be called immediately on the connection's
  28393. own thread.
  28394. @param magicMessageHeaderNumber a magic number to use in the header to check the
  28395. validity of the data blocks being sent and received. This
  28396. can be any number, but the sender and receiver must obviously
  28397. use matching values or they won't recognise each other.
  28398. */
  28399. InterprocessConnection (const bool callbacksOnMessageThread = true,
  28400. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  28401. /** Destructor. */
  28402. ~InterprocessConnection();
  28403. /** Tries to connect this object to a socket.
  28404. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  28405. object waiting to receive client connections on this port number.
  28406. @param hostName the host computer, either a network address or name
  28407. @param portNumber the socket port number to try to connect to
  28408. @param timeOutMillisecs how long to keep trying before giving up
  28409. @returns true if the connection is established successfully
  28410. @see Socket
  28411. */
  28412. bool connectToSocket (const String& hostName,
  28413. const int portNumber,
  28414. const int timeOutMillisecs);
  28415. /** Tries to connect the object to an existing named pipe.
  28416. For this to work, another process on the same computer must already have opened
  28417. an InterprocessConnection object and used createPipe() to create a pipe for this
  28418. to connect to.
  28419. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  28420. @returns true if it connects successfully.
  28421. @see createPipe, NamedPipe
  28422. */
  28423. bool connectToPipe (const String& pipeName,
  28424. const int pipeReceiveMessageTimeoutMs = -1);
  28425. /** Tries to create a new pipe for other processes to connect to.
  28426. This creates a pipe with the given name, so that other processes can use
  28427. connectToPipe() to connect to the other end.
  28428. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  28429. If another process is already using this pipe, this will fail and return false.
  28430. */
  28431. bool createPipe (const String& pipeName,
  28432. const int pipeReceiveMessageTimeoutMs = -1);
  28433. /** Disconnects and closes any currently-open sockets or pipes. */
  28434. void disconnect();
  28435. /** True if a socket or pipe is currently active. */
  28436. bool isConnected() const;
  28437. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  28438. StreamingSocket* getSocket() const throw() { return socket; }
  28439. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  28440. NamedPipe* getPipe() const throw() { return pipe; }
  28441. /** Returns the name of the machine at the other end of this connection.
  28442. This will return an empty string if the other machine isn't known for
  28443. some reason.
  28444. */
  28445. const String getConnectedHostName() const;
  28446. /** Tries to send a message to the other end of this connection.
  28447. This will fail if it's not connected, or if there's some kind of write error. If
  28448. it succeeds, the connection object at the other end will receive the message by
  28449. a callback to its messageReceived() method.
  28450. @see messageReceived
  28451. */
  28452. bool sendMessage (const MemoryBlock& message);
  28453. /** Called when the connection is first connected.
  28454. If the connection was created with the callbacksOnMessageThread flag set, then
  28455. this will be called on the message thread; otherwise it will be called on a server
  28456. thread.
  28457. */
  28458. virtual void connectionMade() = 0;
  28459. /** Called when the connection is broken.
  28460. If the connection was created with the callbacksOnMessageThread flag set, then
  28461. this will be called on the message thread; otherwise it will be called on a server
  28462. thread.
  28463. */
  28464. virtual void connectionLost() = 0;
  28465. /** Called when a message arrives.
  28466. When the object at the other end of this connection sends us a message with sendMessage(),
  28467. this callback is used to deliver it to us.
  28468. If the connection was created with the callbacksOnMessageThread flag set, then
  28469. this will be called on the message thread; otherwise it will be called on a server
  28470. thread.
  28471. @see sendMessage
  28472. */
  28473. virtual void messageReceived (const MemoryBlock& message) = 0;
  28474. juce_UseDebuggingNewOperator
  28475. private:
  28476. CriticalSection pipeAndSocketLock;
  28477. StreamingSocket* socket;
  28478. NamedPipe* pipe;
  28479. bool callbackConnectionState;
  28480. const bool useMessageThread;
  28481. const uint32 magicMessageHeader;
  28482. int pipeReceiveMessageTimeout;
  28483. friend class InterprocessConnectionServer;
  28484. void initialiseWithSocket (StreamingSocket* const socket_);
  28485. void initialiseWithPipe (NamedPipe* const pipe_);
  28486. void handleMessage (const Message& message);
  28487. void connectionMadeInt();
  28488. void connectionLostInt();
  28489. void deliverDataInt (const MemoryBlock& data);
  28490. bool readNextMessageInt();
  28491. void run();
  28492. InterprocessConnection (const InterprocessConnection&);
  28493. const InterprocessConnection& operator= (const InterprocessConnection&);
  28494. };
  28495. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28496. /********* End of inlined file: juce_InterprocessConnection.h *********/
  28497. #endif
  28498. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28499. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  28500. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28501. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28502. /**
  28503. An object that waits for client sockets to connect to a port on this host, and
  28504. creates InterprocessConnection objects for each one.
  28505. To use this, create a class derived from it which implements the createConnectionObject()
  28506. method, so that it creates suitable connection objects for each client that tries
  28507. to connect.
  28508. @see InterprocessConnection
  28509. */
  28510. class JUCE_API InterprocessConnectionServer : private Thread
  28511. {
  28512. public:
  28513. /** Creates an uninitialised server object.
  28514. */
  28515. InterprocessConnectionServer();
  28516. /** Destructor. */
  28517. ~InterprocessConnectionServer();
  28518. /** Starts an internal thread which listens on the given port number.
  28519. While this is running, in another process tries to connect with the
  28520. InterprocessConnection::connectToSocket() method, this object will call
  28521. createConnectionObject() to create a connection to that client.
  28522. Use stop() to stop the thread running.
  28523. @see createConnectionObject, stop
  28524. */
  28525. bool beginWaitingForSocket (const int portNumber);
  28526. /** Terminates the listener thread, if it's active.
  28527. @see beginWaitingForSocket
  28528. */
  28529. void stop();
  28530. protected:
  28531. /** Creates a suitable connection object for a client process that wants to
  28532. connect to this one.
  28533. This will be called by the listener thread when a client process tries
  28534. to connect, and must return a new InterprocessConnection object that will
  28535. then run as this end of the connection.
  28536. @see InterprocessConnection
  28537. */
  28538. virtual InterprocessConnection* createConnectionObject() = 0;
  28539. public:
  28540. juce_UseDebuggingNewOperator
  28541. private:
  28542. StreamingSocket* volatile socket;
  28543. void run();
  28544. InterprocessConnectionServer (const InterprocessConnectionServer&);
  28545. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  28546. };
  28547. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28548. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  28549. #endif
  28550. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  28551. #endif
  28552. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  28553. #endif
  28554. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28555. /********* Start of inlined file: juce_MessageManager.h *********/
  28556. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28557. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28558. class Component;
  28559. class MessageManagerLock;
  28560. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  28561. */
  28562. typedef void* (MessageCallbackFunction) (void* userData);
  28563. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  28564. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  28565. */
  28566. class JUCE_API MessageManager
  28567. {
  28568. public:
  28569. /** Returns the global instance of the MessageManager. */
  28570. static MessageManager* getInstance() throw();
  28571. /** Runs the event dispatch loop until a stop message is posted.
  28572. This method is only intended to be run by the application's startup routine,
  28573. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  28574. @see stopDispatchLoop
  28575. */
  28576. void runDispatchLoop();
  28577. /** Sends a signal that the dispatch loop should terminate.
  28578. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  28579. will be interrupted and will return.
  28580. @see runDispatchLoop
  28581. */
  28582. void stopDispatchLoop();
  28583. /** Returns true if the stopDispatchLoop() method has been called.
  28584. */
  28585. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  28586. /** Synchronously dispatches messages until a given time has elapsed.
  28587. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  28588. otherwise returns true.
  28589. */
  28590. bool runDispatchLoopUntil (int millisecondsToRunFor);
  28591. /** Calls a function using the message-thread.
  28592. This can be used by any thread to cause this function to be called-back
  28593. by the message thread. If it's the message-thread that's calling this method,
  28594. then the function will just be called; if another thread is calling, a message
  28595. will be posted to the queue, and this method will block until that message
  28596. is delivered, the function is called, and the result is returned.
  28597. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  28598. thread has a critical section locked, which an unrelated message callback then tries to lock
  28599. before the message thread gets round to processing this callback.
  28600. @param callback the function to call - its signature must be @code
  28601. void* myCallbackFunction (void*) @endcode
  28602. @param userData a user-defined pointer that will be passed to the function that gets called
  28603. @returns the value that the callback function returns.
  28604. @see MessageManagerLock
  28605. */
  28606. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  28607. void* userData);
  28608. /** Returns true if the caller-thread is the message thread. */
  28609. bool isThisTheMessageThread() const throw();
  28610. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  28611. (Best to ignore this method unless you really know what you're doing..)
  28612. @see getCurrentMessageThread
  28613. */
  28614. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  28615. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  28616. (Best to ignore this method unless you really know what you're doing..)
  28617. @see setCurrentMessageThread
  28618. */
  28619. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  28620. /** Returns true if the caller thread has currenltly got the message manager locked.
  28621. see the MessageManagerLock class for more info about this.
  28622. This will be true if the caller is the message thread, because that automatically
  28623. gains a lock while a message is being dispatched.
  28624. */
  28625. bool currentThreadHasLockedMessageManager() const throw();
  28626. /** Sends a message to all other JUCE applications that are running.
  28627. @param messageText the string that will be passed to the actionListenerCallback()
  28628. method of the broadcast listeners in the other app.
  28629. @see registerBroadcastListener, ActionListener
  28630. */
  28631. static void broadcastMessage (const String& messageText) throw();
  28632. /** Registers a listener to get told about broadcast messages.
  28633. The actionListenerCallback() callback's string parameter
  28634. is the message passed into broadcastMessage().
  28635. @see broadcastMessage
  28636. */
  28637. void registerBroadcastListener (ActionListener* listener) throw();
  28638. /** Deregisters a broadcast listener. */
  28639. void deregisterBroadcastListener (ActionListener* listener) throw();
  28640. /** @internal */
  28641. void deliverMessage (void*);
  28642. /** @internal */
  28643. void deliverBroadcastMessage (const String&);
  28644. /** @internal */
  28645. ~MessageManager() throw();
  28646. juce_UseDebuggingNewOperator
  28647. private:
  28648. MessageManager() throw();
  28649. friend class MessageListener;
  28650. friend class ChangeBroadcaster;
  28651. friend class ActionBroadcaster;
  28652. friend class CallbackMessage;
  28653. static MessageManager* instance;
  28654. SortedSet<const MessageListener*> messageListeners;
  28655. ActionListenerList* broadcastListeners;
  28656. friend class JUCEApplication;
  28657. bool quitMessagePosted, quitMessageReceived;
  28658. Thread::ThreadID messageThreadId;
  28659. VoidArray modalComponents;
  28660. static void* exitModalLoopCallback (void*);
  28661. void postMessageToQueue (Message* const message);
  28662. void postCallbackMessage (Message* const message);
  28663. static void doPlatformSpecificInitialisation();
  28664. static void doPlatformSpecificShutdown();
  28665. friend class MessageManagerLock;
  28666. Thread::ThreadID volatile threadWithLock;
  28667. CriticalSection lockingLock;
  28668. MessageManager (const MessageManager&);
  28669. const MessageManager& operator= (const MessageManager&);
  28670. };
  28671. /** Used to make sure that the calling thread has exclusive access to the message loop.
  28672. Because it's not thread-safe to call any of the Component or other UI classes
  28673. from threads other than the message thread, one of these objects can be used to
  28674. lock the message loop and allow this to be done. The message thread will be
  28675. suspended for the lifetime of the MessageManagerLock object, so create one on
  28676. the stack like this: @code
  28677. void MyThread::run()
  28678. {
  28679. someData = 1234;
  28680. const MessageManagerLock mmLock;
  28681. // the event loop will now be locked so it's safe to make a few calls..
  28682. myComponent->setBounds (newBounds);
  28683. myComponent->repaint();
  28684. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  28685. }
  28686. @endcode
  28687. Obviously be careful not to create one of these and leave it lying around, or
  28688. your app will grind to a halt!
  28689. Another caveat is that using this in conjunction with other CriticalSections
  28690. can create lots of interesting ways of producing a deadlock! In particular, if
  28691. your message thread calls stopThread() for a thread that uses these locks,
  28692. you'll get an (occasional) deadlock..
  28693. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  28694. */
  28695. class JUCE_API MessageManagerLock
  28696. {
  28697. public:
  28698. /** Tries to acquire a lock on the message manager.
  28699. The constructor attempts to gain a lock on the message loop, and the lock will be
  28700. kept for the lifetime of this object.
  28701. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  28702. this method will keep checking whether the thread has been given the
  28703. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  28704. without gaining the lock. If you pass a thread, you must check whether the lock was
  28705. successful by calling lockWasGained(). If this is false, your thread is being told to
  28706. die, so you should take evasive action.
  28707. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  28708. careful when doing this, because it's very easy to deadlock if your message thread
  28709. attempts to call stopThread() on a thread just as that thread attempts to get the
  28710. message lock.
  28711. If the calling thread already has the lock, nothing will be done, so it's safe and
  28712. quick to use these locks recursively.
  28713. E.g.
  28714. @code
  28715. void run()
  28716. {
  28717. ...
  28718. while (! threadShouldExit())
  28719. {
  28720. MessageManagerLock mml (Thread::getCurrentThread());
  28721. if (! mml.lockWasGained())
  28722. return; // another thread is trying to kill us!
  28723. ..do some locked stuff here..
  28724. }
  28725. ..and now the MM is now unlocked..
  28726. }
  28727. @endcode
  28728. */
  28729. MessageManagerLock (Thread* const threadToCheckForExitSignal = 0) throw();
  28730. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  28731. instead of a thread.
  28732. See the MessageManagerLock (Thread*) constructor for details on how this works.
  28733. */
  28734. MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw();
  28735. /** Releases the current thread's lock on the message manager.
  28736. Make sure this object is created and deleted by the same thread,
  28737. otherwise there are no guarantees what will happen!
  28738. */
  28739. ~MessageManagerLock() throw();
  28740. /** Returns true if the lock was successfully acquired.
  28741. (See the constructor that takes a Thread for more info).
  28742. */
  28743. bool lockWasGained() const throw() { return locked; }
  28744. private:
  28745. bool locked, needsUnlocking;
  28746. void* sharedEvents;
  28747. void init (Thread* const thread, ThreadPoolJob* const job) throw();
  28748. };
  28749. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28750. /********* End of inlined file: juce_MessageManager.h *********/
  28751. #endif
  28752. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28753. /********* Start of inlined file: juce_MultiTimer.h *********/
  28754. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28755. #define __JUCE_MULTITIMER_JUCEHEADER__
  28756. /**
  28757. A type of timer class that can run multiple timers with different frequencies,
  28758. all of which share a single callback.
  28759. This class is very similar to the Timer class, but allows you run multiple
  28760. separate timers, where each one has a unique ID number. The methods in this
  28761. class are exactly equivalent to those in Timer, but with the addition of
  28762. this ID number.
  28763. To use it, you need to create a subclass of MultiTimer, implementing the
  28764. timerCallback() method. Then you can start timers with startTimer(), and
  28765. each time the callback is triggered, it passes in the ID of the timer that
  28766. caused it.
  28767. @see Timer
  28768. */
  28769. class JUCE_API MultiTimer
  28770. {
  28771. protected:
  28772. /** Creates a MultiTimer.
  28773. When created, no timers are running, so use startTimer() to start things off.
  28774. */
  28775. MultiTimer() throw();
  28776. /** Creates a copy of another timer.
  28777. Note that this timer will not contain any running timers, even if the one you're
  28778. copying from was running.
  28779. */
  28780. MultiTimer (const MultiTimer& other) throw();
  28781. public:
  28782. /** Destructor. */
  28783. virtual ~MultiTimer();
  28784. /** The user-defined callback routine that actually gets called by each of the
  28785. timers that are running.
  28786. It's perfectly ok to call startTimer() or stopTimer() from within this
  28787. callback to change the subsequent intervals.
  28788. */
  28789. virtual void timerCallback (const int timerId) = 0;
  28790. /** Starts a timer and sets the length of interval required.
  28791. If the timer is already started, this will reset it, so the
  28792. time between calling this method and the next timer callback
  28793. will not be less than the interval length passed in.
  28794. @param timerId a unique Id number that identifies the timer to
  28795. start. This is the id that will be passed back
  28796. to the timerCallback() method when this timer is
  28797. triggered
  28798. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  28799. rounded up to 1)
  28800. */
  28801. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  28802. /** Stops a timer.
  28803. If a timer has been started with the given ID number, it will be cancelled.
  28804. No more callbacks will be made for the specified timer after this method returns.
  28805. If this is called from a different thread, any callbacks that may
  28806. be currently executing may be allowed to finish before the method
  28807. returns.
  28808. */
  28809. void stopTimer (const int timerId) throw();
  28810. /** Checks whether a timer has been started for a specified ID.
  28811. @returns true if a timer with the given ID is running.
  28812. */
  28813. bool isTimerRunning (const int timerId) const throw();
  28814. /** Returns the interval for a specified timer ID.
  28815. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28816. is running for the ID number specified.
  28817. */
  28818. int getTimerInterval (const int timerId) const throw();
  28819. private:
  28820. CriticalSection timerListLock;
  28821. VoidArray timers;
  28822. const MultiTimer& operator= (const MultiTimer&);
  28823. };
  28824. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28825. /********* End of inlined file: juce_MultiTimer.h *********/
  28826. #endif
  28827. #ifndef __JUCE_TIMER_JUCEHEADER__
  28828. #endif
  28829. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28830. #endif
  28831. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28832. /********* Start of inlined file: juce_GradientBrush.h *********/
  28833. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28834. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28835. /********* Start of inlined file: juce_ColourGradient.h *********/
  28836. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28837. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28838. /**
  28839. Structure used to define a colour gradient for painting areas.
  28840. @see GradientBrush
  28841. */
  28842. class JUCE_API ColourGradient
  28843. {
  28844. public:
  28845. /** Creates a gradient object.
  28846. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28847. colour2 should be. In between them there's a gradient.
  28848. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28849. its centre.
  28850. The alpha transparencies of the colours are used, so note that
  28851. if you blend from transparent to a solid colour, the RGB of the transparent
  28852. colour will become visible in parts of the gradient. e.g. blending
  28853. from Colour::transparentBlack to Colours::white will produce a
  28854. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28855. will be white all the way across.
  28856. @see ColourGradient
  28857. */
  28858. ColourGradient (const Colour& colour1,
  28859. const float x1,
  28860. const float y1,
  28861. const Colour& colour2,
  28862. const float x2,
  28863. const float y2,
  28864. const bool isRadial) throw();
  28865. /** Creates an uninitialised gradient.
  28866. If you use this constructor instead of the other one, be sure to set all the
  28867. object's public member variables before using it!
  28868. */
  28869. ColourGradient() throw();
  28870. /** Destructor */
  28871. ~ColourGradient() throw();
  28872. /** Removes any colours that have been added.
  28873. This will also remove any start and end colours, so the gradient won't work. You'll
  28874. need to add more colours with addColour().
  28875. */
  28876. void clearColours() throw();
  28877. /** Adds a colour at a point along the length of the gradient.
  28878. This allows the gradient to go through a spectrum of colours, instead of just a
  28879. start and end colour.
  28880. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28881. of the distance along the line between the two points
  28882. at which the colour should occur.
  28883. @param colour the colour that should be used at this point
  28884. */
  28885. void addColour (const double proportionAlongGradient,
  28886. const Colour& colour) throw();
  28887. /** Multiplies the alpha value of all the colours by the given scale factor */
  28888. void multiplyOpacity (const float multiplier) throw();
  28889. /** Returns the number of colour-stops that have been added. */
  28890. int getNumColours() const throw();
  28891. /** Returns the position along the length of the gradient of the colour with this index.
  28892. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28893. */
  28894. double getColourPosition (const int index) const throw();
  28895. /** Returns the colour that was added with a given index.
  28896. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28897. */
  28898. const Colour getColour (const int index) const throw();
  28899. /** Creates a set of interpolated premultiplied ARGB values.
  28900. The caller must delete the array that is returned using juce_free().
  28901. */
  28902. PixelARGB* createLookupTable (int& numEntries) const throw();
  28903. /** Returns true if all colours are opaque. */
  28904. bool isOpaque() const throw();
  28905. /** Returns true if all colours are completely transparent. */
  28906. bool isInvisible() const throw();
  28907. float x1;
  28908. float y1;
  28909. float x2;
  28910. float y2;
  28911. /** If true, the gradient should be filled circularly, centred around
  28912. (x1, y1), with (x2, y2) defining a point on the circumference.
  28913. If false, the gradient is linear between the two points.
  28914. */
  28915. bool isRadial;
  28916. /** A transform to apply to the resultant gradient shape */
  28917. AffineTransform transform;
  28918. juce_UseDebuggingNewOperator
  28919. private:
  28920. Array <uint32> colours;
  28921. };
  28922. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28923. /********* End of inlined file: juce_ColourGradient.h *********/
  28924. /**
  28925. A Brush that fills areas with a colour gradient.
  28926. The gradient can either be linear or circular.
  28927. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28928. */
  28929. class JUCE_API GradientBrush : public Brush
  28930. {
  28931. public:
  28932. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28933. (x1, y1) is the location relative to the origin of the Graphics context,
  28934. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28935. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28936. its centre.
  28937. The alpha transparencies of the colours are used, so the brush
  28938. need not be completely opaque. Note that this means that if you
  28939. blend from transparent to a solid colour, the RGB of the transparent
  28940. colour will become visible in parts of the gradient. e.g. blending
  28941. from Colour::transparentBlack to Colours::white will produce a
  28942. grey colour, but Colour::transparentWhite to Colours::white will be
  28943. white all the way across.
  28944. @see ColourGradient
  28945. */
  28946. GradientBrush (const Colour& colour1,
  28947. const float x1,
  28948. const float y1,
  28949. const Colour& colour2,
  28950. const float x2,
  28951. const float y2,
  28952. const bool isRadial) throw();
  28953. /** Creates a gradient brush from a ColourGradient object.
  28954. */
  28955. GradientBrush (const ColourGradient& gradient) throw();
  28956. /** Destructor. */
  28957. ~GradientBrush() throw();
  28958. /** Returns the current gradient information */
  28959. const ColourGradient& getGradient() const throw() { return gradient; }
  28960. Brush* createCopy() const throw();
  28961. void applyTransform (const AffineTransform& transform) throw();
  28962. void multiplyOpacity (const float multiple) throw();
  28963. bool isInvisible() const throw();
  28964. void paintPath (LowLevelGraphicsContext& context,
  28965. const Path& path, const AffineTransform& transform) throw();
  28966. void paintRectangle (LowLevelGraphicsContext& context,
  28967. int x, int y, int w, int h) throw();
  28968. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28969. const Image& alphaChannelImage, int imageX, int imageY,
  28970. int x, int y, int w, int h) throw();
  28971. juce_UseDebuggingNewOperator
  28972. protected:
  28973. ColourGradient gradient;
  28974. private:
  28975. GradientBrush (const GradientBrush&);
  28976. const GradientBrush& operator= (const GradientBrush&);
  28977. };
  28978. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28979. /********* End of inlined file: juce_GradientBrush.h *********/
  28980. #endif
  28981. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28982. /********* Start of inlined file: juce_ImageBrush.h *********/
  28983. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28984. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28985. /********* Start of inlined file: juce_Image.h *********/
  28986. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28987. #define __JUCE_IMAGE_JUCEHEADER__
  28988. /**
  28989. Holds a fixed-size bitmap.
  28990. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28991. To draw into an image, create a Graphics object for it.
  28992. e.g. @code
  28993. // create a transparent 500x500 image..
  28994. Image myImage (Image::RGB, 500, 500, true);
  28995. Graphics g (myImage);
  28996. g.setColour (Colours::red);
  28997. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28998. @endcode
  28999. Other useful ways to create an image are with the ImageCache class, or the
  29000. ImageFileFormat, which provides a way to load common image files.
  29001. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  29002. */
  29003. class JUCE_API Image
  29004. {
  29005. public:
  29006. enum PixelFormat
  29007. {
  29008. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  29009. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  29010. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  29011. };
  29012. /** Creates an in-memory image with a specified size and format.
  29013. @param format the number of colour channels in the image
  29014. @param imageWidth the desired width of the image, in pixels - this value must be
  29015. greater than zero (otherwise a width of 1 will be used)
  29016. @param imageHeight the desired width of the image, in pixels - this value must be
  29017. greater than zero (otherwise a height of 1 will be used)
  29018. @param clearImage if true, the image will initially be cleared to black or transparent
  29019. black. If false, the image may contain random data, and the
  29020. user will have to deal with this
  29021. */
  29022. Image (const PixelFormat format,
  29023. const int imageWidth,
  29024. const int imageHeight,
  29025. const bool clearImage);
  29026. /** Creates a copy of another image.
  29027. @see createCopy
  29028. */
  29029. Image (const Image& other);
  29030. /** Destructor. */
  29031. virtual ~Image();
  29032. /** Returns the image's width (in pixels). */
  29033. int getWidth() const throw() { return imageWidth; }
  29034. /** Returns the image's height (in pixels). */
  29035. int getHeight() const throw() { return imageHeight; }
  29036. /** Returns the image's pixel format. */
  29037. PixelFormat getFormat() const throw() { return format; }
  29038. /** True if the image's format is ARGB. */
  29039. bool isARGB() const throw() { return format == ARGB; }
  29040. /** True if the image's format is RGB. */
  29041. bool isRGB() const throw() { return format == RGB; }
  29042. /** True if the image contains an alpha-channel. */
  29043. bool hasAlphaChannel() const throw() { return format != RGB; }
  29044. /** Clears a section of the image with a given colour.
  29045. This won't do any alpha-blending - it just sets all pixels in the image to
  29046. the given colour (which may be non-opaque if the image has an alpha channel).
  29047. */
  29048. virtual void clear (int x, int y, int w, int h,
  29049. const Colour& colourToClearTo = Colour (0x00000000));
  29050. /** Returns a new image that's a copy of this one.
  29051. A new size for the copied image can be specified, or values less than
  29052. zero can be passed-in to use the image's existing dimensions.
  29053. It's up to the caller to delete the image when no longer needed.
  29054. */
  29055. virtual Image* createCopy (int newWidth = -1,
  29056. int newHeight = -1,
  29057. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  29058. /** Returns the colour of one of the pixels in the image.
  29059. If the co-ordinates given are beyond the image's boundaries, this will
  29060. return Colours::transparentBlack.
  29061. (0, 0) is the image's top-left corner.
  29062. @see getAlphaAt, setPixelAt, blendPixelAt
  29063. */
  29064. virtual const Colour getPixelAt (const int x, const int y) const;
  29065. /** Sets the colour of one of the image's pixels.
  29066. If the co-ordinates are beyond the image's boundaries, then nothing will
  29067. happen.
  29068. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  29069. just replace the existing pixel with the given one. The colour's opacity
  29070. will be ignored if this image doesn't have an alpha-channel.
  29071. (0, 0) is the image's top-left corner.
  29072. @see blendPixelAt
  29073. */
  29074. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  29075. /** Changes the opacity of a pixel.
  29076. This only has an effect if the image has an alpha channel and if the
  29077. given co-ordinates are inside the image's boundary.
  29078. The multiplier must be in the range 0 to 1.0, and the current alpha
  29079. at the given co-ordinates will be multiplied by this value.
  29080. @see getAlphaAt, setPixelAt
  29081. */
  29082. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  29083. /** Changes the overall opacity of the image.
  29084. This will multiply the alpha value of each pixel in the image by the given
  29085. amount (limiting the resulting alpha values between 0 and 255). This allows
  29086. you to make an image more or less transparent.
  29087. If the image doesn't have an alpha channel, this won't have any effect.
  29088. */
  29089. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  29090. /** Changes all the colours to be shades of grey, based on their current luminosity.
  29091. */
  29092. virtual void desaturate();
  29093. /** Locks some of the pixels in the image so they can be read and written to.
  29094. This returns a pointer to some memory containing the pixels in the given
  29095. rectangle. It also returns values for the line and pixel stride used within
  29096. the data. The format of the pixel data is the same as that of this image.
  29097. When you've finished reading and changing the data, you must call
  29098. releasePixelDataReadWrite() to give the pixels back to the image.
  29099. For images that are stored in memory, this method may just return a direct
  29100. pointer to the image's data, but other types of image may be stored elsewhere,
  29101. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  29102. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  29103. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  29104. instead.
  29105. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  29106. */
  29107. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  29108. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  29109. */
  29110. virtual void releasePixelDataReadWrite (void* sourceData);
  29111. /** Locks some of the pixels in the image so they can be read.
  29112. This returns a pointer to some memory containing the pixels in the given
  29113. rectangle. It also returns values for the line and pixel stride used within
  29114. the data. The format of the pixel data is the same as that of this image.
  29115. When you've finished reading the data, you must call releasePixelDataReadOnly()
  29116. to let the image free the memory if necessary.
  29117. For images that are stored in memory, this method may just return a direct
  29118. pointer to the image's data, but other types of image may be stored elsewhere,
  29119. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  29120. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  29121. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  29122. instead.
  29123. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  29124. */
  29125. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  29126. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  29127. */
  29128. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  29129. /** Copies some pixel values to a rectangle of the image.
  29130. The format of the pixel data must match that of the image itself, and the
  29131. rectangle supplied must be within the image's bounds.
  29132. */
  29133. virtual void setPixelData (int destX, int destY, int destW, int destH,
  29134. const uint8* sourcePixelData, int sourceLineStride);
  29135. /** Copies a section of the image to somewhere else within itself.
  29136. */
  29137. virtual void moveImageSection (int destX, int destY,
  29138. int sourceX, int sourceY,
  29139. int width, int height);
  29140. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  29141. of the image.
  29142. @param result the list that will have the area added to it
  29143. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  29144. above this level will be considered opaque
  29145. */
  29146. void createSolidAreaMask (RectangleList& result,
  29147. const float alphaThreshold = 0.5f) const;
  29148. juce_UseDebuggingNewOperator
  29149. /** Creates a context suitable for drawing onto this image.
  29150. Don't call this method directly! It's used internally by the Graphics class.
  29151. */
  29152. virtual LowLevelGraphicsContext* createLowLevelContext();
  29153. protected:
  29154. const PixelFormat format;
  29155. const int imageWidth, imageHeight;
  29156. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  29157. Image (const PixelFormat format,
  29158. const int imageWidth,
  29159. const int imageHeight);
  29160. int pixelStride, lineStride;
  29161. uint8* imageData;
  29162. private:
  29163. const Image& operator= (const Image&);
  29164. };
  29165. #endif // __JUCE_IMAGE_JUCEHEADER__
  29166. /********* End of inlined file: juce_Image.h *********/
  29167. /**
  29168. A Brush that fills areas with tiled repetitions of an image.
  29169. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  29170. */
  29171. class JUCE_API ImageBrush : public Brush
  29172. {
  29173. public:
  29174. /* Creates an image brush, ready for use in Graphics::setBrush().
  29175. (x, y) is an anchor point for the top-left of the image
  29176. A reference to the image passed in will be kept, so don't delete
  29177. it within the lifetime of this object
  29178. */
  29179. ImageBrush (Image* const image,
  29180. const int anchorX,
  29181. const int anchorY,
  29182. const float opacity) throw();
  29183. /** Destructor. */
  29184. ~ImageBrush() throw();
  29185. /** Returns the image currently being used. */
  29186. Image* getImage() const throw() { return image; }
  29187. /** Returns the current anchor X position. */
  29188. int getAnchorX() const throw() { return anchorX; }
  29189. /** Returns the current anchor Y position. */
  29190. int getAnchorY() const throw() { return anchorY; }
  29191. /** Returns the current opacity. */
  29192. float getOpacity() const throw() { return opacity; }
  29193. Brush* createCopy() const throw();
  29194. void applyTransform (const AffineTransform& transform) throw();
  29195. void multiplyOpacity (const float multiple) throw();
  29196. bool isInvisible() const throw();
  29197. void paintPath (LowLevelGraphicsContext& context,
  29198. const Path& path, const AffineTransform& transform) throw();
  29199. void paintRectangle (LowLevelGraphicsContext& context,
  29200. int x, int y, int w, int h) throw();
  29201. void paintAlphaChannel (LowLevelGraphicsContext& context,
  29202. const Image& alphaChannelImage, int imageX, int imageY,
  29203. int x, int y, int w, int h) throw();
  29204. juce_UseDebuggingNewOperator
  29205. protected:
  29206. Image* image;
  29207. int anchorX, anchorY;
  29208. float opacity;
  29209. private:
  29210. ImageBrush (const ImageBrush&);
  29211. const ImageBrush& operator= (const ImageBrush&);
  29212. void getStartXY (int& x, int& y) const throw();
  29213. };
  29214. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  29215. /********* End of inlined file: juce_ImageBrush.h *********/
  29216. #endif
  29217. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  29218. #endif
  29219. #ifndef __JUCE_COLOUR_JUCEHEADER__
  29220. #endif
  29221. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  29222. #endif
  29223. #ifndef __JUCE_COLOURS_JUCEHEADER__
  29224. #endif
  29225. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  29226. #endif
  29227. #ifndef __JUCE_FONT_JUCEHEADER__
  29228. #endif
  29229. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29230. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  29231. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29232. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29233. /**
  29234. An glyph from a particular font, with a particular size, style,
  29235. typeface and position.
  29236. @see GlyphArrangement, Font
  29237. */
  29238. class JUCE_API PositionedGlyph
  29239. {
  29240. public:
  29241. /** Returns the character the glyph represents. */
  29242. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  29243. /** Checks whether the glyph is actually empty. */
  29244. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  29245. /** Returns the position of the glyph's left-hand edge. */
  29246. float getLeft() const throw() { return x; }
  29247. /** Returns the position of the glyph's right-hand edge. */
  29248. float getRight() const throw() { return x + w; }
  29249. /** Returns the y position of the glyph's baseline. */
  29250. float getBaselineY() const throw() { return y; }
  29251. /** Returns the y position of the top of the glyph. */
  29252. float getTop() const throw() { return y - fontAscent; }
  29253. /** Returns the y position of the bottom of the glyph. */
  29254. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  29255. /** Shifts the glyph's position by a relative amount. */
  29256. void moveBy (const float deltaX,
  29257. const float deltaY) throw();
  29258. /** Draws the glyph into a graphics context. */
  29259. void draw (const Graphics& g) const throw();
  29260. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  29261. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29262. /** Returns the path for this glyph.
  29263. @param path the glyph's outline will be appended to this path
  29264. */
  29265. void createPath (Path& path) const throw();
  29266. /** Checks to see if a point lies within this glyph. */
  29267. bool hitTest (float x, float y) const throw();
  29268. juce_UseDebuggingNewOperator
  29269. private:
  29270. friend class GlyphArrangement;
  29271. float x, y, w;
  29272. float fontHeight, fontAscent, fontHorizontalScale;
  29273. bool isUnderlined;
  29274. const TypefaceGlyphInfo* glyphInfo;
  29275. PositionedGlyph() throw();
  29276. };
  29277. /**
  29278. A set of glyphs, each with a position.
  29279. You can create a GlyphArrangement, text to it and then draw it onto a
  29280. graphics context. It's used internally by the text methods in the
  29281. Graphics class, but can be used directly if more control is needed.
  29282. @see Font, PositionedGlyph
  29283. */
  29284. class JUCE_API GlyphArrangement
  29285. {
  29286. public:
  29287. /** Creates an empty arrangement. */
  29288. GlyphArrangement() throw();
  29289. /** Takes a copy of another arrangement. */
  29290. GlyphArrangement (const GlyphArrangement& other) throw();
  29291. /** Copies another arrangement onto this one.
  29292. To add another arrangement without clearing this one, use addGlyphArrangement().
  29293. */
  29294. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  29295. /** Destructor. */
  29296. ~GlyphArrangement() throw();
  29297. /** Returns the total number of glyphs in the arrangement. */
  29298. int getNumGlyphs() const throw() { return numGlyphs; }
  29299. /** Returns one of the glyphs from the arrangement.
  29300. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  29301. careful not to pass an out-of-range index here, as it
  29302. doesn't do any bounds-checking.
  29303. */
  29304. PositionedGlyph& getGlyph (const int index) const throw();
  29305. /** Clears all text from the arrangement and resets it.
  29306. */
  29307. void clear() throw();
  29308. /** Appends a line of text to the arrangement.
  29309. This will add the text as a single line, where x is the left-hand edge of the
  29310. first character, and y is the position for the text's baseline.
  29311. If the text contains new-lines or carriage-returns, this will ignore them - use
  29312. addJustifiedText() to add multi-line arrangements.
  29313. */
  29314. void addLineOfText (const Font& font,
  29315. const String& text,
  29316. const float x,
  29317. const float y) throw();
  29318. /** Adds a line of text, truncating it if it's wider than a specified size.
  29319. This is the same as addLineOfText(), but if the line's width exceeds the value
  29320. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  29321. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  29322. */
  29323. void addCurtailedLineOfText (const Font& font,
  29324. const String& text,
  29325. float x,
  29326. const float y,
  29327. const float maxWidthPixels,
  29328. const bool useEllipsis) throw();
  29329. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  29330. This will add text to the arrangement, breaking it into new lines either where there
  29331. is a new-line or carriage-return character in the text, or where a line's width
  29332. exceeds the value set in maxLineWidth.
  29333. Each line that is added will be laid out using the flags set in horizontalLayout, so
  29334. the lines can be left- or right-justified, or centred horizontally in the space
  29335. between x and (x + maxLineWidth).
  29336. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  29337. lines will be placed below it, separated by a distance of font.getHeight().
  29338. */
  29339. void addJustifiedText (const Font& font,
  29340. const String& text,
  29341. float x, float y,
  29342. const float maxLineWidth,
  29343. const Justification& horizontalLayout) throw();
  29344. /** Tries to fit some text withing a given space.
  29345. This does its best to make the given text readable within the specified rectangle,
  29346. so it useful for labelling things.
  29347. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  29348. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  29349. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  29350. it's been truncated.
  29351. A Justification parameter lets you specify how the text is laid out within the rectangle,
  29352. both horizontally and vertically.
  29353. @see Graphics::drawFittedText
  29354. */
  29355. void addFittedText (const Font& font,
  29356. const String& text,
  29357. float x, float y,
  29358. float width, float height,
  29359. const Justification& layout,
  29360. int maximumLinesToUse,
  29361. const float minimumHorizontalScale = 0.7f) throw();
  29362. /** Appends another glyph arrangement to this one. */
  29363. void addGlyphArrangement (const GlyphArrangement& other) throw();
  29364. /** Draws this glyph arrangement to a graphics context.
  29365. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  29366. method, which renders the glyphs as filled vectors.
  29367. */
  29368. void draw (const Graphics& g) const throw();
  29369. /** Draws this glyph arrangement to a graphics context.
  29370. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  29371. method for non-transformed arrangements.
  29372. */
  29373. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29374. /** Converts the set of glyphs into a path.
  29375. @param path the glyphs' outlines will be appended to this path
  29376. */
  29377. void createPath (Path& path) const throw();
  29378. /** Looks for a glyph that contains the given co-ordinate.
  29379. @returns the index of the glyph, or -1 if none were found.
  29380. */
  29381. int findGlyphIndexAt (float x, float y) const throw();
  29382. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  29383. @param startIndex the first glyph to test
  29384. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  29385. startIndex will be included
  29386. @param left on return, the leftmost co-ordinate of the rectangle
  29387. @param top on return, the top co-ordinate of the rectangle
  29388. @param right on return, the rightmost co-ordinate of the rectangle
  29389. @param bottom on return, the bottom co-ordinate of the rectangle
  29390. @param includeWhitespace if true, the extent of any whitespace characters will also
  29391. be taken into account
  29392. */
  29393. void getBoundingBox (int startIndex,
  29394. int numGlyphs,
  29395. float& left,
  29396. float& top,
  29397. float& right,
  29398. float& bottom,
  29399. const bool includeWhitespace) const throw();
  29400. /** Shifts a set of glyphs by a given amount.
  29401. @param startIndex the first glyph to transform
  29402. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  29403. startIndex will be used
  29404. @param deltaX the amount to add to their x-positions
  29405. @param deltaY the amount to add to their y-positions
  29406. */
  29407. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  29408. const float deltaX,
  29409. const float deltaY) throw();
  29410. /** Removes a set of glyphs from the arrangement.
  29411. @param startIndex the first glyph to remove
  29412. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  29413. startIndex will be deleted
  29414. */
  29415. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  29416. /** Expands or compresses a set of glyphs horizontally.
  29417. @param startIndex the first glyph to transform
  29418. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  29419. startIndex will be used
  29420. @param horizontalScaleFactor how much to scale their horizontal width by
  29421. */
  29422. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  29423. const float horizontalScaleFactor) throw();
  29424. /** Justifies a set of glyphs within a given space.
  29425. This moves the glyphs as a block so that the whole thing is located within the
  29426. given rectangle with the specified layout.
  29427. If the Justification::horizontallyJustified flag is specified, each line will
  29428. be stretched out to fill the specified width.
  29429. */
  29430. void justifyGlyphs (const int startIndex, const int numGlyphs,
  29431. const float x,
  29432. const float y,
  29433. const float width,
  29434. const float height,
  29435. const Justification& justification) throw();
  29436. juce_UseDebuggingNewOperator
  29437. private:
  29438. int numGlyphs, numAllocated;
  29439. PositionedGlyph* glyphs;
  29440. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  29441. void removeLast() throw();
  29442. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  29443. void incGlyphRefCount (const int index) const throw();
  29444. void decGlyphRefCount (const int index) const throw();
  29445. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  29446. };
  29447. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29448. /********* End of inlined file: juce_GlyphArrangement.h *********/
  29449. #endif
  29450. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29451. /********* Start of inlined file: juce_TextLayout.h *********/
  29452. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29453. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  29454. class Graphics;
  29455. /**
  29456. A laid-out arrangement of text.
  29457. You can add text in different fonts to a TextLayout object, then call its
  29458. layout() method to word-wrap it into lines. The layout can then be drawn
  29459. using a graphics context.
  29460. It's handy if you've got a message to display, because you can format it,
  29461. measure the extent of the layout, and then create a suitably-sized window
  29462. to show it in.
  29463. @see Font, Graphics::drawFittedText, GlyphArrangement
  29464. */
  29465. class JUCE_API TextLayout
  29466. {
  29467. public:
  29468. /** Creates an empty text layout.
  29469. Text can then be appended using the appendText() method.
  29470. */
  29471. TextLayout() throw();
  29472. /** Creates a copy of another layout object. */
  29473. TextLayout (const TextLayout& other) throw();
  29474. /** Creates a text layout from an initial string and font. */
  29475. TextLayout (const String& text, const Font& font) throw();
  29476. /** Destructor. */
  29477. ~TextLayout() throw();
  29478. /** Copies another layout onto this one. */
  29479. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  29480. /** Clears the layout, removing all its text. */
  29481. void clear() throw();
  29482. /** Adds a string to the end of the arrangement.
  29483. The string will be broken onto new lines wherever it contains
  29484. carriage-returns or linefeeds. After adding it, you can call layout()
  29485. to wrap long lines into a paragraph and justify it.
  29486. */
  29487. void appendText (const String& textToAppend,
  29488. const Font& fontToUse) throw();
  29489. /** Replaces all the text with a new string.
  29490. This is equivalent to calling clear() followed by appendText().
  29491. */
  29492. void setText (const String& newText,
  29493. const Font& fontToUse) throw();
  29494. /** Breaks the text up to form a paragraph with the given width.
  29495. @param maximumWidth any text wider than this will be split
  29496. across multiple lines
  29497. @param justification how the lines are to be laid-out horizontally
  29498. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  29499. width that keeps all the lines of text at a
  29500. similar length - this is good when you're displaying
  29501. a short message and don't want it to get split
  29502. onto two lines with only a couple of words on
  29503. the second line, which looks untidy.
  29504. */
  29505. void layout (int maximumWidth,
  29506. const Justification& justification,
  29507. const bool attemptToBalanceLineLengths) throw();
  29508. /** Returns the overall width of the entire text layout. */
  29509. int getWidth() const throw();
  29510. /** Returns the overall height of the entire text layout. */
  29511. int getHeight() const throw();
  29512. /** Returns the total number of lines of text. */
  29513. int getNumLines() const throw() { return totalLines; }
  29514. /** Returns the width of a particular line of text.
  29515. @param lineNumber the line, from 0 to (getNumLines() - 1)
  29516. */
  29517. int getLineWidth (const int lineNumber) const throw();
  29518. /** Renders the text at a specified position using a graphics context.
  29519. */
  29520. void draw (Graphics& g,
  29521. const int topLeftX,
  29522. const int topLeftY) const throw();
  29523. /** Renders the text within a specified rectangle using a graphics context.
  29524. The justification flags dictate how the block of text should be positioned
  29525. within the rectangle.
  29526. */
  29527. void drawWithin (Graphics& g,
  29528. int x, int y, int w, int h,
  29529. const Justification& layoutFlags) const throw();
  29530. juce_UseDebuggingNewOperator
  29531. private:
  29532. VoidArray tokens;
  29533. int totalLines;
  29534. };
  29535. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  29536. /********* End of inlined file: juce_TextLayout.h *********/
  29537. #endif
  29538. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  29539. #endif
  29540. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29541. /********* Start of inlined file: juce_EdgeTable.h *********/
  29542. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29543. #define __JUCE_EDGETABLE_JUCEHEADER__
  29544. class Path;
  29545. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  29546. /**
  29547. A table of horizontal scan-line segments - used for rasterising Paths.
  29548. @see Path, Graphics
  29549. */
  29550. class JUCE_API EdgeTable
  29551. {
  29552. public:
  29553. /** Indicates the quality at which the edge table should be generated.
  29554. Higher values will have better quality anti-aliasing, but will take
  29555. longer to generate the edge table and to render it.
  29556. */
  29557. enum OversamplingLevel
  29558. {
  29559. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  29560. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  29561. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  29562. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  29563. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  29564. normal user-interface use. */
  29565. };
  29566. /** Creates an empty edge table ready to have paths added.
  29567. A table is created with a fixed vertical size, and only sections of paths
  29568. which lie within their range will be added to the table.
  29569. @param topY the lowest y co-ordinate that the table can contain
  29570. @param height the number of horizontal lines it can contain
  29571. @param verticalOversampling the amount of oversampling used for anti-aliasing
  29572. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  29573. worth changing this except for very special purposes
  29574. */
  29575. EdgeTable (const int topY,
  29576. const int height,
  29577. const OversamplingLevel verticalOversampling = Oversampling_4times,
  29578. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  29579. /** Creates a copy of another edge table. */
  29580. EdgeTable (const EdgeTable& other) throw();
  29581. /** Copies from another edge table. */
  29582. const EdgeTable& operator= (const EdgeTable& other) throw();
  29583. /** Destructor. */
  29584. ~EdgeTable() throw();
  29585. /** Adds edges to the table for a path.
  29586. This will add horizontal lines to the edge table for any parts of the path
  29587. which lie within the vertical bounds for which this table was created.
  29588. @param path the path to add
  29589. @param transform an optional transform to apply to the path while it's
  29590. being added
  29591. */
  29592. void addPath (const Path& path,
  29593. const AffineTransform& transform) throw();
  29594. /** Reduces the amount of space the table has allocated.
  29595. This will shrink the table down to use as little memory as possible - useful for
  29596. read-only tables that get stored and re-used for rendering.
  29597. */
  29598. void optimiseTable() throw();
  29599. /** Iterates the lines in the table, for rendering.
  29600. This function will iterate each line in the table, and call a user-defined class
  29601. to render each pixel or continuous line of pixels that the table contains.
  29602. @param iterationCallback this templated class must contain the following methods:
  29603. @code
  29604. inline void setEdgeTableYPos (int y);
  29605. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  29606. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  29607. @endcode
  29608. (these don't necessarily have to be 'const', but it might help it go faster)
  29609. @param clipLeft the left-hand edge of the rectangle which should be iterated
  29610. @param clipTop the top edge of the rectangle which should be iterated
  29611. @param clipRight the right-hand edge of the rectangle which should be iterated
  29612. @param clipBottom the bottom edge of the rectangle which should be iterated
  29613. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  29614. */
  29615. template <class EdgeTableIterationCallback>
  29616. void iterate (EdgeTableIterationCallback& iterationCallback,
  29617. const int clipLeft,
  29618. int clipTop,
  29619. const int clipRight,
  29620. int clipBottom,
  29621. const int subPixelXOffset) const
  29622. {
  29623. if (clipTop < top)
  29624. clipTop = top;
  29625. if (clipBottom > top + height)
  29626. clipBottom = top + height;
  29627. const int* singleLine = table + lineStrideElements
  29628. * ((clipTop - top) << (int) oversampling);
  29629. int mergedLineAllocation = 128;
  29630. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  29631. int* mergedLine = (int*) temp.getData();
  29632. const int timesOverSampling = 1 << (int) oversampling;
  29633. for (int y = clipTop; y < clipBottom; ++y)
  29634. {
  29635. int numMergedPoints = 0;
  29636. // sort all the oversampled lines into a single merged line ready to draw..
  29637. for (int over = timesOverSampling; --over >= 0;)
  29638. {
  29639. const int* l = singleLine;
  29640. singleLine += lineStrideElements;
  29641. int num = *l;
  29642. jassert (num >= 0);
  29643. if (num > 0)
  29644. {
  29645. if (numMergedPoints + num >= mergedLineAllocation)
  29646. {
  29647. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  29648. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  29649. mergedLine = (int*) temp.getData();
  29650. }
  29651. while (--num >= 0)
  29652. {
  29653. const int x = *++l;
  29654. const int winding = *++l;
  29655. int n = numMergedPoints << 1;
  29656. while (n > 0)
  29657. {
  29658. const int cx = mergedLine [n - 2];
  29659. if (cx <= x)
  29660. break;
  29661. mergedLine [n] = cx;
  29662. --n;
  29663. mergedLine [n + 2] = mergedLine [n];
  29664. --n;
  29665. }
  29666. mergedLine [n] = x;
  29667. mergedLine [n + 1] = winding;
  29668. ++numMergedPoints;
  29669. }
  29670. }
  29671. }
  29672. if (--numMergedPoints > 0)
  29673. {
  29674. const int* line = mergedLine;
  29675. int x = subPixelXOffset + *line;
  29676. int level = *++line;
  29677. int levelAccumulator = 0;
  29678. iterationCallback.setEdgeTableYPos (y);
  29679. while (--numMergedPoints >= 0)
  29680. {
  29681. const int endX = subPixelXOffset + *++line;
  29682. jassert (endX >= x);
  29683. const int absLevel = abs (level);
  29684. int endOfRun = (endX >> 8);
  29685. if (endOfRun == (x >> 8))
  29686. {
  29687. // small segment within the same pixel, so just save it for the next
  29688. // time round..
  29689. levelAccumulator += (endX - x) * absLevel;
  29690. }
  29691. else
  29692. {
  29693. // plot the fist pixel of this segment, including any accumulated
  29694. // levels from smaller segments that haven't been drawn yet
  29695. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  29696. levelAccumulator >>= 8;
  29697. if (levelAccumulator > 0xff)
  29698. levelAccumulator = 0xff;
  29699. x >>= 8;
  29700. if (x >= clipRight)
  29701. {
  29702. levelAccumulator = 0;
  29703. break;
  29704. }
  29705. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  29706. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29707. if (++x >= clipRight)
  29708. {
  29709. levelAccumulator = 0;
  29710. break;
  29711. }
  29712. // if there's a segment of solid pixels, do it all in one go..
  29713. if (absLevel > 0 && endOfRun > x)
  29714. {
  29715. if (x < clipLeft)
  29716. x = clipLeft;
  29717. if (endOfRun > clipRight)
  29718. endOfRun = clipRight;
  29719. const int numPix = endOfRun - x;
  29720. if (numPix > 0)
  29721. iterationCallback.handleEdgeTableLine (x, numPix,
  29722. jmin (absLevel, 0xff));
  29723. }
  29724. // save the bit at the end to be drawn next time round the loop.
  29725. levelAccumulator = (endX & 0xff) * absLevel;
  29726. }
  29727. level += *++line;
  29728. x = endX;
  29729. }
  29730. if (levelAccumulator > 0)
  29731. {
  29732. levelAccumulator >>= 8;
  29733. if (levelAccumulator > 0xff)
  29734. levelAccumulator = 0xff;
  29735. x >>= 8;
  29736. if (x >= clipLeft && x < clipRight)
  29737. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29738. }
  29739. }
  29740. }
  29741. }
  29742. juce_UseDebuggingNewOperator
  29743. private:
  29744. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  29745. int* table;
  29746. int top, height, maxEdgesPerLine, lineStrideElements;
  29747. OversamplingLevel oversampling;
  29748. // this will assume that the y co-ord is within bounds, and will avoid checking
  29749. // this for speed.
  29750. void addEdgePoint (const int x, const int y, const int winding) throw();
  29751. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  29752. };
  29753. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  29754. /********* End of inlined file: juce_EdgeTable.h *********/
  29755. #endif
  29756. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  29757. #endif
  29758. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29759. #endif
  29760. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29761. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29762. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29763. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29764. /**
  29765. Interface class for graphics context objects, used internally by the Graphics class.
  29766. Users are not supposed to create instances of this class directly - do your drawing
  29767. via the Graphics object instead.
  29768. It's a base class for different types of graphics context, that may perform software-based
  29769. or OS-accelerated rendering.
  29770. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  29771. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  29772. context.
  29773. */
  29774. class JUCE_API LowLevelGraphicsContext
  29775. {
  29776. protected:
  29777. LowLevelGraphicsContext();
  29778. public:
  29779. virtual ~LowLevelGraphicsContext();
  29780. /** Returns true if this device is vector-based, e.g. a printer. */
  29781. virtual bool isVectorDevice() const = 0;
  29782. /** Moves the origin to a new position.
  29783. The co-ords are relative to the current origin, and indicate the new position
  29784. of (0, 0).
  29785. */
  29786. virtual void setOrigin (int x, int y) = 0;
  29787. /** Cliping co-ords are relative to the origin. */
  29788. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  29789. /** Cliping co-ords are relative to the origin. */
  29790. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  29791. /** Cliping co-ords are relative to the origin. */
  29792. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  29793. virtual void saveState() = 0;
  29794. virtual void restoreState() = 0;
  29795. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  29796. virtual const Rectangle getClipBounds() const = 0;
  29797. virtual bool isClipEmpty() const = 0;
  29798. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  29799. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  29800. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  29801. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  29802. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29803. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  29804. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  29805. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  29806. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29807. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  29808. virtual void blendImage (const Image& sourceImage,
  29809. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29810. float alpha) = 0;
  29811. virtual void blendImageRescaling (const Image& sourceImage,
  29812. int destX, int destY, int destW, int destH,
  29813. int sourceX, int sourceY, int sourceW, int sourceH,
  29814. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29815. virtual void blendImageWarping (const Image& sourceImage,
  29816. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29817. const AffineTransform& transform,
  29818. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29819. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  29820. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  29821. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29822. };
  29823. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29824. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29825. #endif
  29826. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29827. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29828. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29829. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29830. /**
  29831. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29832. into a PostScript document.
  29833. */
  29834. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29835. {
  29836. public:
  29837. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29838. const String& documentTitle,
  29839. const int totalWidth,
  29840. const int totalHeight);
  29841. ~LowLevelGraphicsPostScriptRenderer();
  29842. bool isVectorDevice() const;
  29843. void setOrigin (int x, int y);
  29844. bool reduceClipRegion (int x, int y, int w, int h);
  29845. bool reduceClipRegion (const RectangleList& clipRegion);
  29846. void excludeClipRegion (int x, int y, int w, int h);
  29847. void saveState();
  29848. void restoreState();
  29849. bool clipRegionIntersects (int x, int y, int w, int h);
  29850. const Rectangle getClipBounds() const;
  29851. bool isClipEmpty() const;
  29852. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29853. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29854. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29855. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29856. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29857. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29858. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29859. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29860. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29861. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29862. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29863. int sourceX, int sourceY, float alpha);
  29864. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29865. int sourceX, int sourceY, int sourceW, int sourceH,
  29866. float alpha, const Graphics::ResamplingQuality quality);
  29867. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29868. const AffineTransform& transform,
  29869. float alpha, const Graphics::ResamplingQuality quality);
  29870. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29871. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29872. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29873. juce_UseDebuggingNewOperator
  29874. protected:
  29875. OutputStream& out;
  29876. RectangleList* clip;
  29877. int totalWidth, totalHeight, xOffset, yOffset;
  29878. bool needToClip;
  29879. Colour lastColour;
  29880. struct SavedState
  29881. {
  29882. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29883. ~SavedState();
  29884. RectangleList* clip;
  29885. const int xOffset, yOffset;
  29886. private:
  29887. SavedState (const SavedState&);
  29888. const SavedState& operator= (const SavedState&);
  29889. };
  29890. OwnedArray <SavedState> stateStack;
  29891. void writeClip();
  29892. void writeColour (const Colour& colour);
  29893. void writePath (const Path& path) const;
  29894. void writeXY (const float x, const float y) const;
  29895. void writeTransform (const AffineTransform& trans) const;
  29896. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29897. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29898. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29899. };
  29900. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29901. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29902. #endif
  29903. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29904. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29905. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29906. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29907. /**
  29908. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29909. its rendering in memory.
  29910. User code is not supposed to create instances of this class directly - do all your
  29911. rendering via the Graphics class instead.
  29912. */
  29913. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29914. {
  29915. public:
  29916. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29917. ~LowLevelGraphicsSoftwareRenderer();
  29918. bool isVectorDevice() const;
  29919. void setOrigin (int x, int y);
  29920. bool reduceClipRegion (int x, int y, int w, int h);
  29921. bool reduceClipRegion (const RectangleList& clipRegion);
  29922. void excludeClipRegion (int x, int y, int w, int h);
  29923. void saveState();
  29924. void restoreState();
  29925. bool clipRegionIntersects (int x, int y, int w, int h);
  29926. const Rectangle getClipBounds() const;
  29927. bool isClipEmpty() const;
  29928. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29929. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29930. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29931. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29932. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29933. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29934. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29935. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29936. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29937. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29938. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29939. int sourceX, int sourceY, float alpha);
  29940. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29941. int sourceX, int sourceY, int sourceW, int sourceH,
  29942. float alpha, const Graphics::ResamplingQuality quality);
  29943. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29944. const AffineTransform& transform,
  29945. float alpha, const Graphics::ResamplingQuality quality);
  29946. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29947. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29948. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29949. RectangleList* getRawClipRegion() throw() { return clip; }
  29950. juce_UseDebuggingNewOperator
  29951. protected:
  29952. Image& image;
  29953. RectangleList* clip;
  29954. int xOffset, yOffset;
  29955. struct SavedState
  29956. {
  29957. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29958. ~SavedState();
  29959. RectangleList* clip;
  29960. const int xOffset, yOffset;
  29961. private:
  29962. SavedState (const SavedState&);
  29963. const SavedState& operator= (const SavedState&);
  29964. };
  29965. OwnedArray <SavedState> stateStack;
  29966. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29967. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29968. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29969. const Path& path, const AffineTransform& transform,
  29970. int& x, int& y, int& w, int& h) const;
  29971. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29972. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29973. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29974. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29975. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29976. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29977. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29978. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29979. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29980. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29981. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29982. float alpha);
  29983. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29984. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29985. const AffineTransform& transform,
  29986. float alpha, const Graphics::ResamplingQuality quality);
  29987. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29988. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29989. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29990. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29991. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29992. };
  29993. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29994. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29995. #endif
  29996. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29997. #endif
  29998. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  29999. #endif
  30000. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  30001. #endif
  30002. #ifndef __JUCE_LINE_JUCEHEADER__
  30003. #endif
  30004. #ifndef __JUCE_PATH_JUCEHEADER__
  30005. #endif
  30006. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  30007. /********* Start of inlined file: juce_PathIterator.h *********/
  30008. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  30009. #define __JUCE_PATHITERATOR_JUCEHEADER__
  30010. /**
  30011. Flattens a Path object into a series of straight-line sections.
  30012. Use one of these to iterate through a Path object, and it will convert
  30013. all the curves into line sections so it's easy to render or perform
  30014. geometric operations on.
  30015. @see Path
  30016. */
  30017. class JUCE_API PathFlatteningIterator
  30018. {
  30019. public:
  30020. /** Creates a PathFlatteningIterator.
  30021. After creation, use the next() method to initialise the fields in the
  30022. object with the first line's position.
  30023. @param path the path to iterate along
  30024. @param transform a transform to apply to each point in the path being iterated
  30025. @param tolerence the amount by which the curves are allowed to deviate from the
  30026. lines into which they are being broken down - a higher tolerence
  30027. is a bit faster, but less smooth.
  30028. */
  30029. PathFlatteningIterator (const Path& path,
  30030. const AffineTransform& transform = AffineTransform::identity,
  30031. float tolerence = 9.0f) throw();
  30032. /** Destructor. */
  30033. ~PathFlatteningIterator() throw();
  30034. /** Fetches the next line segment from the path.
  30035. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  30036. so that they describe the new line segment.
  30037. @returns false when there are no more lines to fetch.
  30038. */
  30039. bool next() throw();
  30040. /** The x position of the start of the current line segment. */
  30041. float x1;
  30042. /** The y position of the start of the current line segment. */
  30043. float y1;
  30044. /** The x position of the end of the current line segment. */
  30045. float x2;
  30046. /** The y position of the end of the current line segment. */
  30047. float y2;
  30048. /** Indicates whether the current line segment is closing a sub-path.
  30049. If the current line is the one that connects the end of a sub-path
  30050. back to the start again, this will be true.
  30051. */
  30052. bool closesSubPath;
  30053. /** The index of the current line within the current sub-path.
  30054. E.g. you can use this to see whether the line is the first one in the
  30055. subpath by seeing if it's 0.
  30056. */
  30057. int subPathIndex;
  30058. /** Returns true if the current segment is the last in the current sub-path. */
  30059. bool isLastInSubpath() const throw() { return stackPos == stackBase
  30060. && (index >= path.numElements
  30061. || points [index] == Path::moveMarker); }
  30062. juce_UseDebuggingNewOperator
  30063. private:
  30064. const Path& path;
  30065. const AffineTransform transform;
  30066. float* points;
  30067. float tolerence, subPathCloseX, subPathCloseY;
  30068. bool isIdentityTransform;
  30069. float* stackBase;
  30070. float* stackPos;
  30071. int index, stackSize;
  30072. PathFlatteningIterator (const PathFlatteningIterator&);
  30073. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  30074. };
  30075. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  30076. /********* End of inlined file: juce_PathIterator.h *********/
  30077. #endif
  30078. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  30079. #endif
  30080. #ifndef __JUCE_POINT_JUCEHEADER__
  30081. #endif
  30082. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30083. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  30084. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30085. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30086. /**
  30087. A rectangle whose co-ordinates can be defined in terms of absolute or
  30088. proportional distances.
  30089. Designed mainly for storing component positions, this gives you a lot of
  30090. control over how each co-ordinate is stored, either as an absolute position,
  30091. or as a proportion of the size of a parent rectangle.
  30092. It also allows you to define the anchor points by which the rectangle is
  30093. positioned, so for example you could specify that the top right of the
  30094. rectangle should be an absolute distance from its parent's bottom-right corner.
  30095. This object can be stored as a string, which takes the form "x y w h", including
  30096. symbols like '%' and letters to indicate the anchor point. See its toString()
  30097. method for more info.
  30098. Example usage:
  30099. @code
  30100. class MyComponent
  30101. {
  30102. void resized()
  30103. {
  30104. // this will set the child component's x to be 20% of our width, its y
  30105. // to be 30, its width to be 150, and its height to be 50% of our
  30106. // height..
  30107. const PositionedRectangle pos1 ("20% 30 150 50%");
  30108. pos1.applyToComponent (*myChildComponent1);
  30109. // this will inset the child component with a gap of 10 pixels
  30110. // around each of its edges..
  30111. const PositionedRectangle pos2 ("10 10 20M 20M");
  30112. pos2.applyToComponent (*myChildComponent2);
  30113. }
  30114. };
  30115. @endcode
  30116. */
  30117. class JUCE_API PositionedRectangle
  30118. {
  30119. public:
  30120. /** Creates an empty rectangle with all co-ordinates set to zero.
  30121. The default anchor point is top-left; the default
  30122. */
  30123. PositionedRectangle() throw();
  30124. /** Initialises a PositionedRectangle from a saved string version.
  30125. The string must be in the format generated by toString().
  30126. */
  30127. PositionedRectangle (const String& stringVersion) throw();
  30128. /** Creates a copy of another PositionedRectangle. */
  30129. PositionedRectangle (const PositionedRectangle& other) throw();
  30130. /** Copies another PositionedRectangle. */
  30131. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  30132. /** Destructor. */
  30133. ~PositionedRectangle() throw();
  30134. /** Returns a string version of this position, from which it can later be
  30135. re-generated.
  30136. The format is four co-ordinates, "x y w h".
  30137. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  30138. - If a co-ordinate is proportional to its parent's width or height, it is stored
  30139. as a percentage, e.g. "80%".
  30140. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  30141. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  30142. the parent's right-hand edge.
  30143. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  30144. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  30145. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  30146. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  30147. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  30148. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  30149. has "c" appended to it. So "-50Rc" would mean that this component's
  30150. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  30151. this component's centre should be placed 40% across the parent's width.
  30152. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  30153. the number has "M" appended to it.
  30154. To reload a stored string, use the constructor that takes a string parameter.
  30155. */
  30156. const String toString() const throw();
  30157. /** Calculates the absolute position, given the size of the space that
  30158. it should go in.
  30159. This will work out any proportional distances and sizes relative to the
  30160. target rectangle, and will return the absolute position.
  30161. @see applyToComponent
  30162. */
  30163. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  30164. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  30165. */
  30166. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  30167. double& x,
  30168. double& y,
  30169. double& width,
  30170. double& height) const throw();
  30171. /** This sets the bounds of the given component to this position.
  30172. This is equivalent to writing:
  30173. @code
  30174. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  30175. @endcode
  30176. @see getRectangle, updateFromComponent
  30177. */
  30178. void applyToComponent (Component& comp) const throw();
  30179. /** Updates this object's co-ordinates to match the given rectangle.
  30180. This will set all co-ordinates based on the given rectangle, re-calculating
  30181. any proportional distances, and using the current anchor points.
  30182. So for example if the x co-ordinate mode is currently proportional, this will
  30183. re-calculate x based on the rectangle's relative position within the target
  30184. rectangle's width.
  30185. If the target rectangle's width or height are zero then it may not be possible
  30186. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  30187. will not be changed.
  30188. */
  30189. void updateFrom (const Rectangle& newPosition,
  30190. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30191. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  30192. */
  30193. void updateFromDouble (const double x, const double y,
  30194. const double width, const double height,
  30195. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30196. /** Updates this object's co-ordinates to match the bounds of this component.
  30197. This is equivalent to calling updateFrom() with the component's bounds and
  30198. it parent size.
  30199. If the component doesn't currently have a parent, then proportional co-ordinates
  30200. might not be updated because it would need to know the parent's size to do the
  30201. maths for this.
  30202. */
  30203. void updateFromComponent (const Component& comp) throw();
  30204. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  30205. enum AnchorPoint
  30206. {
  30207. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  30208. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  30209. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  30210. };
  30211. /** Specifies how an x or y co-ordinate should be interpreted. */
  30212. enum PositionMode
  30213. {
  30214. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  30215. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  30216. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  30217. 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. */
  30218. };
  30219. /** Specifies how the width or height should be interpreted. */
  30220. enum SizeMode
  30221. {
  30222. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  30223. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  30224. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  30225. };
  30226. /** Sets all options for all co-ordinates.
  30227. This requires a reference rectangle to be specified, because if you're changing any
  30228. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  30229. the co-ordinates, and will need to know the parent size so it can calculate this.
  30230. */
  30231. void setModes (const AnchorPoint xAnchorMode,
  30232. const PositionMode xPositionMode,
  30233. const AnchorPoint yAnchorMode,
  30234. const PositionMode yPositionMode,
  30235. const SizeMode widthMode,
  30236. const SizeMode heightMode,
  30237. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30238. /** Returns the anchoring mode for the x co-ordinate.
  30239. To change any of the modes, use setModes().
  30240. */
  30241. AnchorPoint getAnchorPointX() const throw();
  30242. /** Returns the positioning mode for the x co-ordinate.
  30243. To change any of the modes, use setModes().
  30244. */
  30245. PositionMode getPositionModeX() const throw();
  30246. /** Returns the raw x co-ordinate.
  30247. If the x position mode is absolute, then this will be the absolute value. If it's
  30248. proportional, then this will be a fractional proportion, where 1.0 means the full
  30249. width of the parent space.
  30250. */
  30251. double getX() const throw() { return x; }
  30252. /** Sets the raw value of the x co-ordinate.
  30253. See getX() for the meaning of this value.
  30254. */
  30255. void setX (const double newX) throw() { x = newX; }
  30256. /** Returns the anchoring mode for the y co-ordinate.
  30257. To change any of the modes, use setModes().
  30258. */
  30259. AnchorPoint getAnchorPointY() const throw();
  30260. /** Returns the positioning mode for the y co-ordinate.
  30261. To change any of the modes, use setModes().
  30262. */
  30263. PositionMode getPositionModeY() const throw();
  30264. /** Returns the raw y co-ordinate.
  30265. If the y position mode is absolute, then this will be the absolute value. If it's
  30266. proportional, then this will be a fractional proportion, where 1.0 means the full
  30267. height of the parent space.
  30268. */
  30269. double getY() const throw() { return y; }
  30270. /** Sets the raw value of the y co-ordinate.
  30271. See getY() for the meaning of this value.
  30272. */
  30273. void setY (const double newY) throw() { y = newY; }
  30274. /** Returns the mode used to calculate the width.
  30275. To change any of the modes, use setModes().
  30276. */
  30277. SizeMode getWidthMode() const throw();
  30278. /** Returns the raw width value.
  30279. If the width mode is absolute, then this will be the absolute value. If the mode is
  30280. proportional, then this will be a fractional proportion, where 1.0 means the full
  30281. width of the parent space.
  30282. */
  30283. double getWidth() const throw() { return w; }
  30284. /** Sets the raw width value.
  30285. See getWidth() for the details about what this value means.
  30286. */
  30287. void setWidth (const double newWidth) throw() { w = newWidth; }
  30288. /** Returns the mode used to calculate the height.
  30289. To change any of the modes, use setModes().
  30290. */
  30291. SizeMode getHeightMode() const throw();
  30292. /** Returns the raw height value.
  30293. If the height mode is absolute, then this will be the absolute value. If the mode is
  30294. proportional, then this will be a fractional proportion, where 1.0 means the full
  30295. height of the parent space.
  30296. */
  30297. double getHeight() const throw() { return h; }
  30298. /** Sets the raw height value.
  30299. See getHeight() for the details about what this value means.
  30300. */
  30301. void setHeight (const double newHeight) throw() { h = newHeight; }
  30302. /** If the size and position are constance, and wouldn't be affected by changes
  30303. in the parent's size, then this will return true.
  30304. */
  30305. bool isPositionAbsolute() const throw();
  30306. /** Compares two objects. */
  30307. const bool operator== (const PositionedRectangle& other) const throw();
  30308. /** Compares two objects. */
  30309. const bool operator!= (const PositionedRectangle& other) const throw();
  30310. juce_UseDebuggingNewOperator
  30311. private:
  30312. double x, y, w, h;
  30313. uint8 xMode, yMode, wMode, hMode;
  30314. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  30315. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  30316. void decodePosString (const String& s, uint8& mode, double& value) throw();
  30317. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  30318. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  30319. const uint8 xMode, const uint8 wMode,
  30320. const int parentPos, const int parentSize) const throw();
  30321. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  30322. const uint8 xMode, const uint8 wMode,
  30323. const int parentPos, const int parentSize) const throw();
  30324. };
  30325. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30326. /********* End of inlined file: juce_PositionedRectangle.h *********/
  30327. #endif
  30328. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  30329. #endif
  30330. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  30331. #endif
  30332. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  30333. /********* Start of inlined file: juce_CameraDevice.h *********/
  30334. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  30335. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  30336. #if JUCE_USE_CAMERA
  30337. /**
  30338. Receives callbacks with images from a CameraDevice.
  30339. @see CameraDevice::addListener
  30340. */
  30341. class CameraImageListener
  30342. {
  30343. public:
  30344. CameraImageListener() {}
  30345. virtual ~CameraImageListener() {}
  30346. /** This method is called when a new image arrives.
  30347. This may be called by any thread, so be careful about thread-safety,
  30348. and make sure that you process the data as quickly as possible to
  30349. avoid glitching!
  30350. */
  30351. virtual void imageReceived (Image& image) = 0;
  30352. };
  30353. /**
  30354. Controls any camera capture devices that might be available.
  30355. Use getAvailableDevices() to list the devices that are attached to the
  30356. system, then call openDevice to open one for use. Once you have a CameraDevice
  30357. object, you can get a viewer component from it, and use its methods to
  30358. stream to a file or capture still-frames.
  30359. */
  30360. class JUCE_API CameraDevice
  30361. {
  30362. public:
  30363. /** Destructor. */
  30364. virtual ~CameraDevice();
  30365. /** Returns a list of the available cameras on this machine.
  30366. You can open one of these devices by calling openDevice().
  30367. */
  30368. static const StringArray getAvailableDevices();
  30369. /** Opens a camera device.
  30370. The index parameter indicates which of the items returned by getAvailableDevices()
  30371. to open.
  30372. The size constraints allow the method to choose between different resolutions if
  30373. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  30374. then these will be ignored.
  30375. */
  30376. static CameraDevice* openDevice (int deviceIndex,
  30377. int minWidth = 128, int minHeight = 64,
  30378. int maxWidth = 1024, int maxHeight = 768);
  30379. /** Returns the name of this device */
  30380. const String getName() const throw() { return name; }
  30381. /** Creates a component that can be used to display a preview of the
  30382. video from this camera.
  30383. */
  30384. Component* createViewerComponent();
  30385. /** Starts recording video to the specified file.
  30386. You should use getFileExtension() to find out the correct extension to
  30387. use for your filename.
  30388. If the file exists, it will be deleted before the recording starts.
  30389. This method may not start recording instantly, so if you need to know the
  30390. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  30391. after the recording has finished.
  30392. */
  30393. void startRecordingToFile (const File& file);
  30394. /** Stops recording, after a call to startRecordingToFile().
  30395. */
  30396. void stopRecording();
  30397. /** Returns the file extension that should be used for the files
  30398. that you pass to startRecordingToFile().
  30399. This may be platform-specific, e.g. ".mov" or ".avi".
  30400. */
  30401. static const String getFileExtension();
  30402. /** After calling stopRecording(), this method can be called to return the timestamp
  30403. of the first frame that was written to the file.
  30404. */
  30405. const Time getTimeOfFirstRecordedFrame() const;
  30406. /** Adds a listener to receive images from the camera.
  30407. Be very careful not to delete the listener without first removing it by calling
  30408. removeListener().
  30409. */
  30410. void addListener (CameraImageListener* listenerToAdd);
  30411. /** Removes a listener that was previously added with addListener().
  30412. */
  30413. void removeListener (CameraImageListener* listenerToRemove);
  30414. juce_UseDebuggingNewOperator
  30415. protected:
  30416. /** @internal */
  30417. CameraDevice (const String& name, int index);
  30418. private:
  30419. void* internal;
  30420. bool isRecording;
  30421. String name;
  30422. CameraDevice (const CameraDevice&);
  30423. const CameraDevice& operator= (const CameraDevice&);
  30424. };
  30425. #endif
  30426. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  30427. /********* End of inlined file: juce_CameraDevice.h *********/
  30428. #endif
  30429. #ifndef __JUCE_IMAGE_JUCEHEADER__
  30430. #endif
  30431. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30432. /********* Start of inlined file: juce_ImageCache.h *********/
  30433. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30434. #define __JUCE_IMAGECACHE_JUCEHEADER__
  30435. /**
  30436. A global cache of images that have been loaded from files or memory.
  30437. If you're loading an image and may need to use the image in more than one
  30438. place, this is used to allow the same image to be shared rather than loading
  30439. multiple copies into memory.
  30440. Another advantage is that after images are released, they will be kept in
  30441. memory for a few seconds before it is actually deleted, so if you're repeatedly
  30442. loading/deleting the same image, it'll reduce the chances of having to reload it
  30443. each time.
  30444. @see Image, ImageFileFormat
  30445. */
  30446. class JUCE_API ImageCache : private DeletedAtShutdown,
  30447. private Timer
  30448. {
  30449. public:
  30450. /** Loads an image from a file, (or just returns the image if it's already cached).
  30451. If the cache already contains an image that was loaded from this file,
  30452. that image will be returned. Otherwise, this method will try to load the
  30453. file, add it to the cache, and return it.
  30454. It's very important not to delete the image that is returned - instead use
  30455. the ImageCache::release() method.
  30456. Also, remember that the image returned is shared, so drawing into it might
  30457. affect other things that are using it!
  30458. @param file the file to try to load
  30459. @returns the image, or null if it there was an error loading it
  30460. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30461. */
  30462. static Image* getFromFile (const File& file);
  30463. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  30464. If the cache already contains an image that was loaded from this block of memory,
  30465. that image will be returned. Otherwise, this method will try to load the
  30466. file, add it to the cache, and return it.
  30467. It's very important not to delete the image that is returned - instead use
  30468. the ImageCache::release() method.
  30469. Also, remember that the image returned is shared, so drawing into it might
  30470. affect other things that are using it!
  30471. @param imageData the block of memory containing the image data
  30472. @param dataSize the data size in bytes
  30473. @returns the image, or null if it there was an error loading it
  30474. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30475. */
  30476. static Image* getFromMemory (const void* imageData,
  30477. const int dataSize);
  30478. /** Releases an image that was previously created by the ImageCache.
  30479. If an image has been returned by the getFromFile() or getFromMemory() methods,
  30480. it mustn't be deleted directly, but should be released with this method
  30481. instead.
  30482. @see getFromFile, getFromMemory
  30483. */
  30484. static void release (Image* const imageToRelease);
  30485. /** Checks whether an image is in the cache or not.
  30486. @returns true if the image is currently in the cache
  30487. */
  30488. static bool isImageInCache (Image* const imageToLookFor);
  30489. /** Increments the reference-count for a cached image.
  30490. If the image isn't in the cache, this method won't do anything.
  30491. */
  30492. static void incReferenceCount (Image* const image);
  30493. /** Checks the cache for an image with a particular hashcode.
  30494. If there's an image in the cache with this hashcode, it will be returned,
  30495. otherwise it will return zero.
  30496. If an image is returned, it must be released with the release() method
  30497. when no longer needed, to maintain the correct reference counts.
  30498. @param hashCode the hash code that would have been associated with the
  30499. image by addImageToCache()
  30500. @see addImageToCache
  30501. */
  30502. static Image* getFromHashCode (const int64 hashCode);
  30503. /** Adds an image to the cache with a user-defined hash-code.
  30504. After calling this, responsibilty for deleting the image will be taken
  30505. by the ImageCache.
  30506. The image will be initially be given a reference count of 1, so call
  30507. the release() method to delete it.
  30508. @param image the image to add
  30509. @param hashCode the hash-code to associate with it
  30510. @see getFromHashCode
  30511. */
  30512. static void addImageToCache (Image* const image,
  30513. const int64 hashCode);
  30514. /** Changes the amount of time before an unused image will be removed from the cache.
  30515. By default this is about 5 seconds.
  30516. */
  30517. static void setCacheTimeout (const int millisecs);
  30518. juce_UseDebuggingNewOperator
  30519. private:
  30520. CriticalSection lock;
  30521. VoidArray images;
  30522. ImageCache() throw();
  30523. ImageCache (const ImageCache&);
  30524. const ImageCache& operator= (const ImageCache&);
  30525. ~ImageCache();
  30526. void timerCallback();
  30527. };
  30528. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  30529. /********* End of inlined file: juce_ImageCache.h *********/
  30530. #endif
  30531. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30532. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  30533. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30534. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30535. /**
  30536. Represents a filter kernel to use in convoluting an image.
  30537. @see Image::applyConvolution
  30538. */
  30539. class JUCE_API ImageConvolutionKernel
  30540. {
  30541. public:
  30542. /** Creates an empty convulution kernel.
  30543. @param size the length of each dimension of the kernel, so e.g. if the size
  30544. is 5, it will create a 5x5 kernel
  30545. */
  30546. ImageConvolutionKernel (const int size) throw();
  30547. /** Destructor. */
  30548. ~ImageConvolutionKernel() throw();
  30549. /** Resets all values in the kernel to zero.
  30550. */
  30551. void clear() throw();
  30552. /** Sets the value of a specific cell in the kernel.
  30553. The x and y parameters must be in the range 0 < x < getKernelSize().
  30554. @see setOverallSum
  30555. */
  30556. void setKernelValue (const int x,
  30557. const int y,
  30558. const float value) throw();
  30559. /** Rescales all values in the kernel to make the total add up to a fixed value.
  30560. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  30561. */
  30562. void setOverallSum (const float desiredTotalSum) throw();
  30563. /** Multiplies all values in the kernel by a value. */
  30564. void rescaleAllValues (const float multiplier) throw();
  30565. /** Intialises the kernel for a gaussian blur.
  30566. @param blurRadius this may be larger or smaller than the kernel's actual
  30567. size but this will obviously be wasteful or clip at the
  30568. edges. Ideally the kernel should be just larger than
  30569. (blurRadius * 2).
  30570. */
  30571. void createGaussianBlur (const float blurRadius) throw();
  30572. /** Returns the size of the kernel.
  30573. E.g. if it's a 3x3 kernel, this returns 3.
  30574. */
  30575. int getKernelSize() const throw() { return size; }
  30576. /** Returns a 2-dimensional array of the kernel's values.
  30577. The size of each dimension of the array will be getKernelSize().
  30578. */
  30579. float** getValues() const throw() { return values; }
  30580. /** Applies the kernel to an image.
  30581. @param destImage the image that will receive the resultant convoluted pixels.
  30582. @param sourceImage an optional source image to read from - if this is 0, then the
  30583. destination image will be used as the source. If an image is
  30584. specified, it must be exactly the same size and type as the destination
  30585. image.
  30586. @param x the region of the image to apply the filter to
  30587. @param y the region of the image to apply the filter to
  30588. @param width the region of the image to apply the filter to
  30589. @param height the region of the image to apply the filter to
  30590. */
  30591. void applyToImage (Image& destImage,
  30592. const Image* sourceImage,
  30593. int x,
  30594. int y,
  30595. int width,
  30596. int height) const;
  30597. juce_UseDebuggingNewOperator
  30598. private:
  30599. float** values;
  30600. int size;
  30601. // no reason not to implement these one day..
  30602. ImageConvolutionKernel (const ImageConvolutionKernel&);
  30603. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  30604. };
  30605. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30606. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  30607. #endif
  30608. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30609. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  30610. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30611. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30612. /**
  30613. Base-class for codecs that can read and write image file formats such
  30614. as PNG, JPEG, etc.
  30615. This class also contains static methods to make it easy to load images
  30616. from files, streams or from memory.
  30617. @see Image, ImageCache
  30618. */
  30619. class JUCE_API ImageFileFormat
  30620. {
  30621. protected:
  30622. /** Creates an ImageFormat. */
  30623. ImageFileFormat() throw() {}
  30624. public:
  30625. /** Destructor. */
  30626. virtual ~ImageFileFormat() throw() {}
  30627. /** Returns a description of this file format.
  30628. E.g. "JPEG", "PNG"
  30629. */
  30630. virtual const String getFormatName() = 0;
  30631. /** Returns true if the given stream seems to contain data that this format
  30632. understands.
  30633. The format class should only read the first few bytes of the stream and sniff
  30634. for header bytes that it understands.
  30635. @see decodeImage
  30636. */
  30637. virtual bool canUnderstand (InputStream& input) = 0;
  30638. /** Tries to decode and return an image from the given stream.
  30639. This will be called for an image format after calling its canUnderStand() method
  30640. to see if it can handle the stream.
  30641. @param input the stream to read the data from. The stream will be positioned
  30642. at the start of the image data (but this may not necessarily
  30643. be position 0)
  30644. @returns the image that was decoded, or 0 if it fails. It's the
  30645. caller's responsibility to delete this image when no longer needed.
  30646. @see loadFrom
  30647. */
  30648. virtual Image* decodeImage (InputStream& input) = 0;
  30649. /** Attempts to write an image to a stream.
  30650. To specify extra information like encoding quality, there will be appropriate parameters
  30651. in the subclasses of the specific file types.
  30652. @returns true if it nothing went wrong.
  30653. */
  30654. virtual bool writeImageToStream (const Image& sourceImage,
  30655. OutputStream& destStream) = 0;
  30656. /** Tries the built-in decoders to see if it can find one to read this stream.
  30657. There are currently built-in decoders for PNG, JPEG and GIF formats.
  30658. The object that is returned should not be deleted by the caller.
  30659. @see canUnderstand, decodeImage, loadFrom
  30660. */
  30661. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  30662. /** Tries to load an image from a stream.
  30663. This will use the findImageFormatForStream() method to locate a suitable
  30664. codec, and use that to load the image.
  30665. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30666. caller's responsibility to delete this image when no longer needed.
  30667. */
  30668. static Image* loadFrom (InputStream& input);
  30669. /** Tries to load an image from a file.
  30670. This will use the findImageFormatForStream() method to locate a suitable
  30671. codec, and use that to load the image.
  30672. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30673. caller's responsibility to delete this image when no longer needed.
  30674. */
  30675. static Image* loadFrom (const File& file);
  30676. /** Tries to load an image from a block of raw image data.
  30677. This will use the findImageFormatForStream() method to locate a suitable
  30678. codec, and use that to load the image.
  30679. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30680. caller's responsibility to delete this image when no longer needed.
  30681. */
  30682. static Image* loadFrom (const void* rawData,
  30683. const int numBytesOfData);
  30684. };
  30685. /**
  30686. A type of ImageFileFormat for reading and writing PNG files.
  30687. @see ImageFileFormat, JPEGImageFormat
  30688. */
  30689. class JUCE_API PNGImageFormat : public ImageFileFormat
  30690. {
  30691. public:
  30692. PNGImageFormat() throw();
  30693. ~PNGImageFormat() throw();
  30694. const String getFormatName();
  30695. bool canUnderstand (InputStream& input);
  30696. Image* decodeImage (InputStream& input);
  30697. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30698. };
  30699. /**
  30700. A type of ImageFileFormat for reading and writing JPEG files.
  30701. @see ImageFileFormat, PNGImageFormat
  30702. */
  30703. class JUCE_API JPEGImageFormat : public ImageFileFormat
  30704. {
  30705. public:
  30706. JPEGImageFormat() throw();
  30707. ~JPEGImageFormat() throw();
  30708. /** Specifies the quality to be used when writing a JPEG file.
  30709. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  30710. any negative value is "default" quality
  30711. */
  30712. void setQuality (const float newQuality);
  30713. const String getFormatName();
  30714. bool canUnderstand (InputStream& input);
  30715. Image* decodeImage (InputStream& input);
  30716. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30717. private:
  30718. float quality;
  30719. };
  30720. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30721. /********* End of inlined file: juce_ImageFileFormat.h *********/
  30722. #endif
  30723. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30724. /********* Start of inlined file: juce_DrawableText.h *********/
  30725. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  30726. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  30727. /********* Start of inlined file: juce_Drawable.h *********/
  30728. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30729. #define __JUCE_DRAWABLE_JUCEHEADER__
  30730. /**
  30731. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  30732. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30733. */
  30734. class JUCE_API Drawable
  30735. {
  30736. protected:
  30737. /** The base class can't be instantiated directly.
  30738. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30739. */
  30740. Drawable();
  30741. public:
  30742. /** Destructor. */
  30743. virtual ~Drawable();
  30744. /** Creates a deep copy of this Drawable object.
  30745. Use this to create a new copy of this and any sub-objects in the tree.
  30746. */
  30747. virtual Drawable* createCopy() const = 0;
  30748. /** Renders this Drawable object.
  30749. @see drawWithin
  30750. */
  30751. void draw (Graphics& g,
  30752. const AffineTransform& transform = AffineTransform::identity) const;
  30753. /** Renders the Drawable at a given offset within the Graphics context.
  30754. The co-ordinates passed-in are used to translate the object relative to its own
  30755. origin before drawing it - this is basically a quick way of saying:
  30756. @code
  30757. draw (g, AffineTransform::translation (x, y)).
  30758. @endcode
  30759. */
  30760. void drawAt (Graphics& g,
  30761. const float x,
  30762. const float y) const;
  30763. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  30764. changing its aspect-ratio.
  30765. The object can placed arbitrarily within the rectangle based on a Justification type,
  30766. and can either be made as big as possible, or just reduced to fit.
  30767. @param g the graphics context to render onto
  30768. @param destX top-left of the target rectangle to fit it into
  30769. @param destY top-left of the target rectangle to fit it into
  30770. @param destWidth size of the target rectangle to fit the image into
  30771. @param destHeight size of the target rectangle to fit the image into
  30772. @param placement defines the alignment and rescaling to use to fit
  30773. this object within the target rectangle.
  30774. */
  30775. void drawWithin (Graphics& g,
  30776. const int destX,
  30777. const int destY,
  30778. const int destWidth,
  30779. const int destHeight,
  30780. const RectanglePlacement& placement) const;
  30781. /** Holds the information needed when telling a drawable to render itself.
  30782. @see Drawable::draw
  30783. */
  30784. class RenderingContext
  30785. {
  30786. public:
  30787. RenderingContext (Graphics& g, const AffineTransform& transform, const float opacity) throw();
  30788. Graphics& g;
  30789. AffineTransform transform;
  30790. float opacity;
  30791. private:
  30792. const RenderingContext& operator= (const RenderingContext&);
  30793. };
  30794. /** Renders this Drawable object.
  30795. @see draw
  30796. */
  30797. virtual void render (const RenderingContext& context) const = 0;
  30798. /** Returns the smallest rectangle that can contain this Drawable object.
  30799. Co-ordinates are relative to the object's own origin.
  30800. */
  30801. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  30802. /** Returns true if the given point is somewhere inside this Drawable.
  30803. Co-ordinates are relative to the object's own origin.
  30804. */
  30805. virtual bool hitTest (float x, float y) const = 0;
  30806. /** Returns the name given to this drawable.
  30807. @see setName
  30808. */
  30809. const String& getName() const throw() { return name; }
  30810. /** Assigns a name to this drawable. */
  30811. void setName (const String& newName) throw() { name = newName; }
  30812. /** Tries to turn some kind of image file into a drawable.
  30813. The data could be an image that the ImageFileFormat class understands, or it
  30814. could be SVG.
  30815. */
  30816. static Drawable* createFromImageData (const void* data, const int numBytes);
  30817. /** Tries to turn a stream containing some kind of image data into a drawable.
  30818. The data could be an image that the ImageFileFormat class understands, or it
  30819. could be SVG.
  30820. */
  30821. static Drawable* createFromImageDataStream (InputStream& dataSource);
  30822. /** Tries to turn a file containing some kind of image data into a drawable.
  30823. The data could be an image that the ImageFileFormat class understands, or it
  30824. could be SVG.
  30825. */
  30826. static Drawable* createFromImageFile (const File& file);
  30827. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  30828. into a Drawable tree.
  30829. The object returned must be deleted by the caller. If something goes wrong
  30830. while parsing, it may return 0.
  30831. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  30832. implementation, but it can return the basic vector objects.
  30833. */
  30834. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30835. /**
  30836. */
  30837. static Drawable* readFromBinaryStream (InputStream& input);
  30838. /**
  30839. */
  30840. bool writeToBinaryStream (OutputStream& output) const;
  30841. /**
  30842. */
  30843. static Drawable* readFromXml (const XmlElement& xml);
  30844. /**
  30845. */
  30846. XmlElement* createXml() const;
  30847. /** @internal */
  30848. virtual bool readBinary (InputStream& input) = 0;
  30849. /** @internal */
  30850. virtual bool writeBinary (OutputStream& output) const = 0;
  30851. /** @internal */
  30852. virtual bool readXml (const XmlElement& xml) = 0;
  30853. /** @internal */
  30854. virtual void writeXml (XmlElement& xml) const = 0;
  30855. juce_UseDebuggingNewOperator
  30856. private:
  30857. Drawable (const Drawable&);
  30858. const Drawable& operator= (const Drawable&);
  30859. String name;
  30860. };
  30861. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30862. /********* End of inlined file: juce_Drawable.h *********/
  30863. /**
  30864. A drawable object which renders a line of text.
  30865. @see Drawable
  30866. */
  30867. class JUCE_API DrawableText : public Drawable
  30868. {
  30869. public:
  30870. /** Creates a DrawableText object. */
  30871. DrawableText();
  30872. /** Destructor. */
  30873. virtual ~DrawableText();
  30874. /** Sets the block of text to render */
  30875. void setText (const GlyphArrangement& newText);
  30876. /** Sets a single line of text to render.
  30877. This is a convenient method of adding a single line - for
  30878. more complex text, use the setText() that takes a
  30879. GlyphArrangement instead.
  30880. */
  30881. void setText (const String& newText, const Font& fontToUse);
  30882. /** Returns the text arrangement that was set with setText(). */
  30883. const GlyphArrangement& getText() const throw() { return text; }
  30884. /** Sets the colour of the text. */
  30885. void setColour (const Colour& newColour);
  30886. /** Returns the current text colour. */
  30887. const Colour& getColour() const throw() { return colour; }
  30888. /** @internal */
  30889. void render (const Drawable::RenderingContext& context) const;
  30890. /** @internal */
  30891. void getBounds (float& x, float& y, float& width, float& height) const;
  30892. /** @internal */
  30893. bool hitTest (float x, float y) const;
  30894. /** @internal */
  30895. Drawable* createCopy() const;
  30896. /** @internal */
  30897. bool readBinary (InputStream& input);
  30898. /** @internal */
  30899. bool writeBinary (OutputStream& output) const;
  30900. /** @internal */
  30901. bool readXml (const XmlElement& xml);
  30902. /** @internal */
  30903. void writeXml (XmlElement& xml) const;
  30904. juce_UseDebuggingNewOperator
  30905. private:
  30906. GlyphArrangement text;
  30907. Colour colour;
  30908. DrawableText (const DrawableText&);
  30909. const DrawableText& operator= (const DrawableText&);
  30910. };
  30911. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  30912. /********* End of inlined file: juce_DrawableText.h *********/
  30913. #endif
  30914. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30915. /********* Start of inlined file: juce_DrawablePath.h *********/
  30916. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  30917. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  30918. /**
  30919. A drawable object which renders a filled or outlined shape.
  30920. @see Drawable
  30921. */
  30922. class JUCE_API DrawablePath : public Drawable
  30923. {
  30924. public:
  30925. /** Creates a DrawablePath.
  30926. */
  30927. DrawablePath();
  30928. /** Destructor. */
  30929. virtual ~DrawablePath();
  30930. /** Changes the path that will be drawn.
  30931. @see setSolidFill, setOutline
  30932. */
  30933. void setPath (const Path& newPath);
  30934. /** Returns the current path. */
  30935. const Path& getPath() const throw() { return path; }
  30936. /** Sets a colour to fill the path with.
  30937. This colour is used to fill the path - if you don't want the path to be
  30938. filled (e.g. if you're just drawing an outline), set this colour to be
  30939. transparent.
  30940. @see setPath, setOutline
  30941. */
  30942. void setSolidFill (const Colour& newColour);
  30943. /** Sets a custom brush to use to fill the path.
  30944. @see setSolidFill
  30945. */
  30946. void setFillBrush (const Brush& newBrush);
  30947. /** Returns the brush currently being used to fill the shape. */
  30948. Brush* getCurrentBrush() const throw() { return fillBrush; }
  30949. /** Changes the properties of the outline that will be drawn around the path.
  30950. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  30951. colour passed-in here will be used for it.
  30952. @see setPath, setSolidFill
  30953. */
  30954. void setOutline (const float thickness,
  30955. const Colour& outlineColour);
  30956. /** Changes the properties of the outline that will be drawn around the path.
  30957. If the stroke type has 0 thickness, no outline will be drawn.
  30958. @see setPath, setSolidFill
  30959. */
  30960. void setOutline (const PathStrokeType& strokeType,
  30961. const Brush& strokeBrush);
  30962. /** Returns the current outline style. */
  30963. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  30964. /** Returns the brush currently being used to draw the outline. */
  30965. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  30966. /** @internal */
  30967. void render (const Drawable::RenderingContext& context) const;
  30968. /** @internal */
  30969. void getBounds (float& x, float& y, float& width, float& height) const;
  30970. /** @internal */
  30971. bool hitTest (float x, float y) const;
  30972. /** @internal */
  30973. Drawable* createCopy() const;
  30974. /** @internal */
  30975. bool readBinary (InputStream& input);
  30976. /** @internal */
  30977. bool writeBinary (OutputStream& output) const;
  30978. /** @internal */
  30979. bool readXml (const XmlElement& xml);
  30980. /** @internal */
  30981. void writeXml (XmlElement& xml) const;
  30982. juce_UseDebuggingNewOperator
  30983. private:
  30984. Path path, outline;
  30985. Brush* fillBrush;
  30986. Brush* strokeBrush;
  30987. PathStrokeType strokeType;
  30988. void updateOutline();
  30989. DrawablePath (const DrawablePath&);
  30990. const DrawablePath& operator= (const DrawablePath&);
  30991. };
  30992. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  30993. /********* End of inlined file: juce_DrawablePath.h *********/
  30994. #endif
  30995. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30996. /********* Start of inlined file: juce_DrawableComposite.h *********/
  30997. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30998. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30999. /**
  31000. A drawable object which acts as a container for a set of other Drawables.
  31001. @see Drawable
  31002. */
  31003. class JUCE_API DrawableComposite : public Drawable
  31004. {
  31005. public:
  31006. /** Creates a composite Drawable.
  31007. */
  31008. DrawableComposite();
  31009. /** Destructor. */
  31010. virtual ~DrawableComposite();
  31011. /** Adds a new sub-drawable to this one.
  31012. This passes in a Drawable pointer for this object to look after. To add a copy
  31013. of a drawable, use the form of this method that takes a Drawable reference instead.
  31014. @param drawable the object to add - this will be deleted automatically
  31015. when no longer needed, so the caller mustn't keep any
  31016. pointers to it.
  31017. @param transform the transform to apply to this drawable when it's being
  31018. drawn
  31019. @param index where to insert it in the list of drawables. 0 is the back,
  31020. -1 is the front, or any value from 0 and getNumDrawables()
  31021. can be used
  31022. @see removeDrawable
  31023. */
  31024. void insertDrawable (Drawable* drawable,
  31025. const AffineTransform& transform = AffineTransform::identity,
  31026. const int index = -1);
  31027. /** Adds a new sub-drawable to this one.
  31028. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  31029. for this object to look after, use the form of this method that takes a Drawable
  31030. pointer instead.
  31031. @param drawable the object to add - an internal copy will be made of this object
  31032. @param transform the transform to apply to this drawable when it's being
  31033. drawn
  31034. @param index where to insert it in the list of drawables. 0 is the back,
  31035. -1 is the front, or any value from 0 and getNumDrawables()
  31036. can be used
  31037. @see removeDrawable
  31038. */
  31039. void insertDrawable (const Drawable& drawable,
  31040. const AffineTransform& transform = AffineTransform::identity,
  31041. const int index = -1);
  31042. /** Deletes one of the Drawable objects.
  31043. @param index the index of the drawable to delete, between 0
  31044. and (getNumDrawables() - 1).
  31045. @param deleteDrawable if this is true, the drawable that is removed will also
  31046. be deleted. If false, it'll just be removed.
  31047. @see insertDrawable, getNumDrawables
  31048. */
  31049. void removeDrawable (const int index, const bool deleteDrawable = true);
  31050. /** Returns the number of drawables contained inside this one.
  31051. @see getDrawable
  31052. */
  31053. int getNumDrawables() const throw() { return drawables.size(); }
  31054. /** Returns one of the drawables that are contained in this one.
  31055. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  31056. to find it.
  31057. The pointer returned is managed by this object and will be deleted when no longer
  31058. needed, so be careful what you do with it.
  31059. @see getNumDrawables
  31060. */
  31061. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  31062. /** Returns the transform that applies to one of the drawables that are contained in this one.
  31063. The pointer returned is managed by this object and will be deleted when no longer
  31064. needed, so be careful what you do with it.
  31065. @see getNumDrawables
  31066. */
  31067. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  31068. /** Brings one of the Drawables to the front.
  31069. @param index the index of the drawable to move, between 0
  31070. and (getNumDrawables() - 1).
  31071. @see insertDrawable, getNumDrawables
  31072. */
  31073. void bringToFront (const int index);
  31074. /** @internal */
  31075. void render (const Drawable::RenderingContext& context) const;
  31076. /** @internal */
  31077. void getBounds (float& x, float& y, float& width, float& height) const;
  31078. /** @internal */
  31079. bool hitTest (float x, float y) const;
  31080. /** @internal */
  31081. Drawable* createCopy() const;
  31082. /** @internal */
  31083. bool readBinary (InputStream& input);
  31084. /** @internal */
  31085. bool writeBinary (OutputStream& output) const;
  31086. /** @internal */
  31087. bool readXml (const XmlElement& xml);
  31088. /** @internal */
  31089. void writeXml (XmlElement& xml) const;
  31090. juce_UseDebuggingNewOperator
  31091. private:
  31092. OwnedArray <Drawable> drawables;
  31093. OwnedArray <AffineTransform> transforms;
  31094. DrawableComposite (const DrawableComposite&);
  31095. const DrawableComposite& operator= (const DrawableComposite&);
  31096. };
  31097. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  31098. /********* End of inlined file: juce_DrawableComposite.h *********/
  31099. #endif
  31100. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31101. /********* Start of inlined file: juce_DrawableImage.h *********/
  31102. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31103. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31104. /**
  31105. A drawable object which is a bitmap image.
  31106. @see Drawable
  31107. */
  31108. class JUCE_API DrawableImage : public Drawable
  31109. {
  31110. public:
  31111. DrawableImage();
  31112. /** Destructor. */
  31113. virtual ~DrawableImage();
  31114. /** Sets the image that this drawable will render.
  31115. An internal copy is made of the image passed-in. If you want to provide an
  31116. image that this object can take charge of without needing to create a copy,
  31117. use the other setImage() method.
  31118. */
  31119. void setImage (const Image& imageToCopy);
  31120. /** Sets the image that this drawable will render.
  31121. An internal copy of this will not be made, so the caller mustn't delete
  31122. the image while it's still being used by this object.
  31123. A good way to use this is with the ImageCache - if you create an image
  31124. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  31125. it'll be released neatly with its reference count being decreased.
  31126. @param imageToUse the image to render
  31127. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  31128. then the image will be deleted when this object no longer
  31129. needs it - unless the image was created by the ImageCache,
  31130. in which case it will be released with ImageCache::release().
  31131. */
  31132. void setImage (Image* imageToUse,
  31133. const bool releaseWhenNotNeeded);
  31134. /** Returns the current image. */
  31135. Image* getImage() const throw() { return image; }
  31136. /** Clears (and possibly deletes) the currently set image. */
  31137. void clearImage();
  31138. /** Sets the opacity to use when drawing the image. */
  31139. void setOpacity (const float newOpacity);
  31140. /** Returns the image's opacity. */
  31141. float getOpacity() const throw() { return opacity; }
  31142. /** Sets a colour to draw over the image's alpha channel.
  31143. By default this is transparent so isn't drawn, but if you set a non-transparent
  31144. colour here, then it will be overlaid on the image, using the image's alpha
  31145. channel as a mask.
  31146. This is handy for doing things like darkening or lightening an image by overlaying
  31147. it with semi-transparent black or white.
  31148. */
  31149. void setOverlayColour (const Colour& newOverlayColour);
  31150. /** Returns the overlay colour. */
  31151. const Colour& getOverlayColour() const throw() { return overlayColour; }
  31152. /** @internal */
  31153. void render (const Drawable::RenderingContext& context) const;
  31154. /** @internal */
  31155. void getBounds (float& x, float& y, float& width, float& height) const;
  31156. /** @internal */
  31157. bool hitTest (float x, float y) const;
  31158. /** @internal */
  31159. Drawable* createCopy() const;
  31160. /** @internal */
  31161. bool readBinary (InputStream& input);
  31162. /** @internal */
  31163. bool writeBinary (OutputStream& output) const;
  31164. /** @internal */
  31165. bool readXml (const XmlElement& xml);
  31166. /** @internal */
  31167. void writeXml (XmlElement& xml) const;
  31168. juce_UseDebuggingNewOperator
  31169. private:
  31170. Image* image;
  31171. bool canDeleteImage;
  31172. float opacity;
  31173. Colour overlayColour;
  31174. DrawableImage (const DrawableImage&);
  31175. const DrawableImage& operator= (const DrawableImage&);
  31176. };
  31177. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31178. /********* End of inlined file: juce_DrawableImage.h *********/
  31179. #endif
  31180. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  31181. #endif
  31182. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  31183. #endif
  31184. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  31185. #endif
  31186. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  31187. #endif
  31188. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  31189. #endif
  31190. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31191. /********* Start of inlined file: juce_ArrowButton.h *********/
  31192. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31193. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31194. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  31195. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31196. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31197. /**
  31198. An effect filter that adds a drop-shadow behind the image's content.
  31199. (This will only work on images/components that aren't opaque, of course).
  31200. When added to a component, this effect will draw a soft-edged
  31201. shadow based on what gets drawn inside it. The shadow will also
  31202. be applied to the component's children.
  31203. For speed, this doesn't use a proper gaussian blur, but cheats by
  31204. using a simple bilinear filter. If you need a really high-quality
  31205. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31206. @see Component::setComponentEffect
  31207. */
  31208. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31209. {
  31210. public:
  31211. /** Creates a default drop-shadow effect.
  31212. To customise the shadow's appearance, use the setShadowProperties()
  31213. method.
  31214. */
  31215. DropShadowEffect();
  31216. /** Destructor. */
  31217. ~DropShadowEffect();
  31218. /** Sets up parameters affecting the shadow's appearance.
  31219. @param newRadius the (approximate) radius of the blur used
  31220. @param newOpacity the opacity with which the shadow is rendered
  31221. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  31222. component's contents
  31223. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  31224. component's contents
  31225. */
  31226. void setShadowProperties (const float newRadius,
  31227. const float newOpacity,
  31228. const int newShadowOffsetX,
  31229. const int newShadowOffsetY);
  31230. /** @internal */
  31231. void applyEffect (Image& sourceImage, Graphics& destContext);
  31232. juce_UseDebuggingNewOperator
  31233. private:
  31234. int offsetX, offsetY;
  31235. float radius, opacity;
  31236. };
  31237. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31238. /********* End of inlined file: juce_DropShadowEffect.h *********/
  31239. /**
  31240. A button with an arrow in it.
  31241. @see Button
  31242. */
  31243. class JUCE_API ArrowButton : public Button
  31244. {
  31245. public:
  31246. /** Creates an ArrowButton.
  31247. @param buttonName the name to give the button
  31248. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31249. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31250. @param arrowColour the colour to use for the arrow
  31251. */
  31252. ArrowButton (const String& buttonName,
  31253. float arrowDirection,
  31254. const Colour& arrowColour);
  31255. /** Destructor. */
  31256. ~ArrowButton();
  31257. juce_UseDebuggingNewOperator
  31258. protected:
  31259. /** @internal */
  31260. void paintButton (Graphics& g,
  31261. bool isMouseOverButton,
  31262. bool isButtonDown);
  31263. /** @internal */
  31264. void buttonStateChanged();
  31265. private:
  31266. Colour colour;
  31267. DropShadowEffect shadow;
  31268. Path path;
  31269. int offset;
  31270. ArrowButton (const ArrowButton&);
  31271. const ArrowButton& operator= (const ArrowButton&);
  31272. };
  31273. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  31274. /********* End of inlined file: juce_ArrowButton.h *********/
  31275. #endif
  31276. #ifndef __JUCE_BUTTON_JUCEHEADER__
  31277. #endif
  31278. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31279. /********* Start of inlined file: juce_DrawableButton.h *********/
  31280. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31281. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31282. /**
  31283. A button that displays a Drawable.
  31284. Up to three Drawable objects can be given to this button, to represent the
  31285. 'normal', 'over' and 'down' states.
  31286. @see Button
  31287. */
  31288. class JUCE_API DrawableButton : public Button
  31289. {
  31290. public:
  31291. enum ButtonStyle
  31292. {
  31293. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  31294. ImageRaw, /**< The button will just display the images in their normal size and position.
  31295. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  31296. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  31297. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  31298. };
  31299. /** Creates a DrawableButton.
  31300. After creating one of these, use setImages() to specify the drawables to use.
  31301. @param buttonName the name to give the component
  31302. @param buttonStyle the layout to use
  31303. @see ButtonStyle, setButtonStyle, setImages
  31304. */
  31305. DrawableButton (const String& buttonName,
  31306. const ButtonStyle buttonStyle);
  31307. /** Destructor. */
  31308. ~DrawableButton();
  31309. /** Sets up the images to draw for the various button states.
  31310. The button will keep its own internal copies of these drawables.
  31311. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  31312. will be made of the object passed-in if it is non-zero.
  31313. @param overImage the thing to draw for the button's 'over' state - if this is
  31314. zero, the button's normal image will be used when the mouse is
  31315. over it. An internal copy will be made of the object passed-in
  31316. if it is non-zero.
  31317. @param downImage the thing to draw for the button's 'down' state - if this is
  31318. zero, the 'over' image will be used instead (or the normal image
  31319. as a last resort). An internal copy will be made of the object
  31320. passed-in if it is non-zero.
  31321. @param disabledImage an image to draw when the button is disabled. If this is zero,
  31322. the normal image will be drawn with a reduced opacity instead.
  31323. An internal copy will be made of the object passed-in if it is
  31324. non-zero.
  31325. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  31326. state is 'on'. If this is 0, the normal image is used instead
  31327. @param overImageOn same as the overImage, but this is used when the button's toggle
  31328. state is 'on'. If this is 0, the normalImageOn is drawn instead
  31329. @param downImageOn same as the downImage, but this is used when the button's toggle
  31330. state is 'on'. If this is 0, the overImageOn is drawn instead
  31331. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  31332. state is 'on'. If this is 0, the normal image will be drawn instead
  31333. with a reduced opacity
  31334. */
  31335. void setImages (const Drawable* normalImage,
  31336. const Drawable* overImage = 0,
  31337. const Drawable* downImage = 0,
  31338. const Drawable* disabledImage = 0,
  31339. const Drawable* normalImageOn = 0,
  31340. const Drawable* overImageOn = 0,
  31341. const Drawable* downImageOn = 0,
  31342. const Drawable* disabledImageOn = 0);
  31343. /** Changes the button's style.
  31344. @see ButtonStyle
  31345. */
  31346. void setButtonStyle (const ButtonStyle newStyle);
  31347. /** Changes the button's background colours.
  31348. The toggledOffColour is the colour to use when the button's toggle state
  31349. is off, and toggledOnColour when it's on.
  31350. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  31351. used to fill the background of the component.
  31352. For an ImageOnButtonBackground style, the colour is used to draw the
  31353. button's lozenge shape and exactly how the colour's used will depend
  31354. on the LookAndFeel.
  31355. */
  31356. void setBackgroundColours (const Colour& toggledOffColour,
  31357. const Colour& toggledOnColour);
  31358. /** Returns the current background colour being used.
  31359. @see setBackgroundColour
  31360. */
  31361. const Colour& getBackgroundColour() const throw();
  31362. /** Gives the button an optional amount of space around the edge of the drawable.
  31363. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  31364. ones on a button background. If the button is too small for the given gap, a
  31365. smaller gap will be used.
  31366. By default there's a gap of about 3 pixels.
  31367. */
  31368. void setEdgeIndent (const int numPixelsIndent);
  31369. /** Returns the image that the button is currently displaying. */
  31370. const Drawable* getCurrentImage() const throw();
  31371. const Drawable* getNormalImage() const throw();
  31372. const Drawable* getOverImage() const throw();
  31373. const Drawable* getDownImage() const throw();
  31374. juce_UseDebuggingNewOperator
  31375. protected:
  31376. /** @internal */
  31377. void paintButton (Graphics& g,
  31378. bool isMouseOverButton,
  31379. bool isButtonDown);
  31380. private:
  31381. ButtonStyle style;
  31382. Drawable* normalImage;
  31383. Drawable* overImage;
  31384. Drawable* downImage;
  31385. Drawable* disabledImage;
  31386. Drawable* normalImageOn;
  31387. Drawable* overImageOn;
  31388. Drawable* downImageOn;
  31389. Drawable* disabledImageOn;
  31390. Colour backgroundOff, backgroundOn;
  31391. int edgeIndent;
  31392. void deleteImages();
  31393. DrawableButton (const DrawableButton&);
  31394. const DrawableButton& operator= (const DrawableButton&);
  31395. };
  31396. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31397. /********* End of inlined file: juce_DrawableButton.h *********/
  31398. #endif
  31399. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31400. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  31401. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31402. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31403. /**
  31404. A button showing an underlined weblink, that will launch the link
  31405. when it's clicked.
  31406. @see Button
  31407. */
  31408. class JUCE_API HyperlinkButton : public Button
  31409. {
  31410. public:
  31411. /** Creates a HyperlinkButton.
  31412. @param linkText the text that will be displayed in the button - this is
  31413. also set as the Component's name, but the text can be
  31414. changed later with the Button::getButtonText() method
  31415. @param linkURL the URL to launch when the user clicks the button
  31416. */
  31417. HyperlinkButton (const String& linkText,
  31418. const URL& linkURL);
  31419. /** Destructor. */
  31420. ~HyperlinkButton();
  31421. /** Changes the font to use for the text.
  31422. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  31423. to match the size of the component.
  31424. */
  31425. void setFont (const Font& newFont,
  31426. const bool resizeToMatchComponentHeight,
  31427. const Justification& justificationType = Justification::horizontallyCentred);
  31428. /** A set of colour IDs to use to change the colour of various aspects of the link.
  31429. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31430. methods.
  31431. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31432. */
  31433. enum ColourIds
  31434. {
  31435. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  31436. };
  31437. /** Changes the URL that the button will trigger. */
  31438. void setURL (const URL& newURL) throw();
  31439. /** Returns the URL that the button will trigger. */
  31440. const URL& getURL() const throw() { return url; }
  31441. /** Resizes the button horizontally to fit snugly around the text.
  31442. This won't affect the button's height.
  31443. */
  31444. void changeWidthToFitText();
  31445. juce_UseDebuggingNewOperator
  31446. protected:
  31447. /** @internal */
  31448. void clicked();
  31449. /** @internal */
  31450. void colourChanged();
  31451. /** @internal */
  31452. void paintButton (Graphics& g,
  31453. bool isMouseOverButton,
  31454. bool isButtonDown);
  31455. private:
  31456. URL url;
  31457. Font font;
  31458. bool resizeFont;
  31459. Justification justification;
  31460. const Font getFontToUse() const;
  31461. HyperlinkButton (const HyperlinkButton&);
  31462. const HyperlinkButton& operator= (const HyperlinkButton&);
  31463. };
  31464. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31465. /********* End of inlined file: juce_HyperlinkButton.h *********/
  31466. #endif
  31467. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  31468. /********* Start of inlined file: juce_ImageButton.h *********/
  31469. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  31470. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  31471. /**
  31472. As the title suggests, this is a button containing an image.
  31473. The colour and transparency of the image can be set to vary when the
  31474. button state changes.
  31475. @see Button, ShapeButton, TextButton
  31476. */
  31477. class JUCE_API ImageButton : public Button
  31478. {
  31479. public:
  31480. /** Creates an ImageButton.
  31481. Use setImage() to specify the image to use. The colours and opacities that
  31482. are specified here can be changed later using setDrawingOptions().
  31483. @param name the name to give the component
  31484. */
  31485. ImageButton (const String& name);
  31486. /** Destructor. */
  31487. ~ImageButton();
  31488. /** Sets up the images to draw in various states.
  31489. Important! Bear in mind that if you pass the same image in for more than one of
  31490. these parameters, this button will delete it (or release from the ImageCache)
  31491. multiple times!
  31492. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  31493. resized to the same dimensions as the normal image
  31494. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  31495. button when the button's size changes
  31496. @param preserveImageProportions if true then any rescaling of the image to fit
  31497. the button will keep the image's x and y proportions
  31498. correct - i.e. it won't distort its shape, although
  31499. this might create gaps around the edges
  31500. @param normalImage the image to use when the button is in its normal state. The
  31501. image passed in will be deleted (or released if it
  31502. was created by the ImageCache class) when the
  31503. button no longer needs it.
  31504. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  31505. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  31506. normal image - if this colour is transparent, no overlay
  31507. will be drawn. The overlay will be drawn over the top of the
  31508. image, so you can basically add a solid or semi-transparent
  31509. colour to the image to brighten or darken it
  31510. @param overImage the image to use when the mouse is over the button. If
  31511. you want to use the same image as was set in the normalImage
  31512. parameter, this value can be 0. As for normalImage, it
  31513. will be deleted or released by the button when no longer
  31514. needed
  31515. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  31516. is over the button
  31517. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  31518. image when the mouse is over - if this colour is transparent,
  31519. no overlay will be drawn
  31520. @param downImage an image to use when the button is pressed down. If set
  31521. to zero, the 'over' image will be drawn instead (or the
  31522. normal image if there isn't an 'over' image either). This
  31523. image will be deleted or released by the button when no
  31524. longer needed
  31525. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  31526. is pressed
  31527. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  31528. image when the button is pressed down - if this colour is
  31529. transparent, no overlay will be drawn
  31530. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  31531. whenever it's inside the button's bounding rectangle. If
  31532. set to values higher than 0, the mouse will only be
  31533. considered to be over the image when the value of the
  31534. image's alpha channel at that position is greater than
  31535. this level.
  31536. */
  31537. void setImages (const bool resizeButtonNowToFitThisImage,
  31538. const bool rescaleImagesWhenButtonSizeChanges,
  31539. const bool preserveImageProportions,
  31540. Image* const normalImage,
  31541. const float imageOpacityWhenNormal,
  31542. const Colour& overlayColourWhenNormal,
  31543. Image* const overImage,
  31544. const float imageOpacityWhenOver,
  31545. const Colour& overlayColourWhenOver,
  31546. Image* const downImage,
  31547. const float imageOpacityWhenDown,
  31548. const Colour& overlayColourWhenDown,
  31549. const float hitTestAlphaThreshold = 0.0f);
  31550. /** Returns the currently set 'normal' image. */
  31551. Image* getNormalImage() const throw();
  31552. /** Returns the image that's drawn when the mouse is over the button.
  31553. If an 'over' image has been set, this will return it; otherwise it'll
  31554. just return the normal image.
  31555. */
  31556. Image* getOverImage() const throw();
  31557. /** Returns the image that's drawn when the button is held down.
  31558. If a 'down' image has been set, this will return it; otherwise it'll
  31559. return the 'over' image or normal image, depending on what's available.
  31560. */
  31561. Image* getDownImage() const throw();
  31562. juce_UseDebuggingNewOperator
  31563. protected:
  31564. /** @internal */
  31565. bool hitTest (int x, int y);
  31566. /** @internal */
  31567. void paintButton (Graphics& g,
  31568. bool isMouseOverButton,
  31569. bool isButtonDown);
  31570. private:
  31571. bool scaleImageToFit, preserveProportions;
  31572. unsigned char alphaThreshold;
  31573. int imageX, imageY, imageW, imageH;
  31574. Image* normalImage;
  31575. Image* overImage;
  31576. Image* downImage;
  31577. float normalOpacity, overOpacity, downOpacity;
  31578. Colour normalOverlay, overOverlay, downOverlay;
  31579. Image* getCurrentImage() const;
  31580. void deleteImages();
  31581. ImageButton (const ImageButton&);
  31582. const ImageButton& operator= (const ImageButton&);
  31583. };
  31584. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  31585. /********* End of inlined file: juce_ImageButton.h *********/
  31586. #endif
  31587. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31588. /********* Start of inlined file: juce_ShapeButton.h *********/
  31589. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31590. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  31591. /**
  31592. A button that contains a filled shape.
  31593. @see Button, ImageButton, TextButton, ArrowButton
  31594. */
  31595. class JUCE_API ShapeButton : public Button
  31596. {
  31597. public:
  31598. /** Creates a ShapeButton.
  31599. @param name a name to give the component - see Component::setName()
  31600. @param normalColour the colour to fill the shape with when the mouse isn't over
  31601. @param overColour the colour to use when the mouse is over the shape
  31602. @param downColour the colour to use when the button is in the pressed-down state
  31603. */
  31604. ShapeButton (const String& name,
  31605. const Colour& normalColour,
  31606. const Colour& overColour,
  31607. const Colour& downColour);
  31608. /** Destructor. */
  31609. ~ShapeButton();
  31610. /** Sets the shape to use.
  31611. @param newShape the shape to use
  31612. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  31613. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  31614. the button is resized
  31615. @param hasDropShadow if true, the button will be given a drop-shadow effect
  31616. */
  31617. void setShape (const Path& newShape,
  31618. const bool resizeNowToFitThisShape,
  31619. const bool maintainShapeProportions,
  31620. const bool hasDropShadow);
  31621. /** Set the colours to use for drawing the shape.
  31622. @param normalColour the colour to fill the shape with when the mouse isn't over
  31623. @param overColour the colour to use when the mouse is over the shape
  31624. @param downColour the colour to use when the button is in the pressed-down state
  31625. */
  31626. void setColours (const Colour& normalColour,
  31627. const Colour& overColour,
  31628. const Colour& downColour);
  31629. /** Sets up an outline to draw around the shape.
  31630. @param outlineColour the colour to use
  31631. @param outlineStrokeWidth the thickness of line to draw
  31632. */
  31633. void setOutline (const Colour& outlineColour,
  31634. const float outlineStrokeWidth);
  31635. juce_UseDebuggingNewOperator
  31636. protected:
  31637. /** @internal */
  31638. void paintButton (Graphics& g,
  31639. bool isMouseOverButton,
  31640. bool isButtonDown);
  31641. private:
  31642. Colour normalColour, overColour, downColour, outlineColour;
  31643. DropShadowEffect shadow;
  31644. Path shape;
  31645. bool maintainShapeProportions;
  31646. float outlineWidth;
  31647. ShapeButton (const ShapeButton&);
  31648. const ShapeButton& operator= (const ShapeButton&);
  31649. };
  31650. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  31651. /********* End of inlined file: juce_ShapeButton.h *********/
  31652. #endif
  31653. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  31654. #endif
  31655. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31656. /********* Start of inlined file: juce_ToggleButton.h *********/
  31657. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31658. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31659. /**
  31660. A button that can be toggled on/off.
  31661. All buttons can be toggle buttons, but this lets you create one of the
  31662. standard ones which has a tick-box and a text label next to it.
  31663. @see Button, DrawableButton, TextButton
  31664. */
  31665. class JUCE_API ToggleButton : public Button
  31666. {
  31667. public:
  31668. /** Creates a ToggleButton.
  31669. @param buttonText the text to put in the button (the component's name is also
  31670. initially set to this string, but these can be changed later
  31671. using the setName() and setButtonText() methods)
  31672. */
  31673. ToggleButton (const String& buttonText);
  31674. /** Destructor. */
  31675. ~ToggleButton();
  31676. /** Resizes the button to fit neatly around its current text.
  31677. The button's height won't be affected, only its width.
  31678. */
  31679. void changeWidthToFitText();
  31680. /** A set of colour IDs to use to change the colour of various aspects of the button.
  31681. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31682. methods.
  31683. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31684. */
  31685. enum ColourIds
  31686. {
  31687. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  31688. };
  31689. juce_UseDebuggingNewOperator
  31690. protected:
  31691. /** @internal */
  31692. void paintButton (Graphics& g,
  31693. bool isMouseOverButton,
  31694. bool isButtonDown);
  31695. /** @internal */
  31696. void colourChanged();
  31697. private:
  31698. ToggleButton (const ToggleButton&);
  31699. const ToggleButton& operator= (const ToggleButton&);
  31700. };
  31701. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31702. /********* End of inlined file: juce_ToggleButton.h *********/
  31703. #endif
  31704. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31705. /********* Start of inlined file: juce_ToolbarButton.h *********/
  31706. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31707. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31708. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  31709. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31710. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31711. /********* Start of inlined file: juce_Toolbar.h *********/
  31712. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  31713. #define __JUCE_TOOLBAR_JUCEHEADER__
  31714. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  31715. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31716. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31717. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  31718. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31719. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31720. /**
  31721. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  31722. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  31723. derive your component from this class, and make sure that it is somewhere inside a
  31724. DragAndDropContainer component.
  31725. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31726. the operating system onto your component, you don't need any of these classes: instead
  31727. see the FileDragAndDropTarget class.
  31728. @see DragAndDropContainer, FileDragAndDropTarget
  31729. */
  31730. class JUCE_API DragAndDropTarget
  31731. {
  31732. public:
  31733. /** Destructor. */
  31734. virtual ~DragAndDropTarget() {}
  31735. /** Callback to check whether this target is interested in the type of object being
  31736. dragged.
  31737. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31738. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31739. @returns true if this component wants to receive the other callbacks regarging this
  31740. type of object; if it returns false, no other callbacks will be made.
  31741. */
  31742. virtual bool isInterestedInDragSource (const String& sourceDescription,
  31743. Component* sourceComponent) = 0;
  31744. /** Callback to indicate that something is being dragged over this component.
  31745. This gets called when the user moves the mouse into this component while dragging
  31746. something.
  31747. Use this callback as a trigger to make your component repaint itself to give the
  31748. user feedback about whether the item can be dropped here or not.
  31749. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31750. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31751. @param x the mouse x position, relative to this component
  31752. @param y the mouse y position, relative to this component
  31753. @see itemDragExit
  31754. */
  31755. virtual void itemDragEnter (const String& sourceDescription,
  31756. Component* sourceComponent,
  31757. int x,
  31758. int y);
  31759. /** Callback to indicate that the user is dragging something over this component.
  31760. This gets called when the user moves the mouse over this component while dragging
  31761. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  31762. this lets you know what happens in-between.
  31763. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31764. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31765. @param x the mouse x position, relative to this component
  31766. @param y the mouse y position, relative to this component
  31767. */
  31768. virtual void itemDragMove (const String& sourceDescription,
  31769. Component* sourceComponent,
  31770. int x,
  31771. int y);
  31772. /** Callback to indicate that something has been dragged off the edge of this component.
  31773. This gets called when the user moves the mouse out of this component while dragging
  31774. something.
  31775. If you've used itemDragEnter() to repaint your component and give feedback, use this
  31776. as a signal to repaint it in its normal state.
  31777. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31778. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31779. @see itemDragEnter
  31780. */
  31781. virtual void itemDragExit (const String& sourceDescription,
  31782. Component* sourceComponent);
  31783. /** Callback to indicate that the user has dropped something onto this component.
  31784. When the user drops an item this get called, and you can use the description to
  31785. work out whether your object wants to deal with it or not.
  31786. Note that after this is called, the itemDragExit method may not be called, so you should
  31787. clean up in here if there's anything you need to do when the drag finishes.
  31788. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31789. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31790. @param x the mouse x position, relative to this component
  31791. @param y the mouse y position, relative to this component
  31792. */
  31793. virtual void itemDropped (const String& sourceDescription,
  31794. Component* sourceComponent,
  31795. int x,
  31796. int y) = 0;
  31797. /** Overriding this allows the target to tell the drag container whether to
  31798. draw the drag image while the cursor is over it.
  31799. By default it returns true, but if you return false, then the normal drag
  31800. image will not be shown when the cursor is over this target.
  31801. */
  31802. virtual bool shouldDrawDragImageWhenOver();
  31803. };
  31804. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31805. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  31806. /**
  31807. Enables drag-and-drop behaviour for a component and all its sub-components.
  31808. For a component to be able to make or receive drag-and-drop events, one of its parent
  31809. components must derive from this class. It's probably best for the top-level
  31810. component to implement it.
  31811. Then to start a drag operation, any sub-component can just call the startDragging()
  31812. method, and this object will take over, tracking the mouse and sending appropriate
  31813. callbacks to any child components derived from DragAndDropTarget which the mouse
  31814. moves over.
  31815. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31816. the operating system onto your component, you don't need any of these classes: you can do this
  31817. simply by overriding Component::filesDropped().
  31818. @see DragAndDropTarget
  31819. */
  31820. class JUCE_API DragAndDropContainer
  31821. {
  31822. public:
  31823. /** Creates a DragAndDropContainer.
  31824. The object that derives from this class must also be a Component.
  31825. */
  31826. DragAndDropContainer();
  31827. /** Destructor. */
  31828. virtual ~DragAndDropContainer();
  31829. /** Begins a drag-and-drop operation.
  31830. This starts a drag-and-drop operation - call it when the user drags the
  31831. mouse in your drag-source component, and this object will track mouse
  31832. movements until the user lets go of the mouse button, and will send
  31833. appropriate messages to DragAndDropTarget objects that the mouse moves
  31834. over.
  31835. findParentDragContainerFor() is a handy method to call to find the
  31836. drag container to use for a component.
  31837. @param sourceDescription a string to use as the description of the thing being
  31838. dragged - this will be passed to the objects that might be
  31839. dropped-onto so they can decide if they want to handle it or
  31840. not
  31841. @param sourceComponent the component that is being dragged
  31842. @param dragImage the image to drag around underneath the mouse. If this is
  31843. zero, a snapshot of the sourceComponent will be used instead. An
  31844. image passed-in will be deleted by this object when no longer
  31845. needed.
  31846. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  31847. window, and can be dragged to DragAndDropTargets that are the
  31848. children of components other than this one.
  31849. */
  31850. void startDragging (const String& sourceDescription,
  31851. Component* sourceComponent,
  31852. Image* dragImage = 0,
  31853. const bool allowDraggingToOtherJuceWindows = false);
  31854. /** Returns true if something is currently being dragged. */
  31855. bool isDragAndDropActive() const;
  31856. /** Returns the description of the thing that's currently being dragged.
  31857. If nothing's being dragged, this will return an empty string, otherwise it's the
  31858. string that was passed into startDragging().
  31859. @see startDragging
  31860. */
  31861. const String getCurrentDragDescription() const;
  31862. /** Utility to find the DragAndDropContainer for a given Component.
  31863. This will search up this component's parent hierarchy looking for the first
  31864. parent component which is a DragAndDropContainer.
  31865. It's useful when a component wants to call startDragging but doesn't know
  31866. the DragAndDropContainer it should to use.
  31867. Obviously this may return 0 if it doesn't find a suitable component.
  31868. */
  31869. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  31870. /** This performs a synchronous drag-and-drop of a set of files to some external
  31871. application.
  31872. You can call this function in response to a mouseDrag callback, and it will
  31873. block, running its own internal message loop and tracking the mouse, while it
  31874. uses a native operating system drag-and-drop operation to move or copy some
  31875. files to another application.
  31876. @param files a list of filenames to drag
  31877. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  31878. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  31879. @returns true if the files were successfully dropped somewhere, or false if it
  31880. was interrupted
  31881. @see performExternalDragDropOfText
  31882. */
  31883. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  31884. /** This performs a synchronous drag-and-drop of a block of text to some external
  31885. application.
  31886. You can call this function in response to a mouseDrag callback, and it will
  31887. block, running its own internal message loop and tracking the mouse, while it
  31888. uses a native operating system drag-and-drop operation to move or copy some
  31889. text to another application.
  31890. @param text the text to copy
  31891. @returns true if the text was successfully dropped somewhere, or false if it
  31892. was interrupted
  31893. @see performExternalDragDropOfFiles
  31894. */
  31895. static bool performExternalDragDropOfText (const String& text);
  31896. juce_UseDebuggingNewOperator
  31897. protected:
  31898. /** Override this if you want to be able to perform an external drag a set of files
  31899. when the user drags outside of this container component.
  31900. This method will be called when a drag operation moves outside the Juce-based window,
  31901. and if you want it to then perform a file drag-and-drop, add the filenames you want
  31902. to the array passed in, and return true.
  31903. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  31904. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  31905. @param files on return, the filenames you want to drag
  31906. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  31907. it must make a copy of them (see the performExternalDragDropOfFiles()
  31908. method)
  31909. @see performExternalDragDropOfFiles
  31910. */
  31911. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  31912. Component* dragSourceComponent,
  31913. StringArray& files,
  31914. bool& canMoveFiles);
  31915. private:
  31916. friend class DragImageComponent;
  31917. Component* dragImageComponent;
  31918. String currentDragDesc;
  31919. };
  31920. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31921. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31922. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31923. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31924. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31925. /**
  31926. Animates a set of components, moving it to a new position.
  31927. To use this, create a ComponentAnimator, and use its animateComponent() method
  31928. to tell it to move components to destination positions. Any number of
  31929. components can be animated by one ComponentAnimator object (if you've got a
  31930. lot of components to move, it's much more efficient to share a single animator
  31931. than to have many animators running at once).
  31932. You'll need to make sure the animator object isn't deleted before it finishes
  31933. moving the components.
  31934. The class is a ChangeBroadcaster and sends a notification when any components
  31935. start or finish being animated.
  31936. */
  31937. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  31938. private Timer
  31939. {
  31940. public:
  31941. /** Creates a ComponentAnimator. */
  31942. ComponentAnimator();
  31943. /** Destructor. */
  31944. ~ComponentAnimator();
  31945. /** Starts a component moving from its current position to a specified position.
  31946. If the component is already in the middle of an animation, that will be abandoned,
  31947. and a new animation will begin, moving the component from its current location.
  31948. The start and end speed parameters let you apply some acceleration to the component's
  31949. movement.
  31950. @param component the component to move
  31951. @param finalPosition the destination position and size to move it to
  31952. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31953. to arrive at its destination
  31954. @param startSpeed a value to indicate the relative start speed of the
  31955. animation. If this is 0, the component will start
  31956. by accelerating from rest; higher values mean that it
  31957. will have an initial speed greater than zero. If the
  31958. value if greater than 1, it will decelerate towards the
  31959. middle of its journey. To move the component at a constant
  31960. rate for its entire animation, set both the start and
  31961. end speeds to 1.0
  31962. @param endSpeed a relative speed at which the component should be moving
  31963. when the animation finishes. If this is 0, the component
  31964. will decelerate to a standstill at its final position; higher
  31965. values mean the component will still be moving when it stops.
  31966. To move the component at a constant rate for its entire
  31967. animation, set both the start and end speeds to 1.0
  31968. */
  31969. void animateComponent (Component* const component,
  31970. const Rectangle& finalPosition,
  31971. const int millisecondsToSpendMoving,
  31972. const double startSpeed = 1.0,
  31973. const double endSpeed = 1.0);
  31974. /** Stops a component if it's currently being animated.
  31975. If moveComponentToItsFinalPosition is true, then the component will
  31976. be immediately moved to its destination position and size. If false, it will be
  31977. left in whatever location it currently occupies.
  31978. */
  31979. void cancelAnimation (Component* const component,
  31980. const bool moveComponentToItsFinalPosition);
  31981. /** Clears all of the active animations.
  31982. If moveComponentsToTheirFinalPositions is true, all the components will
  31983. be immediately set to their final positions. If false, they will be
  31984. left in whatever locations they currently occupy.
  31985. */
  31986. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31987. /** Returns the destination position for a component.
  31988. If the component is being animated, this will return the target position that
  31989. was specified when animateComponent() was called.
  31990. If the specified component isn't currently being animated, this method will just
  31991. return its current position.
  31992. */
  31993. const Rectangle getComponentDestination (Component* const component);
  31994. /** Returns true if the specified component is currently being animated.
  31995. */
  31996. bool isAnimating (Component* component) const;
  31997. juce_UseDebuggingNewOperator
  31998. private:
  31999. VoidArray tasks;
  32000. uint32 lastTime;
  32001. void* findTaskFor (Component* const component) const;
  32002. void timerCallback();
  32003. };
  32004. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32005. /********* End of inlined file: juce_ComponentAnimator.h *********/
  32006. class ToolbarItemComponent;
  32007. class ToolbarItemFactory;
  32008. class MissingItemsComponent;
  32009. /**
  32010. A toolbar component.
  32011. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  32012. and looks after their order and layout.
  32013. Items (icon buttons or other custom components) are added to a toolbar using a
  32014. ToolbarItemFactory - each type of item is given a unique ID number, and a
  32015. toolbar might contain more than one instance of a particular item type.
  32016. Toolbars can be interactively customised, allowing the user to drag the items
  32017. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  32018. component as a source of new items.
  32019. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  32020. */
  32021. class JUCE_API Toolbar : public Component,
  32022. public DragAndDropContainer,
  32023. public DragAndDropTarget,
  32024. private ButtonListener
  32025. {
  32026. public:
  32027. /** Creates an empty toolbar component.
  32028. To add some icons or other components to your toolbar, you'll need to
  32029. create a ToolbarItemFactory class that can create a suitable set of
  32030. ToolbarItemComponents.
  32031. @see ToolbarItemFactory, ToolbarItemComponents
  32032. */
  32033. Toolbar();
  32034. /** Destructor.
  32035. Any items on the bar will be deleted when the toolbar is deleted.
  32036. */
  32037. ~Toolbar();
  32038. /** Changes the bar's orientation.
  32039. @see isVertical
  32040. */
  32041. void setVertical (const bool shouldBeVertical);
  32042. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  32043. You can change the bar's orientation with setVertical().
  32044. */
  32045. bool isVertical() const throw() { return vertical; }
  32046. /** Returns the depth of the bar.
  32047. If the bar is horizontal, this will return its height; if it's vertical, it
  32048. will return its width.
  32049. @see getLength
  32050. */
  32051. int getThickness() const throw();
  32052. /** Returns the length of the bar.
  32053. If the bar is horizontal, this will return its width; if it's vertical, it
  32054. will return its height.
  32055. @see getThickness
  32056. */
  32057. int getLength() const throw();
  32058. /** Deletes all items from the bar.
  32059. */
  32060. void clear();
  32061. /** Adds an item to the toolbar.
  32062. The factory's ToolbarItemFactory::createItem() will be called by this method
  32063. to create the component that will actually be added to the bar.
  32064. The new item will be inserted at the specified index (if the index is -1, it
  32065. will be added to the right-hand or bottom end of the bar).
  32066. Once added, the component will be automatically deleted by this object when it
  32067. is no longer needed.
  32068. @see ToolbarItemFactory
  32069. */
  32070. void addItem (ToolbarItemFactory& factory,
  32071. const int itemId,
  32072. const int insertIndex = -1);
  32073. /** Deletes one of the items from the bar.
  32074. */
  32075. void removeToolbarItem (const int itemIndex);
  32076. /** Returns the number of items currently on the toolbar.
  32077. @see getItemId, getItemComponent
  32078. */
  32079. int getNumItems() const throw();
  32080. /** Returns the ID of the item with the given index.
  32081. If the index is less than zero or greater than the number of items,
  32082. this will return 0.
  32083. @see getNumItems
  32084. */
  32085. int getItemId (const int itemIndex) const throw();
  32086. /** Returns the component being used for the item with the given index.
  32087. If the index is less than zero or greater than the number of items,
  32088. this will return 0.
  32089. @see getNumItems
  32090. */
  32091. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  32092. /** Clears this toolbar and adds to it the default set of items that the specified
  32093. factory creates.
  32094. @see ToolbarItemFactory::getDefaultItemSet
  32095. */
  32096. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  32097. /** Options for the way items should be displayed.
  32098. @see setStyle, getStyle
  32099. */
  32100. enum ToolbarItemStyle
  32101. {
  32102. iconsOnly, /**< Means that the toolbar should just contain icons. */
  32103. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  32104. textOnly /**< Means that the toolbar only display text labels for each item. */
  32105. };
  32106. /** Returns the toolbar's current style.
  32107. @see ToolbarItemStyle, setStyle
  32108. */
  32109. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32110. /** Changes the toolbar's current style.
  32111. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  32112. */
  32113. void setStyle (const ToolbarItemStyle& newStyle);
  32114. /** Flags used by the showCustomisationDialog() method. */
  32115. enum CustomisationFlags
  32116. {
  32117. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  32118. show the "icons only" option on its choice of toolbar styles. */
  32119. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  32120. show the "icons with text" option on its choice of toolbar styles. */
  32121. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  32122. show the "text only" option on its choice of toolbar styles. */
  32123. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  32124. show a button to reset the toolbar to its default set of items. */
  32125. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  32126. };
  32127. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  32128. The dialog contains a ToolbarItemPalette and various controls for editing other
  32129. aspects of the toolbar. This method will block and run the dialog box modally,
  32130. returning when the user closes it.
  32131. The factory is used to determine the set of items that will be shown on the
  32132. palette.
  32133. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  32134. enum.
  32135. @see ToolbarItemPalette
  32136. */
  32137. void showCustomisationDialog (ToolbarItemFactory& factory,
  32138. const int optionFlags = allCustomisationOptionsEnabled);
  32139. /** Turns on or off the toolbar's editing mode, in which its items can be
  32140. rearranged by the user.
  32141. (In most cases it's easier just to use showCustomisationDialog() instead of
  32142. trying to enable editing directly).
  32143. @see ToolbarItemPalette
  32144. */
  32145. void setEditingActive (const bool editingEnabled);
  32146. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  32147. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32148. methods.
  32149. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32150. */
  32151. enum ColourIds
  32152. {
  32153. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  32154. more control over this, override LookAndFeel::paintToolbarBackground(). */
  32155. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  32156. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  32157. over them. */
  32158. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  32159. held down on them. */
  32160. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  32161. when the style is set to iconsWithText or textOnly. */
  32162. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  32163. the customisation dialog is active and the mouse moves over them. */
  32164. };
  32165. /** Returns a string that represents the toolbar's current set of items.
  32166. This lets you later restore the same item layout using restoreFromString().
  32167. @see restoreFromString
  32168. */
  32169. const String toString() const;
  32170. /** Restores a set of items that was previously stored in a string by the toString()
  32171. method.
  32172. The factory object is used to create any item components that are needed.
  32173. @see toString
  32174. */
  32175. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  32176. const String& savedVersion);
  32177. /** @internal */
  32178. void paint (Graphics& g);
  32179. /** @internal */
  32180. void resized();
  32181. /** @internal */
  32182. void buttonClicked (Button*);
  32183. /** @internal */
  32184. void mouseDown (const MouseEvent&);
  32185. /** @internal */
  32186. bool isInterestedInDragSource (const String&, Component*);
  32187. /** @internal */
  32188. void itemDragMove (const String&, Component*, int, int);
  32189. /** @internal */
  32190. void itemDragExit (const String&, Component*);
  32191. /** @internal */
  32192. void itemDropped (const String&, Component*, int, int);
  32193. /** @internal */
  32194. void updateAllItemPositions (const bool animate);
  32195. /** @internal */
  32196. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  32197. juce_UseDebuggingNewOperator
  32198. private:
  32199. Button* missingItemsButton;
  32200. bool vertical, isEditingActive;
  32201. ToolbarItemStyle toolbarStyle;
  32202. ComponentAnimator animator;
  32203. friend class MissingItemsComponent;
  32204. Array <ToolbarItemComponent*> items;
  32205. friend class ItemDragAndDropOverlayComponent;
  32206. static const tchar* const toolbarDragDescriptor;
  32207. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  32208. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  32209. Toolbar (const Toolbar&);
  32210. const Toolbar& operator= (const Toolbar&);
  32211. };
  32212. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  32213. /********* End of inlined file: juce_Toolbar.h *********/
  32214. class ItemDragAndDropOverlayComponent;
  32215. /**
  32216. A component that can be used as one of the items in a Toolbar.
  32217. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  32218. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  32219. class for further info about creating them.
  32220. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  32221. components too. To do this, set the value of isBeingUsedAsAButton to false when
  32222. calling the constructor, and override contentAreaChanged(), in which you can position
  32223. any sub-components you need to add.
  32224. To add basic buttons without writing a special subclass, have a look at the
  32225. ToolbarButton class.
  32226. @see ToolbarButton, Toolbar, ToolbarItemFactory
  32227. */
  32228. class JUCE_API ToolbarItemComponent : public Button
  32229. {
  32230. public:
  32231. /** Constructor.
  32232. @param itemId the ID of the type of toolbar item which this represents
  32233. @param labelText the text to display if the toolbar's style is set to
  32234. Toolbar::iconsWithText or Toolbar::textOnly
  32235. @param isBeingUsedAsAButton set this to false if you don't want the button
  32236. to draw itself with button over/down states when the mouse
  32237. moves over it or clicks
  32238. */
  32239. ToolbarItemComponent (const int itemId,
  32240. const String& labelText,
  32241. const bool isBeingUsedAsAButton);
  32242. /** Destructor. */
  32243. ~ToolbarItemComponent();
  32244. /** Returns the item type ID that this component represents.
  32245. This value is in the constructor.
  32246. */
  32247. int getItemId() const throw() { return itemId; }
  32248. /** Returns the toolbar that contains this component, or 0 if it's not currently
  32249. inside one.
  32250. */
  32251. Toolbar* getToolbar() const;
  32252. /** Returns true if this component is currently inside a toolbar which is vertical.
  32253. @see Toolbar::isVertical
  32254. */
  32255. bool isToolbarVertical() const;
  32256. /** Returns the current style setting of this item.
  32257. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  32258. @see setStyle, Toolbar::getStyle
  32259. */
  32260. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32261. /** Changes the current style setting of this item.
  32262. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  32263. by the toolbar that holds this item.
  32264. @see setStyle, Toolbar::setStyle
  32265. */
  32266. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  32267. /** Returns the area of the component that should be used to display the button image or
  32268. other contents of the item.
  32269. This content area may change when the item's style changes, and may leave a space around the
  32270. edge of the component where the text label can be shown.
  32271. @see contentAreaChanged
  32272. */
  32273. const Rectangle getContentArea() const throw() { return contentArea; }
  32274. /** This method must return the size criteria for this item, based on a given toolbar
  32275. size and orientation.
  32276. The preferredSize, minSize and maxSize values must all be set by your implementation
  32277. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  32278. toolbar, they refer to the item's height.
  32279. The preferredSize is the size that the component would like to be, and this must be
  32280. between the min and max sizes. For a fixed-size item, simply set all three variables to
  32281. the same value.
  32282. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  32283. Toolbar::getThickness().
  32284. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  32285. vertically.
  32286. */
  32287. virtual bool getToolbarItemSizes (int toolbarThickness,
  32288. bool isToolbarVertical,
  32289. int& preferredSize,
  32290. int& minSize,
  32291. int& maxSize) = 0;
  32292. /** Your subclass should use this method to draw its content area.
  32293. The graphics object that is passed-in will have been clipped and had its origin
  32294. moved to fit the content area as specified get getContentArea(). The width and height
  32295. parameters are the width and height of the content area.
  32296. If the component you're writing isn't a button, you can just do nothing in this method.
  32297. */
  32298. virtual void paintButtonArea (Graphics& g,
  32299. int width, int height,
  32300. bool isMouseOver, bool isMouseDown) = 0;
  32301. /** Callback to indicate that the content area of this item has changed.
  32302. This might be because the component was resized, or because the style changed and
  32303. the space needed for the text label is different.
  32304. See getContentArea() for a description of what the area is.
  32305. */
  32306. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  32307. /** Editing modes.
  32308. These are used by setEditingMode(), but will be rarely needed in user code.
  32309. */
  32310. enum ToolbarEditingMode
  32311. {
  32312. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  32313. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  32314. customisation mode, and the items can be dragged around. */
  32315. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  32316. dragged onto a toolbar to add it to that bar.*/
  32317. };
  32318. /** Changes the editing mode of this component.
  32319. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32320. and is unlikely to be of much use in end-user-code.
  32321. */
  32322. void setEditingMode (const ToolbarEditingMode newMode);
  32323. /** Returns the current editing mode of this component.
  32324. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32325. and is unlikely to be of much use in end-user-code.
  32326. */
  32327. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  32328. /** @internal */
  32329. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  32330. /** @internal */
  32331. void resized();
  32332. juce_UseDebuggingNewOperator
  32333. private:
  32334. friend class Toolbar;
  32335. friend class ItemDragAndDropOverlayComponent;
  32336. const int itemId;
  32337. ToolbarEditingMode mode;
  32338. Toolbar::ToolbarItemStyle toolbarStyle;
  32339. Component* overlayComp;
  32340. int dragOffsetX, dragOffsetY;
  32341. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  32342. Rectangle contentArea;
  32343. ToolbarItemComponent (const ToolbarItemComponent&);
  32344. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  32345. };
  32346. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32347. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  32348. /**
  32349. A type of button designed to go on a toolbar.
  32350. This simple button can have two Drawable objects specified - one for normal
  32351. use and another one (optionally) for the button's "on" state if it's a
  32352. toggle button.
  32353. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  32354. */
  32355. class JUCE_API ToolbarButton : public ToolbarItemComponent
  32356. {
  32357. public:
  32358. /** Creates a ToolbarButton.
  32359. @param itemId the ID for this toolbar item type. This is passed through to the
  32360. ToolbarItemComponent constructor
  32361. @param labelText the text to display on the button (if the toolbar is using a style
  32362. that shows text labels). This is passed through to the
  32363. ToolbarItemComponent constructor
  32364. @param normalImage a drawable object that the button should use as its icon. The object
  32365. that is passed-in here will be kept by this object and will be
  32366. deleted when no longer needed or when this button is deleted.
  32367. @param toggledOnImage a drawable object that the button can use as its icon if the button
  32368. is in a toggled-on state (see the Button::getToggleState() method). If
  32369. 0 is passed-in here, then the normal image will be used instead, regardless
  32370. of the toggle state. The object that is passed-in here will be kept by
  32371. this object and will be deleted when no longer needed or when this button
  32372. is deleted.
  32373. */
  32374. ToolbarButton (const int itemId,
  32375. const String& labelText,
  32376. Drawable* const normalImage,
  32377. Drawable* const toggledOnImage);
  32378. /** Destructor. */
  32379. ~ToolbarButton();
  32380. /** @internal */
  32381. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  32382. int& minSize, int& maxSize);
  32383. /** @internal */
  32384. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  32385. /** @internal */
  32386. void contentAreaChanged (const Rectangle& newBounds);
  32387. juce_UseDebuggingNewOperator
  32388. private:
  32389. Drawable* const normalImage;
  32390. Drawable* const toggledOnImage;
  32391. ToolbarButton (const ToolbarButton&);
  32392. const ToolbarButton& operator= (const ToolbarButton&);
  32393. };
  32394. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32395. /********* End of inlined file: juce_ToolbarButton.h *********/
  32396. #endif
  32397. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  32398. #endif
  32399. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  32400. /********* Start of inlined file: juce_GlowEffect.h *********/
  32401. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  32402. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  32403. /**
  32404. A component effect that adds a coloured blur around the component's contents.
  32405. (This will only work on non-opaque components).
  32406. @see Component::setComponentEffect, DropShadowEffect
  32407. */
  32408. class JUCE_API GlowEffect : public ImageEffectFilter
  32409. {
  32410. public:
  32411. /** Creates a default 'glow' effect.
  32412. To customise its appearance, use the setGlowProperties() method.
  32413. */
  32414. GlowEffect();
  32415. /** Destructor. */
  32416. ~GlowEffect();
  32417. /** Sets the glow's radius and colour.
  32418. The radius is how large the blur should be, and the colour is
  32419. used to render it (for a less intense glow, lower the colour's
  32420. opacity).
  32421. */
  32422. void setGlowProperties (const float newRadius,
  32423. const Colour& newColour);
  32424. /** @internal */
  32425. void applyEffect (Image& sourceImage, Graphics& destContext);
  32426. juce_UseDebuggingNewOperator
  32427. private:
  32428. float radius;
  32429. Colour colour;
  32430. };
  32431. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  32432. /********* End of inlined file: juce_GlowEffect.h *********/
  32433. #endif
  32434. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  32435. #endif
  32436. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32437. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  32438. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32439. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32440. /**
  32441. An effect filter that reduces the image's opacity.
  32442. This can be used to make a component (and its child components) more
  32443. transparent.
  32444. @see Component::setComponentEffect
  32445. */
  32446. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  32447. {
  32448. public:
  32449. /** Creates the effect object.
  32450. The opacity of the component to which the effect is applied will be
  32451. scaled by the given factor (in the range 0 to 1.0f).
  32452. */
  32453. ReduceOpacityEffect (const float opacity = 1.0f);
  32454. /** Destructor. */
  32455. ~ReduceOpacityEffect();
  32456. /** Sets how much to scale the component's opacity.
  32457. @param newOpacity should be between 0 and 1.0f
  32458. */
  32459. void setOpacity (const float newOpacity);
  32460. /** @internal */
  32461. void applyEffect (Image& sourceImage, Graphics& destContext);
  32462. juce_UseDebuggingNewOperator
  32463. private:
  32464. float opacity;
  32465. };
  32466. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32467. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  32468. #endif
  32469. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  32470. #endif
  32471. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32472. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  32473. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32474. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32475. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  32476. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32477. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32478. /**
  32479. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  32480. command in a ApplicationCommandManager.
  32481. Normally, you won't actually create a KeyPressMappingSet directly, because
  32482. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  32483. you'd create yourself an ApplicationCommandManager, and call its
  32484. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  32485. KeyPressMappingSet.
  32486. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  32487. to the top-level component for which you want to handle keystrokes. So for example:
  32488. @code
  32489. class MyMainWindow : public Component
  32490. {
  32491. ApplicationCommandManager* myCommandManager;
  32492. public:
  32493. MyMainWindow()
  32494. {
  32495. myCommandManager = new ApplicationCommandManager();
  32496. // first, make sure the command manager has registered all the commands that its
  32497. // targets can perform..
  32498. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  32499. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  32500. // this will use the command manager to initialise the KeyPressMappingSet with
  32501. // the default keypresses that were specified when the targets added their commands
  32502. // to the manager.
  32503. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  32504. // having set up the default key-mappings, you might now want to load the last set
  32505. // of mappings that the user configured.
  32506. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  32507. // Now tell our top-level window to send any keypresses that arrive to the
  32508. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  32509. addKeyListener (myCommandManager->getKeyMappings());
  32510. }
  32511. ...
  32512. }
  32513. @endcode
  32514. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  32515. register to be told when a command or mapping is added, removed, etc.
  32516. There's also a UI component called KeyMappingEditorComponent that can be used
  32517. to easily edit the key mappings.
  32518. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  32519. */
  32520. class JUCE_API KeyPressMappingSet : public KeyListener,
  32521. public ChangeBroadcaster,
  32522. public FocusChangeListener
  32523. {
  32524. public:
  32525. /** Creates a KeyPressMappingSet for a given command manager.
  32526. Normally, you won't actually create a KeyPressMappingSet directly, because
  32527. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  32528. best thing to do is to create your ApplicationCommandManager, and use the
  32529. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  32530. When a suitable keypress happens, the manager's invoke() method will be
  32531. used to invoke the appropriate command.
  32532. @see ApplicationCommandManager
  32533. */
  32534. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  32535. /** Creates an copy of a KeyPressMappingSet. */
  32536. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  32537. /** Destructor. */
  32538. ~KeyPressMappingSet();
  32539. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  32540. /** Returns a list of keypresses that are assigned to a particular command.
  32541. @param commandID the command's ID
  32542. */
  32543. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  32544. /** Assigns a keypress to a command.
  32545. If the keypress is already assigned to a different command, it will first be
  32546. removed from that command, to avoid it triggering multiple functions.
  32547. @param commandID the ID of the command that you want to add a keypress to. If
  32548. this is 0, the keypress will be removed from anything that it
  32549. was previously assigned to, but not re-assigned
  32550. @param newKeyPress the new key-press
  32551. @param insertIndex if this is less than zero, the key will be appended to the
  32552. end of the list of keypresses; otherwise the new keypress will
  32553. be inserted into the existing list at this index
  32554. */
  32555. void addKeyPress (const CommandID commandID,
  32556. const KeyPress& newKeyPress,
  32557. int insertIndex = -1) throw();
  32558. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  32559. @see resetToDefaultMapping
  32560. */
  32561. void resetToDefaultMappings() throw();
  32562. /** Resets all key-mappings to the defaults for a particular command.
  32563. @see resetToDefaultMappings
  32564. */
  32565. void resetToDefaultMapping (const CommandID commandID) throw();
  32566. /** Removes all keypresses that are assigned to any commands. */
  32567. void clearAllKeyPresses() throw();
  32568. /** Removes all keypresses that are assigned to a particular command. */
  32569. void clearAllKeyPresses (const CommandID commandID) throw();
  32570. /** Removes one of the keypresses that are assigned to a command.
  32571. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  32572. which the keyPressIndex refers.
  32573. */
  32574. void removeKeyPress (const CommandID commandID,
  32575. const int keyPressIndex) throw();
  32576. /** Removes a keypress from any command that it may be assigned to.
  32577. */
  32578. void removeKeyPress (const KeyPress& keypress) throw();
  32579. /** Returns true if the given command is linked to this key. */
  32580. bool containsMapping (const CommandID commandID,
  32581. const KeyPress& keyPress) const throw();
  32582. /** Looks for a command that corresponds to a keypress.
  32583. @returns the UID of the command or 0 if none was found
  32584. */
  32585. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  32586. /** Tries to recreate the mappings from a previously stored state.
  32587. The XML passed in must have been created by the createXml() method.
  32588. If the stored state makes any reference to commands that aren't
  32589. currently available, these will be ignored.
  32590. If the set of mappings being loaded was a set of differences (using createXml (true)),
  32591. then this will call resetToDefaultMappings() and then merge the saved mappings
  32592. on top. If the saved set was created with createXml (false), then this method
  32593. will first clear all existing mappings and load the saved ones as a complete set.
  32594. @returns true if it manages to load the XML correctly
  32595. @see createXml
  32596. */
  32597. bool restoreFromXml (const XmlElement& xmlVersion);
  32598. /** Creates an XML representation of the current mappings.
  32599. This will produce a lump of XML that can be later reloaded using
  32600. restoreFromXml() to recreate the current mapping state.
  32601. The object that is returned must be deleted by the caller.
  32602. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  32603. will be saved into the XML. If it's true, then the XML will
  32604. only store the differences between the current mappings and
  32605. the default mappings you'd get from calling resetToDefaultMappings().
  32606. The advantage of saving a set of differences from the default is that
  32607. if you change the default mappings (in a new version of your app, for
  32608. example), then these will be merged into a user's saved preferences.
  32609. @see restoreFromXml
  32610. */
  32611. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  32612. /** @internal */
  32613. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  32614. /** @internal */
  32615. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  32616. /** @internal */
  32617. void globalFocusChanged (Component* focusedComponent);
  32618. juce_UseDebuggingNewOperator
  32619. private:
  32620. ApplicationCommandManager* commandManager;
  32621. struct CommandMapping
  32622. {
  32623. CommandID commandID;
  32624. Array <KeyPress> keypresses;
  32625. bool wantsKeyUpDownCallbacks;
  32626. };
  32627. OwnedArray <CommandMapping> mappings;
  32628. struct KeyPressTime
  32629. {
  32630. KeyPress key;
  32631. uint32 timeWhenPressed;
  32632. };
  32633. OwnedArray <KeyPressTime> keysDown;
  32634. void handleMessage (const Message& message);
  32635. void invokeCommand (const CommandID commandID,
  32636. const KeyPress& keyPress,
  32637. const bool isKeyDown,
  32638. const int millisecsSinceKeyPressed,
  32639. Component* const originatingComponent) const;
  32640. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  32641. };
  32642. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32643. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  32644. /********* Start of inlined file: juce_TreeView.h *********/
  32645. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  32646. #define __JUCE_TREEVIEW_JUCEHEADER__
  32647. class TreeView;
  32648. /**
  32649. An item in a treeview.
  32650. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  32651. own sub-items.
  32652. To implement an item that contains sub-items, override the itemOpennessChanged()
  32653. method so that when it is opened, it adds the new sub-items to itself using the
  32654. addSubItem method. Depending on the nature of the item it might choose to only
  32655. do this the first time it's opened, or it might want to refresh itself each time.
  32656. It also has the option of deleting its sub-items when it is closed, or leaving them
  32657. in place.
  32658. */
  32659. class JUCE_API TreeViewItem
  32660. {
  32661. public:
  32662. /** Constructor. */
  32663. TreeViewItem();
  32664. /** Destructor. */
  32665. virtual ~TreeViewItem();
  32666. /** Returns the number of sub-items that have been added to this item.
  32667. Note that this doesn't mean much if the node isn't open.
  32668. @see getSubItem, mightContainSubItems, addSubItem
  32669. */
  32670. int getNumSubItems() const throw();
  32671. /** Returns one of the item's sub-items.
  32672. Remember that the object returned might get deleted at any time when its parent
  32673. item is closed or refreshed, depending on the nature of the items you're using.
  32674. @see getNumSubItems
  32675. */
  32676. TreeViewItem* getSubItem (const int index) const throw();
  32677. /** Removes any sub-items. */
  32678. void clearSubItems();
  32679. /** Adds a sub-item.
  32680. @param newItem the object to add to the item's sub-item list. Once added, these can be
  32681. found using getSubItem(). When the items are later removed with
  32682. removeSubItem() (or when this item is deleted), they will be deleted.
  32683. @param insertPosition the index which the new item should have when it's added. If this
  32684. value is less than 0, the item will be added to the end of the list.
  32685. */
  32686. void addSubItem (TreeViewItem* const newItem,
  32687. const int insertPosition = -1);
  32688. /** Removes one of the sub-items.
  32689. @param index the item to remove
  32690. @param deleteItem if true, the item that is removed will also be deleted.
  32691. */
  32692. void removeSubItem (const int index,
  32693. const bool deleteItem = true);
  32694. /** Returns the TreeView to which this item belongs. */
  32695. TreeView* getOwnerView() const throw() { return ownerView; }
  32696. /** Returns the item within which this item is contained. */
  32697. TreeViewItem* getParentItem() const throw() { return parentItem; }
  32698. /** True if this item is currently open in the treeview. */
  32699. bool isOpen() const throw();
  32700. /** Opens or closes the item.
  32701. When opened or closed, the item's itemOpennessChanged() method will be called,
  32702. and a subclass should use this callback to create and add any sub-items that
  32703. it needs to.
  32704. @see itemOpennessChanged, mightContainSubItems
  32705. */
  32706. void setOpen (const bool shouldBeOpen);
  32707. /** True if this item is currently selected.
  32708. Use this when painting the node, to decide whether to draw it as selected or not.
  32709. */
  32710. bool isSelected() const throw();
  32711. /** Selects or deselects the item.
  32712. This will cause a callback to itemSelectionChanged()
  32713. */
  32714. void setSelected (const bool shouldBeSelected,
  32715. const bool deselectOtherItemsFirst);
  32716. /** Returns the rectangle that this item occupies.
  32717. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  32718. top-left of the TreeView comp, so this will depend on the scroll-position of
  32719. the tree. If false, it is relative to the top-left of the topmost item in the
  32720. tree (so this would be unaffected by scrolling the view).
  32721. */
  32722. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  32723. /** Sends a signal to the treeview to make it refresh itself.
  32724. Call this if your items have changed and you want the tree to update to reflect
  32725. this.
  32726. */
  32727. void treeHasChanged() const throw();
  32728. /** Sends a repaint message to redraw just this item.
  32729. Note that you should only call this if you want to repaint a superficial change. If
  32730. you're altering the tree's nodes, you should instead call treeHasChanged().
  32731. */
  32732. void repaintItem() const;
  32733. /** Returns the row number of this item in the tree.
  32734. The row number of an item will change according to which items are open.
  32735. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  32736. */
  32737. int getRowNumberInTree() const throw();
  32738. /** Returns true if all the item's parent nodes are open.
  32739. This is useful to check whether the item might actually be visible or not.
  32740. */
  32741. bool areAllParentsOpen() const throw();
  32742. /** Changes whether lines are drawn to connect any sub-items to this item.
  32743. By default, line-drawing is turned on.
  32744. */
  32745. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  32746. /** Tells the tree whether this item can potentially be opened.
  32747. If your item could contain sub-items, this should return true; if it returns
  32748. false then the tree will not try to open the item. This determines whether or
  32749. not the item will be drawn with a 'plus' button next to it.
  32750. */
  32751. virtual bool mightContainSubItems() = 0;
  32752. /** Returns a string to uniquely identify this item.
  32753. If you're planning on using the TreeView::getOpennessState() method, then
  32754. these strings will be used to identify which nodes are open. The string
  32755. should be unique amongst the item's sibling items, but it's ok for there
  32756. to be duplicates at other levels of the tree.
  32757. If you're not going to store the state, then it's ok not to bother implementing
  32758. this method.
  32759. */
  32760. virtual const String getUniqueName() const;
  32761. /** Called when an item is opened or closed.
  32762. When setOpen() is called and the item has specified that it might
  32763. have sub-items with the mightContainSubItems() method, this method
  32764. is called to let the item create or manage its sub-items.
  32765. So when this is called with isNowOpen set to true (i.e. when the item is being
  32766. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  32767. refresh its sub-item list.
  32768. When this is called with isNowOpen set to false, the subclass might want
  32769. to use clearSubItems() to save on space, or it might choose to leave them,
  32770. depending on the nature of the tree.
  32771. You could also use this callback as a trigger to start a background process
  32772. which asynchronously creates sub-items and adds them, if that's more
  32773. appropriate for the task in hand.
  32774. @see mightContainSubItems
  32775. */
  32776. virtual void itemOpennessChanged (bool isNowOpen);
  32777. /** Must return the width required by this item.
  32778. If your item needs to have a particular width in pixels, return that value; if
  32779. you'd rather have it just fill whatever space is available in the treeview,
  32780. return -1.
  32781. If all your items return -1, no horizontal scrollbar will be shown, but if any
  32782. items have fixed widths and extend beyond the width of the treeview, a
  32783. scrollbar will appear.
  32784. Each item can be a different width, but if they change width, you should call
  32785. treeHasChanged() to update the tree.
  32786. */
  32787. virtual int getItemWidth() const { return -1; }
  32788. /** Must return the height required by this item.
  32789. This is the height in pixels that the item will take up. Items in the tree
  32790. can be different heights, but if they change height, you should call
  32791. treeHasChanged() to update the tree.
  32792. */
  32793. virtual int getItemHeight() const { return 20; }
  32794. /** You can override this method to return false if you don't want to allow the
  32795. user to select this item.
  32796. */
  32797. virtual bool canBeSelected() const { return true; }
  32798. /** Creates a component that will be used to represent this item.
  32799. You don't have to implement this method - if it returns 0 then no component
  32800. will be used for the item, and you can just draw it using the paintItem()
  32801. callback. But if you do return a component, it will be positioned in the
  32802. treeview so that it can be used to represent this item.
  32803. The component returned will be managed by the treeview, so always return
  32804. a new component, and don't keep a reference to it, as the treeview will
  32805. delete it later when it goes off the screen or is no longer needed. Also
  32806. bear in mind that if the component keeps a reference to the item that
  32807. created it, that item could be deleted before the component. Its position
  32808. and size will be completely managed by the tree, so don't attempt to move it
  32809. around.
  32810. Something you may want to do with your component is to give it a pointer to
  32811. the TreeView that created it. This is perfectly safe, and there's no danger
  32812. of it becoming a dangling pointer because the TreeView will always delete
  32813. the component before it is itself deleted.
  32814. As long as you stick to these rules you can return whatever kind of
  32815. component you like. It's most useful if you're doing things like drag-and-drop
  32816. of items, or want to use a Label component to edit item names, etc.
  32817. */
  32818. virtual Component* createItemComponent() { return 0; }
  32819. /** Draws the item's contents.
  32820. You can choose to either implement this method and draw each item, or you
  32821. can use createItemComponent() to create a component that will represent the
  32822. item.
  32823. If all you need in your tree is to be able to draw the items and detect when
  32824. the user selects or double-clicks one of them, it's probably enough to
  32825. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  32826. complicated interactions, you may need to use createItemComponent() instead.
  32827. @param g the graphics context to draw into
  32828. @param width the width of the area available for drawing
  32829. @param height the height of the area available for drawing
  32830. */
  32831. virtual void paintItem (Graphics& g, int width, int height);
  32832. /** Draws the item's open/close button.
  32833. If you don't implement this method, the default behaviour is to
  32834. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  32835. it for custom effects.
  32836. */
  32837. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  32838. /** Called when the user clicks on this item.
  32839. If you're using createItemComponent() to create a custom component for the
  32840. item, the mouse-clicks might not make it through to the treeview, but this
  32841. is how you find out about clicks when just drawing each item individually.
  32842. The associated mouse-event details are passed in, so you can find out about
  32843. which button, where it was, etc.
  32844. @see itemDoubleClicked
  32845. */
  32846. virtual void itemClicked (const MouseEvent& e);
  32847. /** Called when the user double-clicks on this item.
  32848. If you're using createItemComponent() to create a custom component for the
  32849. item, the mouse-clicks might not make it through to the treeview, but this
  32850. is how you find out about clicks when just drawing each item individually.
  32851. The associated mouse-event details are passed in, so you can find out about
  32852. which button, where it was, etc.
  32853. If not overridden, the base class method here will open or close the item as
  32854. if the 'plus' button had been clicked.
  32855. @see itemClicked
  32856. */
  32857. virtual void itemDoubleClicked (const MouseEvent& e);
  32858. /** Called when the item is selected or deselected.
  32859. Use this if you want to do something special when the item's selectedness
  32860. changes. By default it'll get repainted when this happens.
  32861. */
  32862. virtual void itemSelectionChanged (bool isNowSelected);
  32863. /** The item can return a tool tip string here if it wants to.
  32864. @see TooltipClient
  32865. */
  32866. virtual const String getTooltip();
  32867. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  32868. If this returns a non-empty name then when the user drags an item, the treeview will
  32869. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  32870. a drag-and-drop operation, using this string as the source description, with the treeview
  32871. itself as the source component.
  32872. If you need more complex drag-and-drop behaviour, you can use custom components for
  32873. the items, and use those to trigger the drag.
  32874. @see DragAndDropContainer::startDragging
  32875. */
  32876. virtual const String getDragSourceDescription();
  32877. /** Sets a flag to indicate that the item wants to be allowed
  32878. to draw all the way across to the left edge of the treeview.
  32879. By default this is false, which means that when the paintItem()
  32880. method is called, its graphics context is clipped to only allow
  32881. drawing within the item's rectangle. If this flag is set to true,
  32882. then the graphics context isn't clipped on its left side, so it
  32883. can draw all the way across to the left margin. Note that the
  32884. context will still have its origin in the same place though, so
  32885. the coordinates of anything to its left will be negative. It's
  32886. mostly useful if you want to draw a wider bar behind the
  32887. highlighted item.
  32888. */
  32889. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  32890. juce_UseDebuggingNewOperator
  32891. private:
  32892. TreeView* ownerView;
  32893. TreeViewItem* parentItem;
  32894. OwnedArray <TreeViewItem> subItems;
  32895. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  32896. int uid;
  32897. bool selected : 1;
  32898. bool redrawNeeded : 1;
  32899. bool drawLinesInside : 1;
  32900. bool drawsInLeftMargin : 1;
  32901. unsigned int openness : 2;
  32902. friend class TreeView;
  32903. friend class TreeViewContentComponent;
  32904. void updatePositions (int newY);
  32905. int getIndentX() const throw();
  32906. void setOwnerView (TreeView* const newOwner) throw();
  32907. void paintRecursively (Graphics& g, int width);
  32908. TreeViewItem* findItemRecursively (int y) throw();
  32909. TreeViewItem* getDeepestOpenParentItem() throw();
  32910. void restoreFromXml (const XmlElement& e);
  32911. XmlElement* createXmlOpenness() const;
  32912. bool isLastOfSiblings() const throw();
  32913. TreeViewItem* getTopLevelItem() throw();
  32914. int getNumRows() const throw();
  32915. TreeViewItem* getItemOnRow (int index) throw();
  32916. void deselectAllRecursively();
  32917. int countSelectedItemsRecursively() const throw();
  32918. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  32919. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  32920. TreeViewItem (const TreeViewItem&);
  32921. const TreeViewItem& operator= (const TreeViewItem&);
  32922. };
  32923. /**
  32924. A tree-view component.
  32925. Use one of these to hold and display a structure of TreeViewItem objects.
  32926. */
  32927. class JUCE_API TreeView : public Component,
  32928. public SettableTooltipClient,
  32929. private AsyncUpdater
  32930. {
  32931. public:
  32932. /** Creates an empty treeview.
  32933. Once you've got a treeview component, you'll need to give it something to
  32934. display, using the setRootItem() method.
  32935. */
  32936. TreeView (const String& componentName = String::empty);
  32937. /** Destructor. */
  32938. ~TreeView();
  32939. /** Sets the item that is displayed in the treeview.
  32940. A tree has a single root item which contains as many sub-items as it needs. If
  32941. you want the tree to contain a number of root items, you should still use a single
  32942. root item above these, but hide it using setRootItemVisible().
  32943. You can pass in 0 to this method to clear the tree and remove its current root item.
  32944. The object passed in will not be deleted by the treeview, it's up to the caller
  32945. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  32946. this item until you've removed it from the tree, either by calling setRootItem (0),
  32947. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  32948. to delete it.
  32949. */
  32950. void setRootItem (TreeViewItem* const newRootItem);
  32951. /** Returns the tree's root item.
  32952. This will be the last object passed to setRootItem(), or 0 if none has been set.
  32953. */
  32954. TreeViewItem* getRootItem() const throw() { return rootItem; }
  32955. /** This will remove and delete the current root item.
  32956. It's a convenient way of deleting the item and calling setRootItem (0).
  32957. */
  32958. void deleteRootItem();
  32959. /** Changes whether the tree's root item is shown or not.
  32960. If the root item is hidden, only its sub-items will be shown in the treeview - this
  32961. lets you make the tree look as if it's got many root items. If it's hidden, this call
  32962. will also make sure the root item is open (otherwise the treeview would look empty).
  32963. */
  32964. void setRootItemVisible (const bool shouldBeVisible);
  32965. /** Returns true if the root item is visible.
  32966. @see setRootItemVisible
  32967. */
  32968. bool isRootItemVisible() const throw() { return rootItemVisible; }
  32969. /** Sets whether items are open or closed by default.
  32970. Normally, items are closed until the user opens them, but you can use this
  32971. to make them default to being open until explicitly closed.
  32972. @see areItemsOpenByDefault
  32973. */
  32974. void setDefaultOpenness (const bool isOpenByDefault);
  32975. /** Returns true if the tree's items default to being open.
  32976. @see setDefaultOpenness
  32977. */
  32978. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  32979. /** This sets a flag to indicate that the tree can be used for multi-selection.
  32980. You can always select multiple items internally by calling the
  32981. TreeViewItem::setSelected() method, but this flag indicates whether the user
  32982. is allowed to multi-select by clicking on the tree.
  32983. By default it is disabled.
  32984. @see isMultiSelectEnabled
  32985. */
  32986. void setMultiSelectEnabled (const bool canMultiSelect);
  32987. /** Returns whether multi-select has been enabled for the tree.
  32988. @see setMultiSelectEnabled
  32989. */
  32990. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  32991. /** Sets a flag to indicate whether to hide the open/close buttons.
  32992. @see areOpenCloseButtonsVisible
  32993. */
  32994. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  32995. /** Returns whether open/close buttons are shown.
  32996. @see setOpenCloseButtonsVisible
  32997. */
  32998. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  32999. /** Deselects any items that are currently selected. */
  33000. void clearSelectedItems();
  33001. /** Returns the number of items that are currently selected.
  33002. @see getSelectedItem, clearSelectedItems
  33003. */
  33004. int getNumSelectedItems() const throw();
  33005. /** Returns one of the selected items in the tree.
  33006. @param index the index, 0 to (getNumSelectedItems() - 1)
  33007. */
  33008. TreeViewItem* getSelectedItem (const int index) const throw();
  33009. /** Returns the number of rows the tree is using.
  33010. This will depend on which items are open.
  33011. @see TreeViewItem::getRowNumberInTree()
  33012. */
  33013. int getNumRowsInTree() const;
  33014. /** Returns the item on a particular row of the tree.
  33015. If the index is out of range, this will return 0.
  33016. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  33017. */
  33018. TreeViewItem* getItemOnRow (int index) const;
  33019. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  33020. void scrollToKeepItemVisible (TreeViewItem* item);
  33021. /** Returns the treeview's Viewport object. */
  33022. Viewport* getViewport() const throw() { return viewport; }
  33023. /** Returns the number of pixels by which each nested level of the tree is indented.
  33024. @see setIndentSize
  33025. */
  33026. int getIndentSize() const throw() { return indentSize; }
  33027. /** Changes the distance by which each nested level of the tree is indented.
  33028. @see getIndentSize
  33029. */
  33030. void setIndentSize (const int newIndentSize);
  33031. /** Saves the current state of open/closed nodes so it can be restored later.
  33032. This takes a snapshot of which nodes have been explicitly opened or closed,
  33033. and records it as XML. To identify node objects it uses the
  33034. TreeViewItem::getUniqueName() method to create named paths. This
  33035. means that the same state of open/closed nodes can be restored to a
  33036. completely different instance of the tree, as long as it contains nodes
  33037. whose unique names are the same.
  33038. The caller is responsible for deleting the object that is returned.
  33039. @param alsoIncludeScrollPosition if this is true, the state will also
  33040. include information about where the
  33041. tree has been scrolled to vertically,
  33042. so this can also be restored
  33043. @see restoreOpennessState
  33044. */
  33045. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  33046. /** Restores a previously saved arrangement of open/closed nodes.
  33047. This will try to restore a snapshot of the tree's state that was created by
  33048. the getOpennessState() method. If any of the nodes named in the original
  33049. XML aren't present in this tree, they will be ignored.
  33050. @see getOpennessState
  33051. */
  33052. void restoreOpennessState (const XmlElement& newState);
  33053. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  33054. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33055. methods.
  33056. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33057. */
  33058. enum ColourIds
  33059. {
  33060. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  33061. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  33062. };
  33063. /** @internal */
  33064. void paint (Graphics& g);
  33065. /** @internal */
  33066. void resized();
  33067. /** @internal */
  33068. bool keyPressed (const KeyPress& key);
  33069. /** @internal */
  33070. void colourChanged();
  33071. /** @internal */
  33072. void enablementChanged();
  33073. juce_UseDebuggingNewOperator
  33074. private:
  33075. friend class TreeViewItem;
  33076. friend class TreeViewContentComponent;
  33077. Viewport* viewport;
  33078. CriticalSection nodeAlterationLock;
  33079. TreeViewItem* rootItem;
  33080. int indentSize;
  33081. bool defaultOpenness : 1;
  33082. bool needsRecalculating : 1;
  33083. bool rootItemVisible : 1;
  33084. bool multiSelectEnabled : 1;
  33085. bool openCloseButtonsVisible : 1;
  33086. void itemsChanged() throw();
  33087. void handleAsyncUpdate();
  33088. void moveSelectedRow (int delta);
  33089. void updateButtonUnderMouse (const MouseEvent& e);
  33090. TreeView (const TreeView&);
  33091. const TreeView& operator= (const TreeView&);
  33092. };
  33093. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  33094. /********* End of inlined file: juce_TreeView.h *********/
  33095. /**
  33096. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  33097. object.
  33098. @see KeyPressMappingSet
  33099. */
  33100. class JUCE_API KeyMappingEditorComponent : public Component,
  33101. public TreeViewItem,
  33102. public ChangeListener,
  33103. private ButtonListener
  33104. {
  33105. public:
  33106. /** Creates a KeyMappingEditorComponent.
  33107. @param mappingSet this is the set of mappings to display and
  33108. edit. Make sure the mappings object is not
  33109. deleted before this component!
  33110. @param showResetToDefaultButton if true, then at the bottom of the
  33111. list, the component will include a 'reset to
  33112. defaults' button.
  33113. */
  33114. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  33115. const bool showResetToDefaultButton);
  33116. /** Destructor. */
  33117. virtual ~KeyMappingEditorComponent();
  33118. /** Sets up the colours to use for parts of the component.
  33119. @param mainBackground colour to use for most of the background
  33120. @param textColour colour to use for the text
  33121. */
  33122. void setColours (const Colour& mainBackground,
  33123. const Colour& textColour);
  33124. /** Returns the KeyPressMappingSet that this component is acting upon.
  33125. */
  33126. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  33127. /** Can be overridden if some commands need to be excluded from the list.
  33128. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  33129. method to decide what to return, but you can override it to handle special cases.
  33130. */
  33131. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  33132. /** Can be overridden to indicate that some commands are shown as read-only.
  33133. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  33134. method to decide what to return, but you can override it to handle special cases.
  33135. */
  33136. virtual bool isCommandReadOnly (const CommandID commandID);
  33137. /** This can be overridden to let you change the format of the string used
  33138. to describe a keypress.
  33139. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  33140. keys that are triggered by something else externally. If you override the
  33141. method, be sure to let the base class's method handle keys you're not
  33142. interested in.
  33143. */
  33144. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  33145. /** @internal */
  33146. void parentHierarchyChanged();
  33147. /** @internal */
  33148. void resized();
  33149. /** @internal */
  33150. void changeListenerCallback (void*);
  33151. /** @internal */
  33152. bool mightContainSubItems();
  33153. /** @internal */
  33154. const String getUniqueName() const;
  33155. /** @internal */
  33156. void buttonClicked (Button* button);
  33157. juce_UseDebuggingNewOperator
  33158. private:
  33159. KeyPressMappingSet* mappings;
  33160. TreeView* tree;
  33161. friend class KeyMappingTreeViewItem;
  33162. friend class KeyCategoryTreeViewItem;
  33163. friend class KeyMappingItemComponent;
  33164. friend class KeyMappingChangeButton;
  33165. Colour backgroundColour, textColour;
  33166. TextButton* resetButton;
  33167. void assignNewKey (const CommandID commandID, int index);
  33168. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  33169. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  33170. };
  33171. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  33172. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  33173. #endif
  33174. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  33175. #endif
  33176. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  33177. #endif
  33178. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  33179. #endif
  33180. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  33181. #endif
  33182. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33183. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  33184. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33185. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33186. /********* Start of inlined file: juce_MenuBarModel.h *********/
  33187. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  33188. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  33189. class MenuBarModel;
  33190. /**
  33191. A class to receive callbacks when a MenuBarModel changes.
  33192. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  33193. */
  33194. class JUCE_API MenuBarModelListener
  33195. {
  33196. public:
  33197. /** Destructor. */
  33198. virtual ~MenuBarModelListener() {}
  33199. /** This callback is made when items are changed in the menu bar model.
  33200. */
  33201. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  33202. /** This callback is made when an application command is invoked that
  33203. is represented by one of the items in the menu bar model.
  33204. */
  33205. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  33206. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  33207. };
  33208. /**
  33209. A class for controlling MenuBar components.
  33210. This class is used to tell a MenuBar what menus to show, and to respond
  33211. to a menu being selected.
  33212. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  33213. */
  33214. class JUCE_API MenuBarModel : private AsyncUpdater,
  33215. private ApplicationCommandManagerListener
  33216. {
  33217. public:
  33218. MenuBarModel() throw();
  33219. /** Destructor. */
  33220. virtual ~MenuBarModel();
  33221. /** Call this when some of your menu items have changed.
  33222. This method will cause a callback to any MenuBarListener objects that
  33223. are registered with this model.
  33224. If this model is displaying items from an ApplicationCommandManager, you
  33225. can use the setApplicationCommandManagerToWatch() method to cause
  33226. change messages to be sent automatically when the ApplicationCommandManager
  33227. is changed.
  33228. @see addListener, removeListener, MenuBarListener
  33229. */
  33230. void menuItemsChanged();
  33231. /** Tells the menu bar to listen to the specified command manager, and to update
  33232. itself when the commands change.
  33233. This will also allow it to flash a menu name when a command from that menu
  33234. is invoked using a keystroke.
  33235. */
  33236. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  33237. /** Registers a listener for callbacks when the menu items in this model change.
  33238. The listener object will get callbacks when this object's menuItemsChanged()
  33239. method is called.
  33240. @see removeListener
  33241. */
  33242. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  33243. /** Removes a listener.
  33244. @see addListener
  33245. */
  33246. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  33247. /** This method must return a list of the names of the menus. */
  33248. virtual const StringArray getMenuBarNames() = 0;
  33249. /** This should return the popup menu to display for a given top-level menu.
  33250. @param topLevelMenuIndex the index of the top-level menu to show
  33251. @param menuName the name of the top-level menu item to show
  33252. */
  33253. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  33254. const String& menuName) = 0;
  33255. /** This is called when a menu item has been clicked on.
  33256. @param menuItemID the item ID of the PopupMenu item that was selected
  33257. @param topLevelMenuIndex the index of the top-level menu from which the item was
  33258. chosen (just in case you've used duplicate ID numbers
  33259. on more than one of the popup menus)
  33260. */
  33261. virtual void menuItemSelected (int menuItemID,
  33262. int topLevelMenuIndex) = 0;
  33263. #if JUCE_MAC || DOXYGEN
  33264. /** MAC ONLY - Sets the model that is currently being shown as the main
  33265. menu bar at the top of the screen on the Mac.
  33266. You can pass 0 to stop the current model being displayed. Be careful
  33267. not to delete a model while it is being used.
  33268. An optional extra menu can be specified, containing items to add to the top of
  33269. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  33270. an apple, it's the one next to it, with your application's name at the top
  33271. and the services menu etc on it). When one of these items is selected, the
  33272. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  33273. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  33274. object then newMenuBarModel must be non-null.
  33275. */
  33276. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  33277. const PopupMenu* extraAppleMenuItems = 0) throw();
  33278. /** MAC ONLY - Returns the menu model that is currently being shown as
  33279. the main menu bar.
  33280. */
  33281. static MenuBarModel* getMacMainMenu() throw();
  33282. #endif
  33283. /** @internal */
  33284. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  33285. /** @internal */
  33286. void applicationCommandListChanged();
  33287. /** @internal */
  33288. void handleAsyncUpdate();
  33289. juce_UseDebuggingNewOperator
  33290. private:
  33291. ApplicationCommandManager* manager;
  33292. SortedSet <void*> listeners;
  33293. MenuBarModel (const MenuBarModel&);
  33294. const MenuBarModel& operator= (const MenuBarModel&);
  33295. };
  33296. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  33297. /********* End of inlined file: juce_MenuBarModel.h *********/
  33298. /**
  33299. A menu bar component.
  33300. @see MenuBarModel
  33301. */
  33302. class JUCE_API MenuBarComponent : public Component,
  33303. private MenuBarModelListener,
  33304. private Timer
  33305. {
  33306. public:
  33307. /** Creates a menu bar.
  33308. @param model the model object to use to control this bar. You can
  33309. pass 0 into this if you like, and set the model later
  33310. using the setModel() method
  33311. */
  33312. MenuBarComponent (MenuBarModel* const model);
  33313. /** Destructor. */
  33314. ~MenuBarComponent();
  33315. /** Changes the model object to use to control the bar.
  33316. This can be 0, in which case the bar will be empty. Don't delete the object
  33317. that is passed-in while it's still being used by this MenuBar.
  33318. */
  33319. void setModel (MenuBarModel* const newModel);
  33320. /** Pops up one of the menu items.
  33321. This lets you manually open one of the menus - it could be triggered by a
  33322. key shortcut, for example.
  33323. */
  33324. void showMenu (const int menuIndex);
  33325. /** @internal */
  33326. void paint (Graphics& g);
  33327. /** @internal */
  33328. void resized();
  33329. /** @internal */
  33330. void mouseEnter (const MouseEvent& e);
  33331. /** @internal */
  33332. void mouseExit (const MouseEvent& e);
  33333. /** @internal */
  33334. void mouseDown (const MouseEvent& e);
  33335. /** @internal */
  33336. void mouseDrag (const MouseEvent& e);
  33337. /** @internal */
  33338. void mouseUp (const MouseEvent& e);
  33339. /** @internal */
  33340. void mouseMove (const MouseEvent& e);
  33341. /** @internal */
  33342. void inputAttemptWhenModal();
  33343. /** @internal */
  33344. void handleCommandMessage (int commandId);
  33345. /** @internal */
  33346. bool keyPressed (const KeyPress& key);
  33347. /** @internal */
  33348. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  33349. /** @internal */
  33350. void menuCommandInvoked (MenuBarModel* menuBarModel,
  33351. const ApplicationCommandTarget::InvocationInfo& info);
  33352. juce_UseDebuggingNewOperator
  33353. private:
  33354. MenuBarModel* model;
  33355. StringArray menuNames;
  33356. Array <int> xPositions;
  33357. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  33358. int lastMouseX, lastMouseY;
  33359. bool inModalState;
  33360. Component* currentPopup;
  33361. int getItemAt (int x, int y);
  33362. void updateItemUnderMouse (const int x, const int y);
  33363. void hideCurrentMenu();
  33364. void timerCallback();
  33365. void repaintMenuItem (int index);
  33366. MenuBarComponent (const MenuBarComponent&);
  33367. const MenuBarComponent& operator= (const MenuBarComponent&);
  33368. };
  33369. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33370. /********* End of inlined file: juce_MenuBarComponent.h *********/
  33371. #endif
  33372. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  33373. #endif
  33374. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  33375. #endif
  33376. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  33377. #endif
  33378. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33379. /********* Start of inlined file: juce_ComponentDragger.h *********/
  33380. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33381. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33382. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  33383. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33384. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33385. /**
  33386. A class that imposes restrictions on a Component's size or position.
  33387. This is used by classes such as ResizableCornerComponent,
  33388. ResizableBorderComponent and ResizableWindow.
  33389. The base class can impose some basic size and position limits, but you can
  33390. also subclass this for custom uses.
  33391. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  33392. */
  33393. class JUCE_API ComponentBoundsConstrainer
  33394. {
  33395. public:
  33396. /** When first created, the object will not impose any restrictions on the components. */
  33397. ComponentBoundsConstrainer() throw();
  33398. /** Destructor. */
  33399. virtual ~ComponentBoundsConstrainer();
  33400. /** Imposes a minimum width limit. */
  33401. void setMinimumWidth (const int minimumWidth) throw();
  33402. /** Returns the current minimum width. */
  33403. int getMinimumWidth() const throw() { return minW; }
  33404. /** Imposes a maximum width limit. */
  33405. void setMaximumWidth (const int maximumWidth) throw();
  33406. /** Returns the current maximum width. */
  33407. int getMaximumWidth() const throw() { return maxW; }
  33408. /** Imposes a minimum height limit. */
  33409. void setMinimumHeight (const int minimumHeight) throw();
  33410. /** Returns the current minimum height. */
  33411. int getMinimumHeight() const throw() { return minH; }
  33412. /** Imposes a maximum height limit. */
  33413. void setMaximumHeight (const int maximumHeight) throw();
  33414. /** Returns the current maximum height. */
  33415. int getMaximumHeight() const throw() { return maxH; }
  33416. /** Imposes a minimum width and height limit. */
  33417. void setMinimumSize (const int minimumWidth,
  33418. const int minimumHeight) throw();
  33419. /** Imposes a maximum width and height limit. */
  33420. void setMaximumSize (const int maximumWidth,
  33421. const int maximumHeight) throw();
  33422. /** Set all the maximum and minimum dimensions. */
  33423. void setSizeLimits (const int minimumWidth,
  33424. const int minimumHeight,
  33425. const int maximumWidth,
  33426. const int maximumHeight) throw();
  33427. /** Sets the amount by which the component is allowed to go off-screen.
  33428. The values indicate how many pixels must remain on-screen when dragged off
  33429. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  33430. when the component goes off the top of the screen, its y-position will be
  33431. clipped so that there are always at least 10 pixels on-screen. In other words,
  33432. the lowest y-position it can take would be (10 - the component's height).
  33433. If you pass 0 or less for one of these amounts, the component is allowed
  33434. to move beyond that edge completely, with no restrictions at all.
  33435. If you pass a very large number (i.e. larger that the dimensions of the
  33436. component itself), then the component won't be allowed to overlap that
  33437. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  33438. the component will bump into the left side of the screen and go no further.
  33439. */
  33440. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  33441. const int minimumWhenOffTheLeft,
  33442. const int minimumWhenOffTheBottom,
  33443. const int minimumWhenOffTheRight) throw();
  33444. /** Specifies a width-to-height ratio that the resizer should always maintain.
  33445. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  33446. will always be maintained as this multiple of the height.
  33447. @see setResizeLimits
  33448. */
  33449. void setFixedAspectRatio (const double widthOverHeight) throw();
  33450. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  33451. If no aspect ratio is being enforced, this will return 0.
  33452. */
  33453. double getFixedAspectRatio() const throw();
  33454. /** This callback changes the given co-ordinates to impose whatever the current
  33455. constraints are set to be.
  33456. @param x the x position that should be examined and adjusted
  33457. @param y the y position that should be examined and adjusted
  33458. @param w the width that should be examined and adjusted
  33459. @param h the height that should be examined and adjusted
  33460. @param previousBounds the component's current size
  33461. @param limits the region in which the component can be positioned
  33462. @param isStretchingTop whether the top edge of the component is being resized
  33463. @param isStretchingLeft whether the left edge of the component is being resized
  33464. @param isStretchingBottom whether the bottom edge of the component is being resized
  33465. @param isStretchingRight whether the right edge of the component is being resized
  33466. */
  33467. virtual void checkBounds (int& x, int& y, int& w, int& h,
  33468. const Rectangle& previousBounds,
  33469. const Rectangle& limits,
  33470. const bool isStretchingTop,
  33471. const bool isStretchingLeft,
  33472. const bool isStretchingBottom,
  33473. const bool isStretchingRight);
  33474. /** This callback happens when the resizer is about to start dragging. */
  33475. virtual void resizeStart();
  33476. /** This callback happens when the resizer has finished dragging. */
  33477. virtual void resizeEnd();
  33478. /** Checks the given bounds, and then sets the component to the corrected size. */
  33479. void setBoundsForComponent (Component* const component,
  33480. int x, int y, int w, int h,
  33481. const bool isStretchingTop,
  33482. const bool isStretchingLeft,
  33483. const bool isStretchingBottom,
  33484. const bool isStretchingRight);
  33485. /** Performs a check on the current size of a component, and moves or resizes
  33486. it if it fails the constraints.
  33487. */
  33488. void checkComponentBounds (Component* component);
  33489. /** Called by setBoundsForComponent() to apply a new constrained size to a
  33490. component.
  33491. By default this just calls setBounds(), but it virtual in case it's needed for
  33492. extremely cunning purposes.
  33493. */
  33494. virtual void applyBoundsToComponent (Component* component,
  33495. int x, int y, int w, int h);
  33496. juce_UseDebuggingNewOperator
  33497. private:
  33498. int minW, maxW, minH, maxH;
  33499. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  33500. double aspectRatio;
  33501. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  33502. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  33503. };
  33504. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33505. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  33506. /**
  33507. An object to take care of the logic for dragging components around with the mouse.
  33508. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  33509. then in your mouseDrag() callback, call dragComponent().
  33510. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  33511. to limit the component's position and keep it on-screen.
  33512. e.g. @code
  33513. class MyDraggableComp
  33514. {
  33515. ComponentDragger myDragger;
  33516. void mouseDown (const MouseEvent& e)
  33517. {
  33518. myDragger.startDraggingComponent (this, 0);
  33519. }
  33520. void mouseDrag (const MouseEvent& e)
  33521. {
  33522. myDragger.dragComponent (this, e);
  33523. }
  33524. };
  33525. @endcode
  33526. */
  33527. class JUCE_API ComponentDragger
  33528. {
  33529. public:
  33530. /** Creates a ComponentDragger. */
  33531. ComponentDragger();
  33532. /** Destructor. */
  33533. virtual ~ComponentDragger();
  33534. /** Call this from your component's mouseDown() method, to prepare for dragging.
  33535. @param componentToDrag the component that you want to drag
  33536. @param constrainer a constrainer object to use to keep the component
  33537. from going offscreen
  33538. @see dragComponent
  33539. */
  33540. void startDraggingComponent (Component* const componentToDrag,
  33541. ComponentBoundsConstrainer* constrainer);
  33542. /** Call this from your mouseDrag() callback to move the component.
  33543. This will move the component, but will first check the validity of the
  33544. component's new position using the checkPosition() method, which you
  33545. can override if you need to enforce special positioning limits on the
  33546. component.
  33547. @param componentToDrag the component that you want to drag
  33548. @param e the current mouse-drag event
  33549. @see dragComponent
  33550. */
  33551. void dragComponent (Component* const componentToDrag,
  33552. const MouseEvent& e);
  33553. juce_UseDebuggingNewOperator
  33554. private:
  33555. ComponentBoundsConstrainer* constrainer;
  33556. int originalX, originalY;
  33557. };
  33558. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33559. /********* End of inlined file: juce_ComponentDragger.h *********/
  33560. #endif
  33561. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33562. #endif
  33563. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33564. #endif
  33565. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33566. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  33567. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33568. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33569. /**
  33570. Components derived from this class can have files dropped onto them by an external application.
  33571. @see DragAndDropContainer
  33572. */
  33573. class JUCE_API FileDragAndDropTarget
  33574. {
  33575. public:
  33576. /** Destructor. */
  33577. virtual ~FileDragAndDropTarget() {}
  33578. /** Callback to check whether this target is interested in the set of files being offered.
  33579. Note that this will be called repeatedly when the user is dragging the mouse around over your
  33580. component, so don't do anything time-consuming in here, like opening the files to have a look
  33581. inside them!
  33582. @param files the set of (absolute) pathnames of the files that the user is dragging
  33583. @returns true if this component wants to receive the other callbacks regarging this
  33584. type of object; if it returns false, no other callbacks will be made.
  33585. */
  33586. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  33587. /** Callback to indicate that some files are being dragged over this component.
  33588. This gets called when the user moves the mouse into this component while dragging.
  33589. Use this callback as a trigger to make your component repaint itself to give the
  33590. user feedback about whether the files can be dropped here or not.
  33591. @param files the set of (absolute) pathnames of the files that the user is dragging
  33592. @param x the mouse x position, relative to this component
  33593. @param y the mouse y position, relative to this component
  33594. */
  33595. virtual void fileDragEnter (const StringArray& files, int x, int y);
  33596. /** Callback to indicate that the user is dragging some files over this component.
  33597. This gets called when the user moves the mouse over this component while dragging.
  33598. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  33599. this lets you know what happens in-between.
  33600. @param files the set of (absolute) pathnames of the files that the user is dragging
  33601. @param x the mouse x position, relative to this component
  33602. @param y the mouse y position, relative to this component
  33603. */
  33604. virtual void fileDragMove (const StringArray& files, int x, int y);
  33605. /** Callback to indicate that the mouse has moved away from this component.
  33606. This gets called when the user moves the mouse out of this component while dragging
  33607. the files.
  33608. If you've used fileDragEnter() to repaint your component and give feedback, use this
  33609. as a signal to repaint it in its normal state.
  33610. @param files the set of (absolute) pathnames of the files that the user is dragging
  33611. */
  33612. virtual void fileDragExit (const StringArray& files);
  33613. /** Callback to indicate that the user has dropped the files onto this component.
  33614. When the user drops the files, this get called, and you can use the files in whatever
  33615. way is appropriate.
  33616. Note that after this is called, the fileDragExit method may not be called, so you should
  33617. clean up in here if there's anything you need to do when the drag finishes.
  33618. @param files the set of (absolute) pathnames of the files that the user is dragging
  33619. @param x the mouse x position, relative to this component
  33620. @param y the mouse y position, relative to this component
  33621. */
  33622. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  33623. };
  33624. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33625. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  33626. #endif
  33627. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33628. /********* Start of inlined file: juce_LassoComponent.h *********/
  33629. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33630. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33631. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  33632. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33633. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33634. /** Manages a list of selectable items.
  33635. Use one of these to keep a track of things that the user has highlighted, like
  33636. icons or things in a list.
  33637. The class is templated so that you can use it to hold either a set of pointers
  33638. to objects, or a set of ID numbers or handles, for cases where each item may
  33639. not always have a corresponding object.
  33640. To be informed when items are selected/deselected, register a ChangeListener with
  33641. this object.
  33642. @see SelectableObject
  33643. */
  33644. template <class SelectableItemType>
  33645. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  33646. {
  33647. public:
  33648. /** Creates an empty set. */
  33649. SelectedItemSet()
  33650. {
  33651. }
  33652. /** Creates a set based on an array of items. */
  33653. SelectedItemSet (const Array <SelectableItemType>& items)
  33654. : selectedItems (items)
  33655. {
  33656. }
  33657. /** Creates a copy of another set. */
  33658. SelectedItemSet (const SelectedItemSet& other)
  33659. : selectedItems (other.selectedItems)
  33660. {
  33661. }
  33662. /** Creates a copy of another set. */
  33663. const SelectedItemSet& operator= (const SelectedItemSet& other)
  33664. {
  33665. if (selectedItems != other.selectedItems)
  33666. {
  33667. selectedItems = other.selectedItems;
  33668. changed();
  33669. }
  33670. return *this;
  33671. }
  33672. /** Destructor. */
  33673. ~SelectedItemSet()
  33674. {
  33675. }
  33676. /** Clears any other currently selected items, and selects this item.
  33677. If this item is already the only thing selected, no change notification
  33678. will be sent out.
  33679. @see addToSelection, addToSelectionBasedOnModifiers
  33680. */
  33681. void selectOnly (SelectableItemType item)
  33682. {
  33683. if (isSelected (item))
  33684. {
  33685. for (int i = selectedItems.size(); --i >= 0;)
  33686. {
  33687. if (selectedItems.getUnchecked(i) != item)
  33688. {
  33689. deselect (selectedItems.getUnchecked(i));
  33690. i = jmin (i, selectedItems.size());
  33691. }
  33692. }
  33693. }
  33694. else
  33695. {
  33696. deselectAll();
  33697. changed();
  33698. selectedItems.add (item);
  33699. itemSelected (item);
  33700. }
  33701. }
  33702. /** Selects an item.
  33703. If the item is already selected, no change notification will be sent out.
  33704. @see selectOnly, addToSelectionBasedOnModifiers
  33705. */
  33706. void addToSelection (SelectableItemType item)
  33707. {
  33708. if (! isSelected (item))
  33709. {
  33710. changed();
  33711. selectedItems.add (item);
  33712. itemSelected (item);
  33713. }
  33714. }
  33715. /** Selects or deselects an item.
  33716. This will use the modifier keys to decide whether to deselect other items
  33717. first.
  33718. So if the shift key is held down, the item will be added without deselecting
  33719. anything (same as calling addToSelection() )
  33720. If no modifiers are down, the current selection will be cleared first (same
  33721. as calling selectOnly() )
  33722. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  33723. so it'll be added to the set unless it's already there, in which case it'll be
  33724. deselected.
  33725. If the items that you're selecting can also be dragged, you may need to use the
  33726. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  33727. subtleties of this kind of usage.
  33728. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  33729. */
  33730. void addToSelectionBasedOnModifiers (SelectableItemType item,
  33731. const ModifierKeys& modifiers)
  33732. {
  33733. if (modifiers.isShiftDown())
  33734. {
  33735. addToSelection (item);
  33736. }
  33737. else if (modifiers.isCommandDown())
  33738. {
  33739. if (isSelected (item))
  33740. deselect (item);
  33741. else
  33742. addToSelection (item);
  33743. }
  33744. else
  33745. {
  33746. selectOnly (item);
  33747. }
  33748. }
  33749. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  33750. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  33751. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  33752. makes it easy to handle multiple-selection of sets of objects that can also
  33753. be dragged.
  33754. For example, if you have several items already selected, and you click on
  33755. one of them (without dragging), then you'd expect this to deselect the other, and
  33756. just select the item you clicked on. But if you had clicked on this item and
  33757. dragged it, you'd have expected them all to stay selected.
  33758. When you call this method, you'll need to store the boolean result, because the
  33759. addToSelectionOnMouseUp() method will need to be know this value.
  33760. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  33761. */
  33762. bool addToSelectionOnMouseDown (SelectableItemType item,
  33763. const ModifierKeys& modifiers)
  33764. {
  33765. if (isSelected (item))
  33766. {
  33767. return ! modifiers.isPopupMenu();
  33768. }
  33769. else
  33770. {
  33771. addToSelectionBasedOnModifiers (item, modifiers);
  33772. return false;
  33773. }
  33774. }
  33775. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  33776. Call this during a mouseUp callback, when you have previously called the
  33777. addToSelectionOnMouseDown() method during your mouseDown event.
  33778. See addToSelectionOnMouseDown() for more info
  33779. @param item the item to select (or deselect)
  33780. @param modifiers the modifiers from the mouse-up event
  33781. @param wasItemDragged true if your item was dragged during the mouse click
  33782. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  33783. back from the addToSelectionOnMouseDown() call that you
  33784. should have made during the matching mouseDown event
  33785. */
  33786. void addToSelectionOnMouseUp (SelectableItemType item,
  33787. const ModifierKeys& modifiers,
  33788. const bool wasItemDragged,
  33789. const bool resultOfMouseDownSelectMethod)
  33790. {
  33791. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  33792. addToSelectionBasedOnModifiers (item, modifiers);
  33793. }
  33794. /** Deselects an item. */
  33795. void deselect (SelectableItemType item)
  33796. {
  33797. const int i = selectedItems.indexOf (item);
  33798. if (i >= 0)
  33799. {
  33800. changed();
  33801. itemDeselected (selectedItems.remove (i));
  33802. }
  33803. }
  33804. /** Deselects all items. */
  33805. void deselectAll()
  33806. {
  33807. if (selectedItems.size() > 0)
  33808. {
  33809. changed();
  33810. for (int i = selectedItems.size(); --i >= 0;)
  33811. {
  33812. itemDeselected (selectedItems.remove (i));
  33813. i = jmin (i, selectedItems.size());
  33814. }
  33815. }
  33816. }
  33817. /** Returns the number of currently selected items.
  33818. @see getSelectedItem
  33819. */
  33820. int getNumSelected() const throw()
  33821. {
  33822. return selectedItems.size();
  33823. }
  33824. /** Returns one of the currently selected items.
  33825. Returns 0 if the index is out-of-range.
  33826. @see getNumSelected
  33827. */
  33828. SelectableItemType getSelectedItem (const int index) const throw()
  33829. {
  33830. return selectedItems [index];
  33831. }
  33832. /** True if this item is currently selected. */
  33833. bool isSelected (const SelectableItemType item) const throw()
  33834. {
  33835. return selectedItems.contains (item);
  33836. }
  33837. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  33838. /** Can be overridden to do special handling when an item is selected.
  33839. For example, if the item is an object, you might want to call it and tell
  33840. it that it's being selected.
  33841. */
  33842. virtual void itemSelected (SelectableItemType item) {}
  33843. /** Can be overridden to do special handling when an item is deselected.
  33844. For example, if the item is an object, you might want to call it and tell
  33845. it that it's being deselected.
  33846. */
  33847. virtual void itemDeselected (SelectableItemType item) {}
  33848. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  33849. */
  33850. void changed (const bool synchronous = false)
  33851. {
  33852. if (synchronous)
  33853. sendSynchronousChangeMessage (this);
  33854. else
  33855. sendChangeMessage (this);
  33856. }
  33857. juce_UseDebuggingNewOperator
  33858. private:
  33859. Array <SelectableItemType> selectedItems;
  33860. };
  33861. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33862. /********* End of inlined file: juce_SelectedItemSet.h *********/
  33863. /**
  33864. A class used by the LassoComponent to manage the things that it selects.
  33865. This allows the LassoComponent to find out which items are within the lasso,
  33866. and to change the list of selected items.
  33867. @see LassoComponent, SelectedItemSet
  33868. */
  33869. template <class SelectableItemType>
  33870. class LassoSource
  33871. {
  33872. public:
  33873. /** Destructor. */
  33874. virtual ~LassoSource() {}
  33875. /** Returns the set of items that lie within a given lassoable region.
  33876. Your implementation of this method must find all the relevent items that lie
  33877. within the given rectangle. and add them to the itemsFound array.
  33878. The co-ordinates are relative to the top-left of the lasso component's parent
  33879. component. (i.e. they are the same as the size and position of the lasso
  33880. component itself).
  33881. */
  33882. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  33883. int x, int y, int width, int height) = 0;
  33884. /** Returns the SelectedItemSet that the lasso should update.
  33885. This set will be continuously updated by the LassoComponent as it gets
  33886. dragged around, so make sure that you've got a ChangeListener attached to
  33887. the set so that your UI objects will know when the selection changes and
  33888. be able to update themselves appropriately.
  33889. */
  33890. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  33891. };
  33892. /**
  33893. A component that acts as a rectangular selection region, which you drag with
  33894. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  33895. To use one of these:
  33896. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  33897. component, and call its beginLasso() method, giving it a
  33898. suitable LassoSource object that it can use to find out which items are in
  33899. the active area.
  33900. - Each time your parent component gets a mouseDrag event, call dragLasso()
  33901. to update the lasso's position - it will use its LassoSource to calculate and
  33902. update the current selection.
  33903. - After the drag has finished and you get a mouseUp callback, you should call
  33904. endLasso() to clean up. This will make the lasso component invisible, and you
  33905. can remove it from the parent component, or delete it.
  33906. The class takes into account the modifier keys that are being held down while
  33907. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  33908. be added to the original selection; if ctrl or command is pressed, they will be
  33909. xor'ed with any previously selected items.
  33910. @see LassoSource, SelectedItemSet
  33911. */
  33912. template <class SelectableItemType>
  33913. class LassoComponent : public Component
  33914. {
  33915. public:
  33916. /** Creates a Lasso component.
  33917. The fill colour is used to fill the lasso'ed rectangle, and the outline
  33918. colour is used to draw a line around its edge.
  33919. */
  33920. LassoComponent (const int outlineThickness_ = 1)
  33921. : source (0),
  33922. outlineThickness (outlineThickness_)
  33923. {
  33924. }
  33925. /** Destructor. */
  33926. ~LassoComponent()
  33927. {
  33928. }
  33929. /** Call this in your mouseDown event, to initialise a drag.
  33930. Pass in a suitable LassoSource object which the lasso will use to find
  33931. the items and change the selection.
  33932. After using this method to initialise the lasso, repeatedly call dragLasso()
  33933. in your component's mouseDrag callback.
  33934. @see dragLasso, endLasso, LassoSource
  33935. */
  33936. void beginLasso (const MouseEvent& e,
  33937. LassoSource <SelectableItemType>* const lassoSource)
  33938. {
  33939. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  33940. jassert (lassoSource != 0); // the source can't be null!
  33941. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  33942. source = lassoSource;
  33943. if (lassoSource != 0)
  33944. originalSelection = lassoSource->getLassoSelection().getItemArray();
  33945. setSize (0, 0);
  33946. }
  33947. /** Call this in your mouseDrag event, to update the lasso's position.
  33948. This must be repeatedly calling when the mouse is dragged, after you've
  33949. first initialised the lasso with beginLasso().
  33950. This method takes into account the modifier keys that are being held down, so
  33951. if shift is pressed, then the lassoed items will be added to any that were
  33952. previously selected; if ctrl or command is pressed, then they will be xor'ed
  33953. with previously selected items.
  33954. @see beginLasso, endLasso
  33955. */
  33956. void dragLasso (const MouseEvent& e)
  33957. {
  33958. if (source != 0)
  33959. {
  33960. const int x1 = e.getMouseDownX();
  33961. const int y1 = e.getMouseDownY();
  33962. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  33963. setVisible (true);
  33964. Array <SelectableItemType> itemsInLasso;
  33965. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  33966. if (e.mods.isShiftDown())
  33967. {
  33968. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  33969. itemsInLasso.addArray (originalSelection);
  33970. }
  33971. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  33972. {
  33973. Array <SelectableItemType> originalMinusNew (originalSelection);
  33974. originalMinusNew.removeValuesIn (itemsInLasso);
  33975. itemsInLasso.removeValuesIn (originalSelection);
  33976. itemsInLasso.addArray (originalMinusNew);
  33977. }
  33978. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  33979. }
  33980. }
  33981. /** Call this in your mouseUp event, after the lasso has been dragged.
  33982. @see beginLasso, dragLasso
  33983. */
  33984. void endLasso()
  33985. {
  33986. source = 0;
  33987. originalSelection.clear();
  33988. setVisible (false);
  33989. }
  33990. /** A set of colour IDs to use to change the colour of various aspects of the label.
  33991. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33992. methods.
  33993. Note that you can also use the constants from TextEditor::ColourIds to change the
  33994. colour of the text editor that is opened when a label is editable.
  33995. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33996. */
  33997. enum ColourIds
  33998. {
  33999. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  34000. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  34001. };
  34002. /** @internal */
  34003. void paint (Graphics& g)
  34004. {
  34005. g.fillAll (findColour (lassoFillColourId));
  34006. g.setColour (findColour (lassoOutlineColourId));
  34007. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  34008. // this suggests that you've left a lasso comp lying around after the
  34009. // mouse drag has finished.. Be careful to call endLasso() when you get a
  34010. // mouse-up event.
  34011. jassert (isMouseButtonDownAnywhere());
  34012. }
  34013. /** @internal */
  34014. bool hitTest (int x, int y) { return false; }
  34015. juce_UseDebuggingNewOperator
  34016. private:
  34017. Array <SelectableItemType> originalSelection;
  34018. LassoSource <SelectableItemType>* source;
  34019. int outlineThickness;
  34020. };
  34021. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34022. /********* End of inlined file: juce_LassoComponent.h *********/
  34023. #endif
  34024. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  34025. #endif
  34026. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  34027. #endif
  34028. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34029. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  34030. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34031. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34032. /**
  34033. Monitors a component for mouse activity, and triggers a callback
  34034. when the mouse hovers in one place for a specified length of time.
  34035. To use a hover-detector, just create one and call its setHoverComponent()
  34036. method to start it watching a component. You can call setHoverComponent (0)
  34037. to make it inactive.
  34038. (Be careful not to delete a component that's being monitored without first
  34039. stopping or deleting the hover detector).
  34040. */
  34041. class JUCE_API MouseHoverDetector
  34042. {
  34043. public:
  34044. /** Creates a hover detector.
  34045. Initially the object is inactive, and you need to tell it which component
  34046. to monitor, using the setHoverComponent() method.
  34047. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  34048. needs to stay still before the mouseHovered() method
  34049. is invoked. You can change this setting later with
  34050. the setHoverTimeMillisecs() method
  34051. */
  34052. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  34053. /** Destructor. */
  34054. virtual ~MouseHoverDetector();
  34055. /** Changes the time for which the mouse has to stay still before it's considered
  34056. to be hovering.
  34057. */
  34058. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  34059. /** Changes the component that's being monitored for hovering.
  34060. Be careful not to delete a component that's being monitored without first
  34061. stopping or deleting the hover detector.
  34062. */
  34063. void setHoverComponent (Component* const newSourceComponent);
  34064. protected:
  34065. /** Called back when the mouse hovers.
  34066. After the mouse has stayed still over the component for the length of time
  34067. specified by setHoverTimeMillisecs(), this method will be invoked.
  34068. When the mouse is first moved after this callback has occurred, the
  34069. mouseMovedAfterHover() method will be called.
  34070. @param mouseX the mouse's X position relative to the component being monitored
  34071. @param mouseY the mouse's Y position relative to the component being monitored
  34072. */
  34073. virtual void mouseHovered (int mouseX,
  34074. int mouseY) = 0;
  34075. /** Called when the mouse is moved away after just having hovered. */
  34076. virtual void mouseMovedAfterHover() = 0;
  34077. private:
  34078. class JUCE_API HoverDetectorInternal : public MouseListener,
  34079. public Timer
  34080. {
  34081. public:
  34082. MouseHoverDetector* owner;
  34083. int lastX, lastY;
  34084. void timerCallback();
  34085. void mouseEnter (const MouseEvent&);
  34086. void mouseExit (const MouseEvent&);
  34087. void mouseDown (const MouseEvent&);
  34088. void mouseUp (const MouseEvent&);
  34089. void mouseMove (const MouseEvent&);
  34090. void mouseWheelMove (const MouseEvent&, float, float);
  34091. } internalTimer;
  34092. friend class HoverDetectorInternal;
  34093. Component* source;
  34094. int hoverTimeMillisecs;
  34095. bool hasJustHovered;
  34096. void hoverTimerCallback();
  34097. void checkJustHoveredCallback();
  34098. };
  34099. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34100. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  34101. #endif
  34102. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  34103. #endif
  34104. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  34105. #endif
  34106. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34107. #endif
  34108. #ifndef __JUCE_LABEL_JUCEHEADER__
  34109. #endif
  34110. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34111. #endif
  34112. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34113. /********* Start of inlined file: juce_ProgressBar.h *********/
  34114. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34115. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34116. /**
  34117. A progress bar component.
  34118. To use this, just create one and make it visible. It'll run its own timer
  34119. to keep an eye on a variable that you give it, and will automatically
  34120. redraw itself when the variable changes.
  34121. For an easy way of running a background task with a dialog box showing its
  34122. progress, see the ThreadWithProgressWindow class.
  34123. @see ThreadWithProgressWindow
  34124. */
  34125. class JUCE_API ProgressBar : public Component,
  34126. public SettableTooltipClient,
  34127. private Timer
  34128. {
  34129. public:
  34130. /** Creates a ProgressBar.
  34131. @param progress pass in a reference to a double that you're going to
  34132. update with your task's progress. The ProgressBar will
  34133. monitor the value of this variable and will redraw itself
  34134. when the value changes. The range is from 0 to 1.0. Obviously
  34135. you'd better be careful not to delete this variable while the
  34136. ProgressBar still exists!
  34137. */
  34138. ProgressBar (double& progress);
  34139. /** Destructor. */
  34140. ~ProgressBar();
  34141. /** Turns the percentage display on or off.
  34142. By default this is on, and the progress bar will display a text string showing
  34143. its current percentage.
  34144. */
  34145. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34146. /** Gives the progress bar a string to display inside it.
  34147. If you call this, it will turn off the percentage display.
  34148. @see setPercentageDisplay
  34149. */
  34150. void setTextToDisplay (const String& text);
  34151. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34152. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34153. methods.
  34154. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34155. */
  34156. enum ColourIds
  34157. {
  34158. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34159. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34160. classes will probably use variations on this colour. */
  34161. };
  34162. juce_UseDebuggingNewOperator
  34163. protected:
  34164. /** @internal */
  34165. void paint (Graphics& g);
  34166. /** @internal */
  34167. void lookAndFeelChanged();
  34168. /** @internal */
  34169. void visibilityChanged();
  34170. /** @internal */
  34171. void colourChanged();
  34172. private:
  34173. double& progress;
  34174. double currentValue;
  34175. bool displayPercentage;
  34176. String displayedMessage, currentMessage;
  34177. uint32 lastCallbackTime;
  34178. void timerCallback();
  34179. ProgressBar (const ProgressBar&);
  34180. const ProgressBar& operator= (const ProgressBar&);
  34181. };
  34182. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34183. /********* End of inlined file: juce_ProgressBar.h *********/
  34184. #endif
  34185. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34186. /********* Start of inlined file: juce_Slider.h *********/
  34187. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34188. #define __JUCE_SLIDER_JUCEHEADER__
  34189. /********* Start of inlined file: juce_SliderListener.h *********/
  34190. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34191. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  34192. class Slider;
  34193. /**
  34194. A class for receiving callbacks from a Slider.
  34195. To be told when a slider's value changes, you can register a SliderListener
  34196. object using Slider::addListener().
  34197. @see Slider::addListener, Slider::removeListener
  34198. */
  34199. class JUCE_API SliderListener
  34200. {
  34201. public:
  34202. /** Destructor. */
  34203. virtual ~SliderListener() {}
  34204. /** Called when the slider's value is changed.
  34205. This may be caused by dragging it, or by typing in its text entry box,
  34206. or by a call to Slider::setValue().
  34207. You can find out the new value using Slider::getValue().
  34208. @see Slider::valueChanged
  34209. */
  34210. virtual void sliderValueChanged (Slider* slider) = 0;
  34211. /** Called when the slider is about to be dragged.
  34212. This is called when a drag begins, then it's followed by multiple calls
  34213. to sliderValueChanged(), and then sliderDragEnded() is called after the
  34214. user lets go.
  34215. @see sliderDragEnded, Slider::startedDragging
  34216. */
  34217. virtual void sliderDragStarted (Slider* slider);
  34218. /** Called after a drag operation has finished.
  34219. @see sliderDragStarted, Slider::stoppedDragging
  34220. */
  34221. virtual void sliderDragEnded (Slider* slider);
  34222. };
  34223. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  34224. /********* End of inlined file: juce_SliderListener.h *********/
  34225. /**
  34226. A slider control for changing a value.
  34227. The slider can be horizontal, vertical, or rotary, and can optionally have
  34228. a text-box inside it to show an editable display of the current value.
  34229. To use it, create a Slider object and use the setSliderStyle() method
  34230. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  34231. To define the values that it can be set to, see the setRange() and setValue() methods.
  34232. There are also lots of custom tweaks you can do by subclassing and overriding
  34233. some of the virtual methods, such as changing the scaling, changing the format of
  34234. the text display, custom ways of limiting the values, etc.
  34235. You can register SliderListeners with a slider, which will be informed when the value
  34236. changes, or a subclass can override valueChanged() to be informed synchronously.
  34237. @see SliderListener
  34238. */
  34239. class JUCE_API Slider : public Component,
  34240. public SettableTooltipClient,
  34241. private AsyncUpdater,
  34242. private ButtonListener,
  34243. private LabelListener
  34244. {
  34245. public:
  34246. /** Creates a slider.
  34247. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  34248. setRange(), etc.
  34249. */
  34250. Slider (const String& componentName);
  34251. /** Destructor. */
  34252. ~Slider();
  34253. /** The types of slider available.
  34254. @see setSliderStyle, setRotaryParameters
  34255. */
  34256. enum SliderStyle
  34257. {
  34258. LinearHorizontal, /**< A traditional horizontal slider. */
  34259. LinearVertical, /**< A traditional vertical slider. */
  34260. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  34261. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  34262. @see setRotaryParameters */
  34263. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  34264. @see setRotaryParameters */
  34265. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  34266. @see setRotaryParameters */
  34267. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  34268. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34269. @see setMinValue, setMaxValue */
  34270. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34271. @see setMinValue, setMaxValue */
  34272. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  34273. value, with the current value being somewhere between them.
  34274. @see setMinValue, setMaxValue */
  34275. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  34276. value, with the current value being somewhere between them.
  34277. @see setMinValue, setMaxValue */
  34278. };
  34279. /** Changes the type of slider interface being used.
  34280. @param newStyle the type of interface
  34281. @see setRotaryParameters, setVelocityBasedMode,
  34282. */
  34283. void setSliderStyle (const SliderStyle newStyle);
  34284. /** Returns the slider's current style.
  34285. @see setSliderStyle
  34286. */
  34287. SliderStyle getSliderStyle() const throw() { return style; }
  34288. /** Changes the properties of a rotary slider.
  34289. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  34290. the slider's minimum value is represented
  34291. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  34292. the slider's maximum value is represented. This must be
  34293. greater than startAngleRadians
  34294. @param stopAtEnd if true, then when the slider is dragged around past the
  34295. minimum or maximum, it'll stop there; if false, it'll wrap
  34296. back to the opposite value
  34297. */
  34298. void setRotaryParameters (const float startAngleRadians,
  34299. const float endAngleRadians,
  34300. const bool stopAtEnd);
  34301. /** Sets the distance the mouse has to move to drag the slider across
  34302. the full extent of its range.
  34303. This only applies when in modes like RotaryHorizontalDrag, where it's using
  34304. relative mouse movements to adjust the slider.
  34305. */
  34306. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  34307. /** Changes the way the the mouse is used when dragging the slider.
  34308. If true, this will turn on velocity-sensitive dragging, so that
  34309. the faster the mouse moves, the bigger the movement to the slider. This
  34310. helps when making accurate adjustments if the slider's range is quite large.
  34311. If false, the slider will just try to snap to wherever the mouse is.
  34312. */
  34313. void setVelocityBasedMode (const bool isVelocityBased) throw();
  34314. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  34315. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  34316. or if you're holding down ctrl.
  34317. @param sensitivity higher values than 1.0 increase the range of acceleration used
  34318. @param threshold the minimum number of pixels that the mouse needs to move for it
  34319. to be treated as a movement
  34320. @param offset values greater than 0.0 increase the minimum speed that will be used when
  34321. the threshold is reached
  34322. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  34323. key to toggle velocity-sensitive mode
  34324. */
  34325. void setVelocityModeParameters (const double sensitivity = 1.0,
  34326. const int threshold = 1,
  34327. const double offset = 0.0,
  34328. const bool userCanPressKeyToSwapMode = true) throw();
  34329. /** Sets up a skew factor to alter the way values are distributed.
  34330. You may want to use a range of values on the slider where more accuracy
  34331. is required towards one end of the range, so this will logarithmically
  34332. spread the values across the length of the slider.
  34333. If the factor is < 1.0, the lower end of the range will fill more of the
  34334. slider's length; if the factor is > 1.0, the upper end of the range
  34335. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  34336. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  34337. method instead.
  34338. @see getSkewFactor, setSkewFactorFromMidPoint
  34339. */
  34340. void setSkewFactor (const double factor) throw();
  34341. /** Sets up a skew factor to alter the way values are distributed.
  34342. This allows you to specify the slider value that should appear in the
  34343. centre of the slider's visible range.
  34344. @see setSkewFactor, getSkewFactor
  34345. */
  34346. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  34347. /** Returns the current skew factor.
  34348. See setSkewFactor for more info.
  34349. @see setSkewFactor, setSkewFactorFromMidPoint
  34350. */
  34351. double getSkewFactor() const throw() { return skewFactor; }
  34352. /** Used by setIncDecButtonsMode().
  34353. */
  34354. enum IncDecButtonMode
  34355. {
  34356. incDecButtonsNotDraggable,
  34357. incDecButtonsDraggable_AutoDirection,
  34358. incDecButtonsDraggable_Horizontal,
  34359. incDecButtonsDraggable_Vertical
  34360. };
  34361. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  34362. can be dragged on the buttons to drag the values.
  34363. By default this is turned off. When enabled, clicking on the buttons still works
  34364. them as normal, but by holding down the mouse on a button and dragging it a little
  34365. distance, it flips into a mode where the value can be dragged. The drag direction can
  34366. either be set explicitly to be vertical or horizontal, or can be set to
  34367. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  34368. are side-by-side or above each other.
  34369. */
  34370. void setIncDecButtonsMode (const IncDecButtonMode mode);
  34371. /** The position of the slider's text-entry box.
  34372. @see setTextBoxStyle
  34373. */
  34374. enum TextEntryBoxPosition
  34375. {
  34376. NoTextBox, /**< Doesn't display a text box. */
  34377. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  34378. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  34379. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  34380. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  34381. };
  34382. /** Changes the location and properties of the text-entry box.
  34383. @param newPosition where it should go (or NoTextBox to not have one at all)
  34384. @param isReadOnly if true, it's a read-only display
  34385. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  34386. room for the slider as well!
  34387. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  34388. room for the slider as well!
  34389. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  34390. */
  34391. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  34392. const bool isReadOnly,
  34393. const int textEntryBoxWidth,
  34394. const int textEntryBoxHeight);
  34395. /** Returns the status of the text-box.
  34396. @see setTextBoxStyle
  34397. */
  34398. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  34399. /** Returns the width used for the text-box.
  34400. @see setTextBoxStyle
  34401. */
  34402. int getTextBoxWidth() const throw() { return textBoxWidth; }
  34403. /** Returns the height used for the text-box.
  34404. @see setTextBoxStyle
  34405. */
  34406. int getTextBoxHeight() const throw() { return textBoxHeight; }
  34407. /** Makes the text-box editable.
  34408. By default this is true, and the user can enter values into the textbox,
  34409. but it can be turned off if that's not suitable.
  34410. @see setTextBoxStyle, getValueFromText, getTextFromValue
  34411. */
  34412. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  34413. /** Returns true if the text-box is read-only.
  34414. @see setTextBoxStyle
  34415. */
  34416. bool isTextBoxEditable() const throw() { return editableText; }
  34417. /** If the text-box is editable, this will give it the focus so that the user can
  34418. type directly into it.
  34419. This is basically the effect as the user clicking on it.
  34420. */
  34421. void showTextBox();
  34422. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  34423. focus away from it.
  34424. @param discardCurrentEditorContents if true, the slider's value will be left
  34425. unchanged; if false, the current contents of the
  34426. text editor will be used to set the slider position
  34427. before it is hidden.
  34428. */
  34429. void hideTextBox (const bool discardCurrentEditorContents);
  34430. /** Changes the slider's current value.
  34431. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34432. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34433. want to handle it.
  34434. @param newValue the new value to set - this will be restricted by the
  34435. minimum and maximum range, and will be snapped to the
  34436. nearest interval if one has been set
  34437. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34438. any SliderListeners or the valueChanged() method
  34439. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34440. synchronously; if false, it will be asynchronous
  34441. */
  34442. void setValue (double newValue,
  34443. const bool sendUpdateMessage = true,
  34444. const bool sendMessageSynchronously = false);
  34445. /** Returns the slider's current value. */
  34446. double getValue() const throw();
  34447. /** Sets the limits that the slider's value can take.
  34448. @param newMinimum the lowest value allowed
  34449. @param newMaximum the highest value allowed
  34450. @param newInterval the steps in which the value is allowed to increase - if this
  34451. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  34452. */
  34453. void setRange (const double newMinimum,
  34454. const double newMaximum,
  34455. const double newInterval = 0);
  34456. /** Returns the current maximum value.
  34457. @see setRange
  34458. */
  34459. double getMaximum() const throw() { return maximum; }
  34460. /** Returns the current minimum value.
  34461. @see setRange
  34462. */
  34463. double getMinimum() const throw() { return minimum; }
  34464. /** Returns the current step-size for values.
  34465. @see setRange
  34466. */
  34467. double getInterval() const throw() { return interval; }
  34468. /** For a slider with two or three thumbs, this returns the lower of its values.
  34469. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34470. A slider with three values also uses the normal getValue() and setValue() methods to
  34471. control the middle value.
  34472. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34473. */
  34474. double getMinValue() const throw();
  34475. /** For a slider with two or three thumbs, this sets the lower of its values.
  34476. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34477. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34478. want to handle it.
  34479. @param newValue the new value to set - this will be restricted by the
  34480. minimum and maximum range, and will be snapped to the nearest
  34481. interval if one has been set.
  34482. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34483. any SliderListeners or the valueChanged() method
  34484. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34485. synchronously; if false, it will be asynchronous
  34486. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34487. max value (in a two-value slider) or the mid value (in a three-value
  34488. slider). If false, then if this value goes beyond those values,
  34489. it will push them along with it.
  34490. @see getMinValue, setMaxValue, setValue
  34491. */
  34492. void setMinValue (double newValue,
  34493. const bool sendUpdateMessage = true,
  34494. const bool sendMessageSynchronously = false,
  34495. const bool allowNudgingOfOtherValues = false);
  34496. /** For a slider with two or three thumbs, this returns the higher of its values.
  34497. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34498. A slider with three values also uses the normal getValue() and setValue() methods to
  34499. control the middle value.
  34500. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34501. */
  34502. double getMaxValue() const throw();
  34503. /** For a slider with two or three thumbs, this sets the lower of its values.
  34504. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34505. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34506. want to handle it.
  34507. @param newValue the new value to set - this will be restricted by the
  34508. minimum and maximum range, and will be snapped to the nearest
  34509. interval if one has been set.
  34510. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34511. any SliderListeners or the valueChanged() method
  34512. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34513. synchronously; if false, it will be asynchronous
  34514. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34515. min value (in a two-value slider) or the mid value (in a three-value
  34516. slider). If false, then if this value goes beyond those values,
  34517. it will push them along with it.
  34518. @see getMaxValue, setMinValue, setValue
  34519. */
  34520. void setMaxValue (double newValue,
  34521. const bool sendUpdateMessage = true,
  34522. const bool sendMessageSynchronously = false,
  34523. const bool allowNudgingOfOtherValues = false);
  34524. /** Adds a listener to be called when this slider's value changes. */
  34525. void addListener (SliderListener* const listener) throw();
  34526. /** Removes a previously-registered listener. */
  34527. void removeListener (SliderListener* const listener) throw();
  34528. /** This lets you choose whether double-clicking moves the slider to a given position.
  34529. By default this is turned off, but it's handy if you want a double-click to act
  34530. as a quick way of resetting a slider. Just pass in the value you want it to
  34531. go to when double-clicked.
  34532. @see getDoubleClickReturnValue
  34533. */
  34534. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  34535. const double valueToSetOnDoubleClick) throw();
  34536. /** Returns the values last set by setDoubleClickReturnValue() method.
  34537. Sets isEnabled to true if double-click is enabled, and returns the value
  34538. that was set.
  34539. @see setDoubleClickReturnValue
  34540. */
  34541. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  34542. /** Tells the slider whether to keep sending change messages while the user
  34543. is dragging the slider.
  34544. If set to true, a change message will only be sent when the user has
  34545. dragged the slider and let go. If set to false (the default), then messages
  34546. will be continuously sent as they drag it while the mouse button is still
  34547. held down.
  34548. */
  34549. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  34550. /** This lets you change whether the slider thumb jumps to the mouse position
  34551. when you click.
  34552. By default, this is true. If it's false, then the slider moves with relative
  34553. motion when you drag it.
  34554. This only applies to linear bars, and won't affect two- or three- value
  34555. sliders.
  34556. */
  34557. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  34558. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34559. slider is being dragged.
  34560. This can be handy if your slider doesn't have a text-box, so that users can
  34561. see the value just when they're changing it.
  34562. If you pass a component as the parentComponentToUse parameter, the pop-up
  34563. bubble will be added as a child of that component when it's needed. If you
  34564. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34565. transparent window, so if you're using an OS that can't do transparent windows
  34566. you'll have to add it to a parent component instead).
  34567. */
  34568. void setPopupDisplayEnabled (const bool isEnabled,
  34569. Component* const parentComponentToUse) throw();
  34570. /** If this is set to true, then right-clicking on the slider will pop-up
  34571. a menu to let the user change the way it works.
  34572. By default this is turned off, but when turned on, the menu will include
  34573. things like velocity sensitivity, and for rotary sliders, whether they
  34574. use a linear or rotary mouse-drag to move them.
  34575. */
  34576. void setPopupMenuEnabled (const bool menuEnabled) throw();
  34577. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34578. By default it's enabled.
  34579. */
  34580. void setScrollWheelEnabled (const bool enabled) throw();
  34581. /** Returns a number to indicate which thumb is currently being dragged by the
  34582. mouse.
  34583. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34584. the maximum-value thumb, or -1 if none is currently down.
  34585. */
  34586. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  34587. /** Callback to indicate that the user is about to start dragging the slider.
  34588. @see SliderListener::sliderDragStarted
  34589. */
  34590. virtual void startedDragging();
  34591. /** Callback to indicate that the user has just stopped dragging the slider.
  34592. @see SliderListener::sliderDragEnded
  34593. */
  34594. virtual void stoppedDragging();
  34595. /** Callback to indicate that the user has just moved the slider.
  34596. @see SliderListener::sliderValueChanged
  34597. */
  34598. virtual void valueChanged();
  34599. /** Callback to indicate that the user has just moved the slider.
  34600. Note - the valueChanged() method has changed its format and now no longer has
  34601. any parameters. Update your code to use the new version.
  34602. This version has been left here with an int as its return value to cause
  34603. a syntax error if you've got existing code that uses the old version.
  34604. */
  34605. virtual int valueChanged (double) { jassertfalse; return 0; }
  34606. /** Subclasses can override this to convert a text string to a value.
  34607. When the user enters something into the text-entry box, this method is
  34608. called to convert it to a value.
  34609. The default routine just tries to convert it to a double.
  34610. @see getTextFromValue
  34611. */
  34612. virtual double getValueFromText (const String& text);
  34613. /** Turns the slider's current value into a text string.
  34614. Subclasses can override this to customise the formatting of the text-entry box.
  34615. The default implementation just turns the value into a string, using
  34616. a number of decimal places based on the range interval. If a suffix string
  34617. has been set using setTextValueSuffix(), this will be appended to the text.
  34618. @see getValueFromText
  34619. */
  34620. virtual const String getTextFromValue (double value);
  34621. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34622. a string.
  34623. This is used by the default implementation of getTextFromValue(), and is just
  34624. appended to the numeric value. For more advanced formatting, you can override
  34625. getTextFromValue() and do something else.
  34626. */
  34627. void setTextValueSuffix (const String& suffix);
  34628. /** Allows a user-defined mapping of distance along the slider to its value.
  34629. The default implementation for this performs the skewing operation that
  34630. can be set up in the setSkewFactor() method. Override it if you need
  34631. some kind of custom mapping instead, but make sure you also implement the
  34632. inverse function in valueToProportionOfLength().
  34633. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34634. @returns the slider value that is represented by this position
  34635. @see valueToProportionOfLength
  34636. */
  34637. virtual double proportionOfLengthToValue (double proportion);
  34638. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34639. The default implementation for this performs the skewing operation that
  34640. can be set up in the setSkewFactor() method. Override it if you need
  34641. some kind of custom mapping instead, but make sure you also implement the
  34642. inverse function in proportionOfLengthToValue().
  34643. @param value a valid slider value, between the range of values specified in
  34644. setRange()
  34645. @returns a value 0 to 1.0 indicating the distance along the slider that
  34646. represents this value
  34647. @see proportionOfLengthToValue
  34648. */
  34649. virtual double valueToProportionOfLength (double value);
  34650. /** Returns the X or Y coordinate of a value along the slider's length.
  34651. If the slider is horizontal, this will be the X coordinate of the given
  34652. value, relative to the left of the slider. If it's vertical, then this will
  34653. be the Y coordinate, relative to the top of the slider.
  34654. If the slider is rotary, this will throw an assertion and return 0. If the
  34655. value is out-of-range, it will be constrained to the length of the slider.
  34656. */
  34657. float getPositionOfValue (const double value);
  34658. /** This can be overridden to allow the slider to snap to user-definable values.
  34659. If overridden, it will be called when the user tries to move the slider to
  34660. a given position, and allows a subclass to sanity-check this value, possibly
  34661. returning a different value to use instead.
  34662. @param attemptedValue the value the user is trying to enter
  34663. @param userIsDragging true if the user is dragging with the mouse; false if
  34664. they are entering the value using the text box
  34665. @returns the value to use instead
  34666. */
  34667. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  34668. /** This can be called to force the text box to update its contents.
  34669. (Not normally needed, as this is done automatically).
  34670. */
  34671. void updateText();
  34672. /** True if the slider moves horizontally. */
  34673. bool isHorizontal() const throw();
  34674. /** True if the slider moves vertically. */
  34675. bool isVertical() const throw();
  34676. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34677. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34678. methods.
  34679. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34680. */
  34681. enum ColourIds
  34682. {
  34683. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34684. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34685. and feel class how this is used. */
  34686. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34687. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34688. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34689. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34690. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34691. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34692. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34693. };
  34694. juce_UseDebuggingNewOperator
  34695. protected:
  34696. /** @internal */
  34697. void labelTextChanged (Label*);
  34698. /** @internal */
  34699. void paint (Graphics& g);
  34700. /** @internal */
  34701. void resized();
  34702. /** @internal */
  34703. void mouseDown (const MouseEvent& e);
  34704. /** @internal */
  34705. void mouseUp (const MouseEvent& e);
  34706. /** @internal */
  34707. void mouseDrag (const MouseEvent& e);
  34708. /** @internal */
  34709. void mouseDoubleClick (const MouseEvent& e);
  34710. /** @internal */
  34711. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34712. /** @internal */
  34713. void modifierKeysChanged (const ModifierKeys& modifiers);
  34714. /** @internal */
  34715. void buttonClicked (Button* button);
  34716. /** @internal */
  34717. void lookAndFeelChanged();
  34718. /** @internal */
  34719. void enablementChanged();
  34720. /** @internal */
  34721. void focusOfChildComponentChanged (FocusChangeType cause);
  34722. /** @internal */
  34723. void handleAsyncUpdate();
  34724. /** @internal */
  34725. void colourChanged();
  34726. private:
  34727. SortedSet <void*> listeners;
  34728. double currentValue, valueMin, valueMax;
  34729. double minimum, maximum, interval, doubleClickReturnValue;
  34730. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34731. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34732. int velocityModeThreshold;
  34733. float rotaryStart, rotaryEnd;
  34734. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34735. int mouseDragStartX, mouseDragStartY;
  34736. int sliderRegionStart, sliderRegionSize;
  34737. int sliderBeingDragged;
  34738. int pixelsForFullDragExtent;
  34739. Rectangle sliderRect;
  34740. String textSuffix;
  34741. SliderStyle style;
  34742. TextEntryBoxPosition textBoxPos;
  34743. int textBoxWidth, textBoxHeight;
  34744. IncDecButtonMode incDecButtonMode;
  34745. bool editableText : 1, doubleClickToValue : 1;
  34746. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34747. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34748. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34749. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34750. Font font;
  34751. Label* valueBox;
  34752. Button* incButton;
  34753. Button* decButton;
  34754. Component* popupDisplay;
  34755. Component* parentForPopupDisplay;
  34756. float getLinearSliderPos (const double value);
  34757. void restoreMouseIfHidden();
  34758. void sendDragStart();
  34759. void sendDragEnd();
  34760. double constrainedValue (double value) const throw();
  34761. void triggerChangeMessage (const bool synchronous);
  34762. bool incDecDragDirectionIsHorizontal() const throw();
  34763. Slider (const Slider&);
  34764. const Slider& operator= (const Slider&);
  34765. };
  34766. #endif // __JUCE_SLIDER_JUCEHEADER__
  34767. /********* End of inlined file: juce_Slider.h *********/
  34768. #endif
  34769. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34770. #endif
  34771. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34772. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  34773. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34774. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34775. class TableHeaderComponent;
  34776. /**
  34777. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  34778. You can register one of these objects for table events using TableHeaderComponent::addListener()
  34779. and TableHeaderComponent::removeListener().
  34780. @see TableHeaderComponent
  34781. */
  34782. class JUCE_API TableHeaderListener
  34783. {
  34784. public:
  34785. TableHeaderListener() {}
  34786. /** Destructor. */
  34787. virtual ~TableHeaderListener() {}
  34788. /** This is called when some of the table's columns are added, removed, hidden,
  34789. or rearranged.
  34790. */
  34791. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  34792. /** This is called when one or more of the table's columns are resized.
  34793. */
  34794. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  34795. /** This is called when the column by which the table should be sorted is changed.
  34796. */
  34797. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  34798. /** This is called when the user begins or ends dragging one of the columns around.
  34799. When the user starts dragging a column, this is called with the ID of that
  34800. column. When they finish dragging, it is called again with 0 as the ID.
  34801. */
  34802. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  34803. int columnIdNowBeingDragged);
  34804. };
  34805. /**
  34806. A component that displays a strip of column headings for a table, and allows these
  34807. to be resized, dragged around, etc.
  34808. This is just the component that goes at the top of a table. You can use it
  34809. directly for custom components, or to create a simple table, use the
  34810. TableListBox class.
  34811. To use one of these, create it and use addColumn() to add all the columns that you need.
  34812. Each column must be given a unique ID number that's used to refer to it.
  34813. @see TableListBox, TableHeaderListener
  34814. */
  34815. class JUCE_API TableHeaderComponent : public Component,
  34816. private AsyncUpdater
  34817. {
  34818. public:
  34819. /** Creates an empty table header.
  34820. */
  34821. TableHeaderComponent();
  34822. /** Destructor. */
  34823. ~TableHeaderComponent();
  34824. /** A combination of these flags are passed into the addColumn() method to specify
  34825. the properties of a column.
  34826. */
  34827. enum ColumnPropertyFlags
  34828. {
  34829. 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. */
  34830. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  34831. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  34832. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  34833. 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. */
  34834. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  34835. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  34836. /** This set of default flags is used as the default parameter value in addColumn(). */
  34837. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  34838. /** A quick way of combining flags for a column that's not resizable. */
  34839. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  34840. /** A quick way of combining flags for a column that's not resizable or sortable. */
  34841. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  34842. /** A quick way of combining flags for a column that's not sortable. */
  34843. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  34844. };
  34845. /** Adds a column to the table.
  34846. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  34847. registered listeners.
  34848. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  34849. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  34850. a unique ID. This is used to identify the column later on, after the user may have
  34851. changed the order that they appear in
  34852. @param width the initial width of the column, in pixels
  34853. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  34854. if the 'resizable' flag is specified for this column
  34855. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  34856. if the 'resizable' flag is specified for this column
  34857. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  34858. properties of this column
  34859. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  34860. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  34861. all columns, not just the index amongst those that are currently visible
  34862. */
  34863. void addColumn (const String& columnName,
  34864. const int columnId,
  34865. const int width,
  34866. const int minimumWidth = 30,
  34867. const int maximumWidth = -1,
  34868. const int propertyFlags = defaultFlags,
  34869. const int insertIndex = -1);
  34870. /** Removes a column with the given ID.
  34871. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  34872. registered listeners.
  34873. */
  34874. void removeColumn (const int columnIdToRemove);
  34875. /** Deletes all columns from the table.
  34876. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  34877. registered listeners.
  34878. */
  34879. void removeAllColumns();
  34880. /** Returns the number of columns in the table.
  34881. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  34882. return the total number of columns, including hidden ones.
  34883. @see isColumnVisible
  34884. */
  34885. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  34886. /** Returns the name for a column.
  34887. @see setColumnName
  34888. */
  34889. const String getColumnName (const int columnId) const throw();
  34890. /** Changes the name of a column. */
  34891. void setColumnName (const int columnId, const String& newName);
  34892. /** Moves a column to a different index in the table.
  34893. @param columnId the column to move
  34894. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  34895. */
  34896. void moveColumn (const int columnId, int newVisibleIndex);
  34897. /** Changes the width of a column.
  34898. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  34899. */
  34900. void setColumnWidth (const int columnId, const int newWidth);
  34901. /** Shows or hides a column.
  34902. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  34903. @see isColumnVisible
  34904. */
  34905. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  34906. /** Returns true if this column is currently visible.
  34907. @see setColumnVisible
  34908. */
  34909. bool isColumnVisible (const int columnId) const;
  34910. /** Changes the column which is the sort column.
  34911. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  34912. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  34913. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  34914. @see getSortColumnId, isSortedForwards, reSortTable
  34915. */
  34916. void setSortColumnId (const int columnId, const bool sortForwards);
  34917. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  34918. @see setSortColumnId, isSortedForwards
  34919. */
  34920. int getSortColumnId() const throw();
  34921. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  34922. @see setSortColumnId
  34923. */
  34924. bool isSortedForwards() const throw();
  34925. /** Triggers a re-sort of the table according to the current sort-column.
  34926. If you modifiy the table's contents, you can call this to signal that the table needs
  34927. to be re-sorted.
  34928. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  34929. tableSortOrderChanged() method of any listeners).
  34930. */
  34931. void reSortTable();
  34932. /** Returns the total width of all the visible columns in the table.
  34933. */
  34934. int getTotalWidth() const throw();
  34935. /** Returns the index of a given column.
  34936. If there's no such column ID, this will return -1.
  34937. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  34938. otherwise it'll return the index amongst all the columns, including any hidden ones.
  34939. */
  34940. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  34941. /** Returns the ID of the column at a given index.
  34942. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  34943. otherwise it'll count it amongst all the columns, including any hidden ones.
  34944. If the index is out-of-range, it'll return 0.
  34945. */
  34946. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  34947. /** Returns the rectangle containing of one of the columns.
  34948. The index is an index from 0 to the number of columns that are currently visible (hidden
  34949. ones are not counted). It returns a rectangle showing the position of the column relative
  34950. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  34951. */
  34952. const Rectangle getColumnPosition (const int index) const throw();
  34953. /** Finds the column ID at a given x-position in the component.
  34954. If there is a column at this point this returns its ID, or if not, it will return 0.
  34955. */
  34956. int getColumnIdAtX (const int xToFind) const throw();
  34957. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  34958. entire width of the component.
  34959. By default this is disabled. Turning it on also means that when resizing a column, those
  34960. on the right will be squashed to fit.
  34961. */
  34962. void setStretchToFitActive (const bool shouldStretchToFit);
  34963. /** Returns true if stretch-to-fit has been enabled.
  34964. @see setStretchToFitActive
  34965. */
  34966. bool isStretchToFitActive() const throw();
  34967. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34968. specified width, keeping their relative proportions the same.
  34969. If the minimum widths of the columns are too wide to fit into this space, it may
  34970. actually end up wider.
  34971. */
  34972. void resizeAllColumnsToFit (int targetTotalWidth);
  34973. /** Enables or disables the pop-up menu.
  34974. The default menu allows the user to show or hide columns. You can add custom
  34975. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34976. By default the menu is enabled.
  34977. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34978. */
  34979. void setPopupMenuActive (const bool hasMenu);
  34980. /** Returns true if the pop-up menu is enabled.
  34981. @see setPopupMenuActive
  34982. */
  34983. bool isPopupMenuActive() const throw();
  34984. /** Returns a string that encapsulates the table's current layout.
  34985. This can be restored later using restoreFromString(). It saves the order of
  34986. the columns, the currently-sorted column, and the widths.
  34987. @see restoreFromString
  34988. */
  34989. const String toString() const;
  34990. /** Restores the state of the table, based on a string previously created with
  34991. toString().
  34992. @see toString
  34993. */
  34994. void restoreFromString (const String& storedVersion);
  34995. /** Adds a listener to be informed about things that happen to the header. */
  34996. void addListener (TableHeaderListener* const newListener) throw();
  34997. /** Removes a previously-registered listener. */
  34998. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  34999. /** This can be overridden to handle a mouse-click on one of the column headers.
  35000. The default implementation will use this click to call getSortColumnId() and
  35001. change the sort order.
  35002. */
  35003. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  35004. /** This can be overridden to add custom items to the pop-up menu.
  35005. If you override this, you should call the superclass's method to add its
  35006. column show/hide items, if you want them on the menu as well.
  35007. Then to handle the result, override reactToMenuItem().
  35008. @see reactToMenuItem
  35009. */
  35010. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  35011. /** Override this to handle any custom items that you have added to the
  35012. pop-up menu with an addMenuItems() override.
  35013. If the menuReturnId isn't one of your own custom menu items, you'll need to
  35014. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  35015. handle the items that it had added.
  35016. @see addMenuItems
  35017. */
  35018. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  35019. /** @internal */
  35020. void paint (Graphics& g);
  35021. /** @internal */
  35022. void resized();
  35023. /** @internal */
  35024. void mouseMove (const MouseEvent&);
  35025. /** @internal */
  35026. void mouseEnter (const MouseEvent&);
  35027. /** @internal */
  35028. void mouseExit (const MouseEvent&);
  35029. /** @internal */
  35030. void mouseDown (const MouseEvent&);
  35031. /** @internal */
  35032. void mouseDrag (const MouseEvent&);
  35033. /** @internal */
  35034. void mouseUp (const MouseEvent&);
  35035. /** @internal */
  35036. const MouseCursor getMouseCursor();
  35037. /** Can be overridden for more control over the pop-up menu behaviour. */
  35038. virtual void showColumnChooserMenu (const int columnIdClicked);
  35039. juce_UseDebuggingNewOperator
  35040. private:
  35041. struct ColumnInfo
  35042. {
  35043. String name;
  35044. int id, propertyFlags, width, minimumWidth, maximumWidth;
  35045. double lastDeliberateWidth;
  35046. bool isVisible() const throw();
  35047. };
  35048. OwnedArray <ColumnInfo> columns;
  35049. Array <TableHeaderListener*> listeners;
  35050. Component* dragOverlayComp;
  35051. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  35052. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  35053. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  35054. ColumnInfo* getInfoForId (const int columnId) const throw();
  35055. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  35056. void sendColumnsChanged();
  35057. void handleAsyncUpdate();
  35058. void beginDrag (const MouseEvent&);
  35059. void endDrag (const int finalIndex);
  35060. int getResizeDraggerAt (const int mouseX) const throw();
  35061. void updateColumnUnderMouse (int x, int y);
  35062. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  35063. TableHeaderComponent (const TableHeaderComponent&);
  35064. const TableHeaderComponent operator= (const TableHeaderComponent&);
  35065. };
  35066. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35067. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  35068. #endif
  35069. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35070. /********* Start of inlined file: juce_TableListBox.h *********/
  35071. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35072. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  35073. /**
  35074. One of these is used by a TableListBox as the data model for the table's contents.
  35075. The virtual methods that you override in this class take care of drawing the
  35076. table cells, and reacting to events.
  35077. @see TableListBox
  35078. */
  35079. class JUCE_API TableListBoxModel
  35080. {
  35081. public:
  35082. TableListBoxModel() {}
  35083. /** Destructor. */
  35084. virtual ~TableListBoxModel() {}
  35085. /** This must return the number of rows currently in the table.
  35086. If the number of rows changes, you must call TableListBox::updateContent() to
  35087. cause it to refresh the list.
  35088. */
  35089. virtual int getNumRows() = 0;
  35090. /** This must draw the background behind one of the rows in the table.
  35091. The graphics context has its origin at the row's top-left, and your method
  35092. should fill the area specified by the width and height parameters.
  35093. */
  35094. virtual void paintRowBackground (Graphics& g,
  35095. int rowNumber,
  35096. int width, int height,
  35097. bool rowIsSelected) = 0;
  35098. /** This must draw one of the cells.
  35099. The graphics context's origin will already be set to the top-left of the cell,
  35100. whose size is specified by (width, height).
  35101. */
  35102. virtual void paintCell (Graphics& g,
  35103. int rowNumber,
  35104. int columnId,
  35105. int width, int height,
  35106. bool rowIsSelected) = 0;
  35107. /** This is used to create or update a custom component to go in a cell.
  35108. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  35109. and handle mouse clicks with cellClicked().
  35110. This method will be called whenever a custom component might need to be updated - e.g.
  35111. when the table is changed, or TableListBox::updateContent() is called.
  35112. If you don't need a custom component for the specified cell, then return 0.
  35113. If you do want a custom component, and the existingComponentToUpdate is null, then
  35114. this method must create a new component suitable for the cell, and return it.
  35115. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35116. by this method. In this case, the method must either update it to make sure it's correctly representing
  35117. the given cell (which may be different from the one that the component was created for), or it can
  35118. delete this component and return a new one.
  35119. */
  35120. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  35121. Component* existingComponentToUpdate);
  35122. /** This callback is made when the user clicks on one of the cells in the table.
  35123. The mouse event's coordinates will be relative to the entire table row.
  35124. @see cellDoubleClicked, backgroundClicked
  35125. */
  35126. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  35127. /** This callback is made when the user clicks on one of the cells in the table.
  35128. The mouse event's coordinates will be relative to the entire table row.
  35129. @see cellClicked, backgroundClicked
  35130. */
  35131. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  35132. /** This can be overridden to react to the user double-clicking on a part of the list where
  35133. there are no rows.
  35134. @see cellClicked
  35135. */
  35136. virtual void backgroundClicked();
  35137. /** This callback is made when the table's sort order is changed.
  35138. This could be because the user has clicked a column header, or because the
  35139. TableHeaderComponent::setSortColumnId() method was called.
  35140. If you implement this, your method should re-sort the table using the given
  35141. column as the key.
  35142. */
  35143. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  35144. /** Returns the best width for one of the columns.
  35145. If you implement this method, you should measure the width of all the items
  35146. in this column, and return the best size.
  35147. Returning 0 means that the column shouldn't be changed.
  35148. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  35149. */
  35150. virtual int getColumnAutoSizeWidth (int columnId);
  35151. /** Override this to be informed when rows are selected or deselected.
  35152. @see ListBox::selectedRowsChanged()
  35153. */
  35154. virtual void selectedRowsChanged (int lastRowSelected);
  35155. /** Override this to be informed when the delete key is pressed.
  35156. @see ListBox::deleteKeyPressed()
  35157. */
  35158. virtual void deleteKeyPressed (int lastRowSelected);
  35159. /** Override this to be informed when the return key is pressed.
  35160. @see ListBox::returnKeyPressed()
  35161. */
  35162. virtual void returnKeyPressed (int lastRowSelected);
  35163. /** Override this to be informed when the list is scrolled.
  35164. This might be caused by the user moving the scrollbar, or by programmatic changes
  35165. to the list position.
  35166. */
  35167. virtual void listWasScrolled();
  35168. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  35169. If this returns a non-empty name then when the user drags a row, the table will try to
  35170. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  35171. drag-and-drop operation, using this string as the source description, and the listbox
  35172. itself as the source component.
  35173. @see DragAndDropContainer::startDragging
  35174. */
  35175. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35176. };
  35177. /**
  35178. A table of cells, using a TableHeaderComponent as its header.
  35179. This component makes it easy to create a table by providing a TableListBoxModel as
  35180. the data source.
  35181. @see TableListBoxModel, TableHeaderComponent
  35182. */
  35183. class JUCE_API TableListBox : public ListBox,
  35184. private ListBoxModel,
  35185. private TableHeaderListener
  35186. {
  35187. public:
  35188. /** Creates a TableListBox.
  35189. The model pointer passed-in can be null, in which case you can set it later
  35190. with setModel().
  35191. */
  35192. TableListBox (const String& componentName,
  35193. TableListBoxModel* const model);
  35194. /** Destructor. */
  35195. ~TableListBox();
  35196. /** Changes the TableListBoxModel that is being used for this table.
  35197. */
  35198. void setModel (TableListBoxModel* const newModel);
  35199. /** Returns the model currently in use. */
  35200. TableListBoxModel* getModel() const throw() { return model; }
  35201. /** Returns the header component being used in this table. */
  35202. TableHeaderComponent* getHeader() const throw() { return header; }
  35203. /** Changes the height of the table header component.
  35204. @see getHeaderHeight
  35205. */
  35206. void setHeaderHeight (const int newHeight);
  35207. /** Returns the height of the table header.
  35208. @see setHeaderHeight
  35209. */
  35210. int getHeaderHeight() const throw();
  35211. /** Resizes a column to fit its contents.
  35212. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  35213. and applies that to the column.
  35214. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  35215. */
  35216. void autoSizeColumn (const int columnId);
  35217. /** Calls autoSizeColumn() for all columns in the table. */
  35218. void autoSizeAllColumns();
  35219. /** Enables or disables the auto size options on the popup menu.
  35220. By default, these are enabled.
  35221. */
  35222. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  35223. /** True if the auto-size options should be shown on the menu.
  35224. @see setAutoSizeMenuOptionsShown
  35225. */
  35226. bool isAutoSizeMenuOptionShown() const throw();
  35227. /** Returns the position of one of the cells in the table.
  35228. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  35229. the table component's top-left. The row number isn't checked to see if it's
  35230. in-range, but the column ID must exist or this will return an empty rectangle.
  35231. If relativeToComponentTopLeft is false, the co-ords are relative to the
  35232. top-left of the table's top-left cell.
  35233. */
  35234. const Rectangle getCellPosition (const int columnId,
  35235. const int rowNumber,
  35236. const bool relativeToComponentTopLeft) const;
  35237. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  35238. @see ListBox::scrollToEnsureRowIsOnscreen
  35239. */
  35240. void scrollToEnsureColumnIsOnscreen (const int columnId);
  35241. /** @internal */
  35242. int getNumRows();
  35243. /** @internal */
  35244. void paintListBoxItem (int, Graphics&, int, int, bool);
  35245. /** @internal */
  35246. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35247. /** @internal */
  35248. void selectedRowsChanged (int lastRowSelected);
  35249. /** @internal */
  35250. void deleteKeyPressed (int currentSelectedRow);
  35251. /** @internal */
  35252. void returnKeyPressed (int currentSelectedRow);
  35253. /** @internal */
  35254. void backgroundClicked();
  35255. /** @internal */
  35256. void listWasScrolled();
  35257. /** @internal */
  35258. void tableColumnsChanged (TableHeaderComponent*);
  35259. /** @internal */
  35260. void tableColumnsResized (TableHeaderComponent*);
  35261. /** @internal */
  35262. void tableSortOrderChanged (TableHeaderComponent*);
  35263. /** @internal */
  35264. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  35265. /** @internal */
  35266. void resized();
  35267. juce_UseDebuggingNewOperator
  35268. private:
  35269. TableHeaderComponent* header;
  35270. TableListBoxModel* model;
  35271. int columnIdNowBeingDragged;
  35272. bool autoSizeOptionsShown;
  35273. void updateColumnComponents() const;
  35274. TableListBox (const TableListBox&);
  35275. const TableListBox& operator= (const TableListBox&);
  35276. };
  35277. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  35278. /********* End of inlined file: juce_TableListBox.h *********/
  35279. #endif
  35280. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  35281. #endif
  35282. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35283. #endif
  35284. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35285. #endif
  35286. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35287. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  35288. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35289. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35290. /**
  35291. A factory object which can create ToolbarItemComponent objects.
  35292. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  35293. that it can create.
  35294. Each type of item is identified by a unique ID, and multiple instances of an
  35295. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  35296. bars).
  35297. @see Toolbar, ToolbarItemComponent, ToolbarButton
  35298. */
  35299. class JUCE_API ToolbarItemFactory
  35300. {
  35301. public:
  35302. ToolbarItemFactory();
  35303. /** Destructor. */
  35304. virtual ~ToolbarItemFactory();
  35305. /** A set of reserved item ID values, used for the built-in item types.
  35306. */
  35307. enum SpecialItemIds
  35308. {
  35309. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  35310. can be placed between sets of items to break them into groups. */
  35311. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  35312. items.*/
  35313. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  35314. either side of it, filling any available space. */
  35315. };
  35316. /** Must return a list of the IDs for all the item types that this factory can create.
  35317. The ids should be added to the array that is passed-in.
  35318. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  35319. and the predefined IDs in the SpecialItemIds enum.
  35320. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  35321. to this list if you want your toolbar to be able to contain those items.
  35322. The list returned here is used by the ToolbarItemPalette class to obtain its list
  35323. of available items, and their order on the palette will reflect the order in which
  35324. they appear on this list.
  35325. @see ToolbarItemPalette
  35326. */
  35327. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  35328. /** Must return the set of items that should be added to a toolbar as its default set.
  35329. This method is used by Toolbar::addDefaultItems() to determine which items to
  35330. create.
  35331. The items that your method adds to the array that is passed-in will be added to the
  35332. toolbar in the same order. Items can appear in the list more than once.
  35333. */
  35334. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  35335. /** Must create an instance of one of the items that the factory lists in its
  35336. getAllToolbarItemIds() method.
  35337. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  35338. method, except for the built-in item types from the SpecialItemIds enum, which
  35339. are created internally by the toolbar code.
  35340. Try not to keep a pointer to the object that is returned, as it will be deleted
  35341. automatically by the toolbar, and remember that multiple instances of the same
  35342. item type are likely to exist at the same time.
  35343. */
  35344. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  35345. };
  35346. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35347. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  35348. #endif
  35349. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35350. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  35351. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35352. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35353. /**
  35354. A component containing a list of toolbar items, which the user can drag onto
  35355. a toolbar to add them.
  35356. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  35357. which automatically shows one of these in a dialog box with lots of extra controls.
  35358. @see Toolbar
  35359. */
  35360. class JUCE_API ToolbarItemPalette : public Component,
  35361. public DragAndDropContainer
  35362. {
  35363. public:
  35364. /** Creates a palette of items for a given factory, with the aim of adding them
  35365. to the specified toolbar.
  35366. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  35367. set of items that are shown in this palette.
  35368. The toolbar and factory must not be deleted while this object exists.
  35369. */
  35370. ToolbarItemPalette (ToolbarItemFactory& factory,
  35371. Toolbar* const toolbar);
  35372. /** Destructor. */
  35373. ~ToolbarItemPalette();
  35374. /** @internal */
  35375. void resized();
  35376. juce_UseDebuggingNewOperator
  35377. private:
  35378. ToolbarItemFactory& factory;
  35379. Toolbar* toolbar;
  35380. Viewport* viewport;
  35381. friend class Toolbar;
  35382. void replaceComponent (ToolbarItemComponent* const comp);
  35383. ToolbarItemPalette (const ToolbarItemPalette&);
  35384. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  35385. };
  35386. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35387. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  35388. #endif
  35389. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35390. #endif
  35391. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35392. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  35393. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35394. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35395. /**
  35396. A PropertyComponent that contains an on/off toggle button.
  35397. This type of property component can be used if you have a boolean value to
  35398. toggle on/off.
  35399. @see PropertyComponent
  35400. */
  35401. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  35402. private ButtonListener
  35403. {
  35404. public:
  35405. /** Creates a button component.
  35406. @param propertyName the property name to be passed to the PropertyComponent
  35407. @param buttonTextWhenTrue the text shown in the button when the value is true
  35408. @param buttonTextWhenFalse the text shown in the button when the value is false
  35409. */
  35410. BooleanPropertyComponent (const String& propertyName,
  35411. const String& buttonTextWhenTrue,
  35412. const String& buttonTextWhenFalse);
  35413. /** Destructor. */
  35414. ~BooleanPropertyComponent();
  35415. /** Called to change the state of the boolean value. */
  35416. virtual void setState (const bool newState) = 0;
  35417. /** Must return the current value of the property. */
  35418. virtual bool getState() const = 0;
  35419. /** @internal */
  35420. void paint (Graphics& g);
  35421. /** @internal */
  35422. void refresh();
  35423. /** @internal */
  35424. void buttonClicked (Button*);
  35425. juce_UseDebuggingNewOperator
  35426. private:
  35427. ToggleButton* button;
  35428. String onText, offText;
  35429. };
  35430. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35431. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  35432. #endif
  35433. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35434. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  35435. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35436. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35437. /**
  35438. A PropertyComponent that contains a button.
  35439. This type of property component can be used if you need a button to trigger some
  35440. kind of action.
  35441. @see PropertyComponent
  35442. */
  35443. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  35444. private ButtonListener
  35445. {
  35446. public:
  35447. /** Creates a button component.
  35448. @param propertyName the property name to be passed to the PropertyComponent
  35449. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  35450. */
  35451. ButtonPropertyComponent (const String& propertyName,
  35452. const bool triggerOnMouseDown);
  35453. /** Destructor. */
  35454. ~ButtonPropertyComponent();
  35455. /** Called when the user clicks the button.
  35456. */
  35457. virtual void buttonClicked() = 0;
  35458. /** Returns the string that should be displayed in the button.
  35459. If you need to change this string, call refresh() to update the component.
  35460. */
  35461. virtual const String getButtonText() const = 0;
  35462. /** @internal */
  35463. void refresh();
  35464. /** @internal */
  35465. void buttonClicked (Button*);
  35466. juce_UseDebuggingNewOperator
  35467. private:
  35468. TextButton* button;
  35469. };
  35470. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35471. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  35472. #endif
  35473. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35474. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  35475. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35476. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35477. /**
  35478. A PropertyComponent that shows its value as a combo box.
  35479. This type of property component contains a list of options and has a
  35480. combo box to choose one.
  35481. Your subclass's constructor must add some strings to the choices StringArray
  35482. and these are shown in the list.
  35483. The getIndex() method will be called to find out which option is the currently
  35484. selected one. If you call refresh() it will call getIndex() to check whether
  35485. the value has changed, and will update the combo box if needed.
  35486. If the user selects a different item from the list, setIndex() will be
  35487. called to let your class process this.
  35488. @see PropertyComponent, PropertyPanel
  35489. */
  35490. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  35491. private ComboBoxListener
  35492. {
  35493. public:
  35494. /** Creates the component.
  35495. Your subclass's constructor must add a list of options to the choices
  35496. member variable.
  35497. */
  35498. ChoicePropertyComponent (const String& propertyName);
  35499. /** Destructor. */
  35500. ~ChoicePropertyComponent();
  35501. /** Called when the user selects an item from the combo box.
  35502. Your subclass must use this callback to update the value that this component
  35503. represents. The index is the index of the chosen item in the choices
  35504. StringArray.
  35505. */
  35506. virtual void setIndex (const int newIndex) = 0;
  35507. /** Returns the index of the item that should currently be shown.
  35508. This is the index of the item in the choices StringArray that will be
  35509. shown.
  35510. */
  35511. virtual int getIndex() const = 0;
  35512. /** Returns the list of options. */
  35513. const StringArray& getChoices() const throw();
  35514. /** @internal */
  35515. void refresh();
  35516. /** @internal */
  35517. void comboBoxChanged (ComboBox*);
  35518. juce_UseDebuggingNewOperator
  35519. protected:
  35520. /** The list of options that will be shown in the combo box.
  35521. Your subclass must populate this array in its constructor. If any empty
  35522. strings are added, these will be replaced with horizontal separators (see
  35523. ComboBox::addSeparator() for more info).
  35524. */
  35525. StringArray choices;
  35526. private:
  35527. ComboBox* comboBox;
  35528. };
  35529. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35530. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  35531. #endif
  35532. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35533. #endif
  35534. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35535. #endif
  35536. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35537. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  35538. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35539. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35540. /**
  35541. A PropertyComponent that shows its value as a slider.
  35542. @see PropertyComponent, Slider
  35543. */
  35544. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  35545. private SliderListener
  35546. {
  35547. public:
  35548. /** Creates the property component.
  35549. The ranges, interval and skew factor are passed to the Slider component.
  35550. If you need to customise the slider in other ways, your constructor can
  35551. access the slider member variable and change it directly.
  35552. */
  35553. SliderPropertyComponent (const String& propertyName,
  35554. const double rangeMin,
  35555. const double rangeMax,
  35556. const double interval,
  35557. const double skewFactor = 1.0);
  35558. /** Destructor. */
  35559. ~SliderPropertyComponent();
  35560. /** Called when the user moves the slider to change its value.
  35561. Your subclass must use this method to update whatever item this property
  35562. represents.
  35563. */
  35564. virtual void setValue (const double newValue) = 0;
  35565. /** Returns the value that the slider should show. */
  35566. virtual const double getValue() const = 0;
  35567. /** @internal */
  35568. void refresh();
  35569. /** @internal */
  35570. void changeListenerCallback (void*);
  35571. /** @internal */
  35572. void sliderValueChanged (Slider*);
  35573. juce_UseDebuggingNewOperator
  35574. protected:
  35575. /** The slider component being used in this component.
  35576. Your subclass has access to this in case it needs to customise it in some way.
  35577. */
  35578. Slider* slider;
  35579. };
  35580. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35581. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  35582. #endif
  35583. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35584. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  35585. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35586. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35587. /**
  35588. A PropertyComponent that shows its value as editable text.
  35589. @see PropertyComponent
  35590. */
  35591. class JUCE_API TextPropertyComponent : public PropertyComponent
  35592. {
  35593. public:
  35594. /** Creates a text property component.
  35595. The maxNumChars is used to set the length of string allowable, and isMultiLine
  35596. sets whether the text editor allows carriage returns.
  35597. @see TextEditor
  35598. */
  35599. TextPropertyComponent (const String& propertyName,
  35600. const int maxNumChars,
  35601. const bool isMultiLine);
  35602. /** Destructor. */
  35603. ~TextPropertyComponent();
  35604. /** Called when the user edits the text.
  35605. Your subclass must use this callback to change the value of whatever item
  35606. this property component represents.
  35607. */
  35608. virtual void setText (const String& newText) = 0;
  35609. /** Returns the text that should be shown in the text editor.
  35610. */
  35611. virtual const String getText() const = 0;
  35612. /** @internal */
  35613. void refresh();
  35614. /** @internal */
  35615. void textWasEdited();
  35616. juce_UseDebuggingNewOperator
  35617. private:
  35618. Label* textEditor;
  35619. };
  35620. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35621. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  35622. #endif
  35623. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  35624. #endif
  35625. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  35626. #endif
  35627. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35628. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  35629. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35630. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35631. /** An object that watches for any movement of a component or any of its parent components.
  35632. This makes it easy to check when a component is moved relative to its top-level
  35633. peer window. The normal Component::moved() method is only called when a component
  35634. moves relative to its immediate parent, and sometimes you want to know if any of
  35635. components higher up the tree have moved (which of course will affect the overall
  35636. position of all their sub-components).
  35637. It also includes a callback that lets you know when the top-level peer is changed.
  35638. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  35639. because they need to keep their custom windows in the right place and respond to
  35640. changes in the peer.
  35641. */
  35642. class JUCE_API ComponentMovementWatcher : public ComponentListener
  35643. {
  35644. public:
  35645. /** Creates a ComponentMovementWatcher to watch a given target component. */
  35646. ComponentMovementWatcher (Component* const component);
  35647. /** Destructor. */
  35648. ~ComponentMovementWatcher();
  35649. /** This callback happens when the component that is being watched is moved
  35650. relative to its top-level peer window, or when it is resized.
  35651. */
  35652. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  35653. /** This callback happens when the component's top-level peer is changed.
  35654. */
  35655. virtual void componentPeerChanged() = 0;
  35656. juce_UseDebuggingNewOperator
  35657. /** @internal */
  35658. void componentParentHierarchyChanged (Component& component);
  35659. /** @internal */
  35660. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35661. private:
  35662. Component* const component;
  35663. ComponentPeer* lastPeer;
  35664. VoidArray registeredParentComps;
  35665. bool reentrant;
  35666. int lastX, lastY, lastWidth, lastHeight;
  35667. #ifdef JUCE_DEBUG
  35668. ComponentDeletionWatcher* deletionWatcher;
  35669. #endif
  35670. void unregister() throw();
  35671. void registerWithParentComps() throw();
  35672. ComponentMovementWatcher (const ComponentMovementWatcher&);
  35673. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  35674. };
  35675. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35676. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  35677. #endif
  35678. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35679. /********* Start of inlined file: juce_GroupComponent.h *********/
  35680. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35681. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35682. /**
  35683. A component that draws an outline around itself and has an optional title at
  35684. the top, for drawing an outline around a group of controls.
  35685. */
  35686. class JUCE_API GroupComponent : public Component
  35687. {
  35688. public:
  35689. /** Creates a GroupComponent.
  35690. @param componentName the name to give the component
  35691. @param labelText the text to show at the top of the outline
  35692. */
  35693. GroupComponent (const String& componentName,
  35694. const String& labelText);
  35695. /** Destructor. */
  35696. ~GroupComponent();
  35697. /** Changes the text that's shown at the top of the component. */
  35698. void setText (const String& newText) throw();
  35699. /** Returns the currently displayed text label. */
  35700. const String getText() const throw();
  35701. /** Sets the positioning of the text label.
  35702. (The default is Justification::left)
  35703. @see getTextLabelPosition
  35704. */
  35705. void setTextLabelPosition (const Justification& justification);
  35706. /** Returns the current text label position.
  35707. @see setTextLabelPosition
  35708. */
  35709. const Justification getTextLabelPosition() const throw() { return justification; }
  35710. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35711. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35712. methods.
  35713. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35714. */
  35715. enum ColourIds
  35716. {
  35717. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  35718. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  35719. };
  35720. /** @internal */
  35721. void paint (Graphics& g);
  35722. /** @internal */
  35723. void enablementChanged();
  35724. /** @internal */
  35725. void colourChanged();
  35726. private:
  35727. String text;
  35728. Justification justification;
  35729. GroupComponent (const GroupComponent&);
  35730. const GroupComponent& operator= (const GroupComponent&);
  35731. };
  35732. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35733. /********* End of inlined file: juce_GroupComponent.h *********/
  35734. #endif
  35735. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35736. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  35737. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35738. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35739. /********* Start of inlined file: juce_TabbedComponent.h *********/
  35740. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35741. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35742. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  35743. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35744. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35745. class TabbedButtonBar;
  35746. /** In a TabbedButtonBar, this component is used for each of the buttons.
  35747. If you want to create a TabbedButtonBar with custom tab components, derive
  35748. your component from this class, and override the TabbedButtonBar::createTabButton()
  35749. method to create it instead of the default one.
  35750. @see TabbedButtonBar
  35751. */
  35752. class JUCE_API TabBarButton : public Button
  35753. {
  35754. public:
  35755. /** Creates the tab button. */
  35756. TabBarButton (const String& name,
  35757. TabbedButtonBar* const ownerBar,
  35758. const int tabIndex);
  35759. /** Destructor. */
  35760. ~TabBarButton();
  35761. /** Chooses the best length for the tab, given the specified depth.
  35762. If the tab is horizontal, this should return its width, and the depth
  35763. specifies its height. If it's vertical, it should return the height, and
  35764. the depth is actually its width.
  35765. */
  35766. virtual int getBestTabLength (const int depth);
  35767. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35768. void clicked (const ModifierKeys& mods);
  35769. bool hitTest (int x, int y);
  35770. juce_UseDebuggingNewOperator
  35771. protected:
  35772. friend class TabbedButtonBar;
  35773. TabbedButtonBar* const owner;
  35774. int tabIndex, overlapPixels;
  35775. DropShadowEffect shadow;
  35776. /** Returns an area of the component that's safe to draw in.
  35777. This deals with the orientation of the tabs, which affects which side is
  35778. touching the tabbed box's content component.
  35779. */
  35780. void getActiveArea (int& x, int& y, int& w, int& h);
  35781. private:
  35782. TabBarButton (const TabBarButton&);
  35783. const TabBarButton& operator= (const TabBarButton&);
  35784. };
  35785. /**
  35786. A vertical or horizontal bar containing tabs that you can select.
  35787. You can use one of these to generate things like a dialog box that has
  35788. tabbed pages you can flip between. Attach a ChangeListener to the
  35789. button bar to be told when the user changes the page.
  35790. An easier method than doing this is to use a TabbedComponent, which
  35791. contains its own TabbedButtonBar and which takes care of the layout
  35792. and other housekeeping.
  35793. @see TabbedComponent
  35794. */
  35795. class JUCE_API TabbedButtonBar : public Component,
  35796. public ChangeBroadcaster,
  35797. public ButtonListener
  35798. {
  35799. public:
  35800. /** The placement of the tab-bar
  35801. @see setOrientation, getOrientation
  35802. */
  35803. enum Orientation
  35804. {
  35805. TabsAtTop,
  35806. TabsAtBottom,
  35807. TabsAtLeft,
  35808. TabsAtRight
  35809. };
  35810. /** Creates a TabbedButtonBar with a given placement.
  35811. You can change the orientation later if you need to.
  35812. */
  35813. TabbedButtonBar (const Orientation orientation);
  35814. /** Destructor. */
  35815. ~TabbedButtonBar();
  35816. /** Changes the bar's orientation.
  35817. This won't change the bar's actual size - you'll need to do that yourself,
  35818. but this determines which direction the tabs go in, and which side they're
  35819. stuck to.
  35820. */
  35821. void setOrientation (const Orientation orientation);
  35822. /** Returns the current orientation.
  35823. @see setOrientation
  35824. */
  35825. Orientation getOrientation() const throw() { return orientation; }
  35826. /** Deletes all the tabs from the bar.
  35827. @see addTab
  35828. */
  35829. void clearTabs();
  35830. /** Adds a tab to the bar.
  35831. Tabs are added in left-to-right reading order.
  35832. If this is the first tab added, it'll also be automatically selected.
  35833. */
  35834. void addTab (const String& tabName,
  35835. const Colour& tabBackgroundColour,
  35836. int insertIndex = -1);
  35837. /** Changes the name of one of the tabs. */
  35838. void setTabName (const int tabIndex,
  35839. const String& newName);
  35840. /** Gets rid of one of the tabs. */
  35841. void removeTab (const int tabIndex);
  35842. /** Moves a tab to a new index in the list.
  35843. Pass -1 as the index to move it to the end of the list.
  35844. */
  35845. void moveTab (const int currentIndex,
  35846. const int newIndex);
  35847. /** Returns the number of tabs in the bar. */
  35848. int getNumTabs() const;
  35849. /** Returns a list of all the tab names in the bar. */
  35850. const StringArray getTabNames() const;
  35851. /** Changes the currently selected tab.
  35852. This will send a change message and cause a synchronous callback to
  35853. the currentTabChanged() method. (But if the given tab is already selected,
  35854. nothing will be done).
  35855. To deselect all the tabs, use an index of -1.
  35856. */
  35857. void setCurrentTabIndex (int newTabIndex, const bool sendChangeMessage = true);
  35858. /** Returns the name of the currently selected tab.
  35859. This could be an empty string if none are selected.
  35860. */
  35861. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  35862. /** Returns the index of the currently selected tab.
  35863. This could return -1 if none are selected.
  35864. */
  35865. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  35866. /** Returns the button for a specific tab.
  35867. The button that is returned may be deleted later by this component, so don't hang
  35868. on to the pointer that is returned. A null pointer may be returned if the index is
  35869. out of range.
  35870. */
  35871. TabBarButton* getTabButton (const int index) const;
  35872. /** Callback method to indicate the selected tab has been changed.
  35873. @see setCurrentTabIndex
  35874. */
  35875. virtual void currentTabChanged (const int newCurrentTabIndex,
  35876. const String& newCurrentTabName);
  35877. /** Callback method to indicate that the user has right-clicked on a tab.
  35878. (Or ctrl-clicked on the Mac)
  35879. */
  35880. virtual void popupMenuClickOnTab (const int tabIndex,
  35881. const String& tabName);
  35882. /** Returns the colour of a tab.
  35883. This is the colour that was specified in addTab().
  35884. */
  35885. const Colour getTabBackgroundColour (const int tabIndex);
  35886. /** Changes the background colour of a tab.
  35887. @see addTab, getTabBackgroundColour
  35888. */
  35889. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35890. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35891. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35892. methods.
  35893. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35894. */
  35895. enum ColourIds
  35896. {
  35897. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  35898. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  35899. the look and feel will choose an appropriate colour. */
  35900. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  35901. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  35902. this isn't specified, the look and feel will choose an appropriate
  35903. colour. */
  35904. };
  35905. /** @internal */
  35906. void resized();
  35907. /** @internal */
  35908. void buttonClicked (Button* button);
  35909. /** @internal */
  35910. void lookAndFeelChanged();
  35911. juce_UseDebuggingNewOperator
  35912. protected:
  35913. /** This creates one of the tabs.
  35914. If you need to use custom tab components, you can override this method and
  35915. return your own class instead of the default.
  35916. */
  35917. virtual TabBarButton* createTabButton (const String& tabName,
  35918. const int tabIndex);
  35919. private:
  35920. Orientation orientation;
  35921. StringArray tabs;
  35922. Array <Colour> tabColours;
  35923. int currentTabIndex;
  35924. Component* behindFrontTab;
  35925. Button* extraTabsButton;
  35926. TabbedButtonBar (const TabbedButtonBar&);
  35927. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  35928. };
  35929. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35930. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  35931. /**
  35932. A component with a TabbedButtonBar along one of its sides.
  35933. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  35934. with addTab(), and this will take care of showing the pages for you when the
  35935. user clicks on a different tab.
  35936. @see TabbedButtonBar
  35937. */
  35938. class JUCE_API TabbedComponent : public Component
  35939. {
  35940. public:
  35941. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  35942. Once created, add some tabs with the addTab() method.
  35943. */
  35944. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  35945. /** Destructor. */
  35946. ~TabbedComponent();
  35947. /** Changes the placement of the tabs.
  35948. This will rearrange the layout to place the tabs along the appropriate
  35949. side of this component, and will shift the content component accordingly.
  35950. @see TabbedButtonBar::setOrientation
  35951. */
  35952. void setOrientation (const TabbedButtonBar::Orientation orientation);
  35953. /** Returns the current tab placement.
  35954. @see setOrientation, TabbedButtonBar::getOrientation
  35955. */
  35956. TabbedButtonBar::Orientation getOrientation() const throw();
  35957. /** Specifies how many pixels wide or high the tab-bar should be.
  35958. If the tabs are placed along the top or bottom, this specified the height
  35959. of the bar; if they're along the left or right edges, it'll be the width
  35960. of the bar.
  35961. */
  35962. void setTabBarDepth (const int newDepth);
  35963. /** Returns the current thickness of the tab bar.
  35964. @see setTabBarDepth
  35965. */
  35966. int getTabBarDepth() const throw() { return tabDepth; }
  35967. /** Specifies the thickness of an outline that should be drawn around the content component.
  35968. If this thickness is > 0, a line will be drawn around the three sides of the content
  35969. component which don't touch the tab-bar, and the content component will be inset by this amount.
  35970. To set the colour of the line, use setColour (outlineColourId, ...).
  35971. */
  35972. void setOutline (const int newThickness);
  35973. /** Specifies a gap to leave around the edge of the content component.
  35974. Each edge of the content component will be indented by the given number of pixels.
  35975. */
  35976. void setIndent (const int indentThickness);
  35977. /** Removes all the tabs from the bar.
  35978. @see TabbedButtonBar::clearTabs
  35979. */
  35980. void clearTabs();
  35981. /** Adds a tab to the tab-bar.
  35982. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  35983. is true, it will be deleted when the tab is removed or when this object is
  35984. deleted.
  35985. @see TabbedButtonBar::addTab
  35986. */
  35987. void addTab (const String& tabName,
  35988. const Colour& tabBackgroundColour,
  35989. Component* const contentComponent,
  35990. const bool deleteComponentWhenNotNeeded,
  35991. const int insertIndex = -1);
  35992. /** Changes the name of one of the tabs. */
  35993. void setTabName (const int tabIndex,
  35994. const String& newName);
  35995. /** Gets rid of one of the tabs. */
  35996. void removeTab (const int tabIndex);
  35997. /** Returns the number of tabs in the bar. */
  35998. int getNumTabs() const;
  35999. /** Returns a list of all the tab names in the bar. */
  36000. const StringArray getTabNames() const;
  36001. /** Returns the content component that was added for the given index.
  36002. Be sure not to use or delete the components that are returned, as this may interfere
  36003. with the TabbedComponent's use of them.
  36004. */
  36005. Component* getTabContentComponent (const int tabIndex) const throw();
  36006. /** Returns the colour of one of the tabs. */
  36007. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  36008. /** Changes the background colour of one of the tabs. */
  36009. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36010. /** Changes the currently-selected tab.
  36011. To deselect all the tabs, pass -1 as the index.
  36012. @see TabbedButtonBar::setCurrentTabIndex
  36013. */
  36014. void setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage = true);
  36015. /** Returns the index of the currently selected tab.
  36016. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  36017. */
  36018. int getCurrentTabIndex() const;
  36019. /** Returns the name of the currently selected tab.
  36020. @see addTab, TabbedButtonBar::getCurrentTabName()
  36021. */
  36022. const String& getCurrentTabName() const;
  36023. /** Returns the current component that's filling the panel.
  36024. This will return 0 if there isn't one.
  36025. */
  36026. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  36027. /** Callback method to indicate the selected tab has been changed.
  36028. @see setCurrentTabIndex
  36029. */
  36030. virtual void currentTabChanged (const int newCurrentTabIndex,
  36031. const String& newCurrentTabName);
  36032. /** Callback method to indicate that the user has right-clicked on a tab.
  36033. (Or ctrl-clicked on the Mac)
  36034. */
  36035. virtual void popupMenuClickOnTab (const int tabIndex,
  36036. const String& tabName);
  36037. /** Returns the tab button bar component that is being used.
  36038. */
  36039. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  36040. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36041. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36042. methods.
  36043. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36044. */
  36045. enum ColourIds
  36046. {
  36047. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  36048. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  36049. (See setOutline) */
  36050. };
  36051. /** @internal */
  36052. void paint (Graphics& g);
  36053. /** @internal */
  36054. void resized();
  36055. /** @internal */
  36056. void lookAndFeelChanged();
  36057. juce_UseDebuggingNewOperator
  36058. protected:
  36059. TabbedButtonBar* tabs;
  36060. /** This creates one of the tab buttons.
  36061. If you need to use custom tab components, you can override this method and
  36062. return your own class instead of the default.
  36063. */
  36064. virtual TabBarButton* createTabButton (const String& tabName,
  36065. const int tabIndex);
  36066. private:
  36067. Array <Component*> contentComponents;
  36068. Component* panelComponent;
  36069. int tabDepth;
  36070. int outlineThickness, edgeIndent;
  36071. friend class TabCompButtonBar;
  36072. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  36073. TabbedComponent (const TabbedComponent&);
  36074. const TabbedComponent& operator= (const TabbedComponent&);
  36075. };
  36076. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36077. /********* End of inlined file: juce_TabbedComponent.h *********/
  36078. /********* Start of inlined file: juce_DocumentWindow.h *********/
  36079. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36080. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36081. /********* Start of inlined file: juce_ResizableWindow.h *********/
  36082. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36083. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36084. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  36085. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36086. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36087. /********* Start of inlined file: juce_DropShadower.h *********/
  36088. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36089. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36090. /**
  36091. Adds a drop-shadow to a component.
  36092. This object creates and manages a set of components which sit around a
  36093. component, creating a gaussian shadow around it. The components will track
  36094. the position of the component and if it's brought to the front they'll also
  36095. follow this.
  36096. For desktop windows you don't need to use this class directly - just
  36097. set the Component::windowHasDropShadow flag when calling
  36098. Component::addToDesktop(), and the system will create one of these if it's
  36099. needed (which it obviously isn't on the Mac, for example).
  36100. */
  36101. class JUCE_API DropShadower : public ComponentListener
  36102. {
  36103. public:
  36104. /** Creates a DropShadower.
  36105. @param alpha the opacity of the shadows, from 0 to 1.0
  36106. @param xOffset the horizontal displacement of the shadow, in pixels
  36107. @param yOffset the vertical displacement of the shadow, in pixels
  36108. @param blurRadius the radius of the blur to use for creating the shadow
  36109. */
  36110. DropShadower (const float alpha = 0.5f,
  36111. const int xOffset = 1,
  36112. const int yOffset = 5,
  36113. const float blurRadius = 10.0f);
  36114. /** Destructor. */
  36115. virtual ~DropShadower();
  36116. /** Attaches the DropShadower to the component you want to shadow. */
  36117. void setOwner (Component* componentToFollow);
  36118. /** @internal */
  36119. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36120. /** @internal */
  36121. void componentBroughtToFront (Component& component);
  36122. /** @internal */
  36123. void componentChildrenChanged (Component& component);
  36124. /** @internal */
  36125. void componentParentHierarchyChanged (Component& component);
  36126. /** @internal */
  36127. void componentVisibilityChanged (Component& component);
  36128. juce_UseDebuggingNewOperator
  36129. private:
  36130. Component* owner;
  36131. int numShadows;
  36132. Component* shadowWindows[4];
  36133. Image* shadowImageSections[12];
  36134. const int shadowEdge, xOffset, yOffset;
  36135. const float alpha, blurRadius;
  36136. bool inDestructor, reentrant;
  36137. void updateShadows();
  36138. void setShadowImage (Image* const src,
  36139. const int num,
  36140. const int w, const int h,
  36141. const int sx, const int sy) throw();
  36142. void bringShadowWindowsToFront();
  36143. void deleteShadowWindows();
  36144. DropShadower (const DropShadower&);
  36145. const DropShadower& operator= (const DropShadower&);
  36146. };
  36147. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  36148. /********* End of inlined file: juce_DropShadower.h *********/
  36149. /**
  36150. A base class for top-level windows.
  36151. This class is used for components that are considered a major part of your
  36152. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  36153. etc. Things like menus that pop up briefly aren't derived from it.
  36154. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  36155. could itself be the child of another component.
  36156. The class manages a list of all instances of top-level windows that are in use,
  36157. and each one is also given the concept of being "active". The active window is
  36158. one that is actively being used by the user. This isn't quite the same as the
  36159. component with the keyboard focus, because there may be a popup menu or other
  36160. temporary window which gets keyboard focus while the active top level window is
  36161. unchanged.
  36162. A top-level window also has an optional drop-shadow.
  36163. @see ResizableWindow, DocumentWindow, DialogWindow
  36164. */
  36165. class JUCE_API TopLevelWindow : public Component
  36166. {
  36167. public:
  36168. /** Creates a TopLevelWindow.
  36169. @param name the name to give the component
  36170. @param addToDesktop if true, the window will be automatically added to the
  36171. desktop; if false, you can use it as a child component
  36172. */
  36173. TopLevelWindow (const String& name,
  36174. const bool addToDesktop);
  36175. /** Destructor. */
  36176. ~TopLevelWindow();
  36177. /** True if this is currently the TopLevelWindow that is actively being used.
  36178. This isn't quite the same as having keyboard focus, because the focus may be
  36179. on a child component or a temporary pop-up menu, etc, while this window is
  36180. still considered to be active.
  36181. @see activeWindowStatusChanged
  36182. */
  36183. bool isActiveWindow() const throw() { return windowIsActive_; }
  36184. /** This will set the bounds of the window so that it's centred in front of another
  36185. window.
  36186. If your app has a few windows open and want to pop up a dialog box for one of
  36187. them, you can use this to show it in front of the relevent parent window, which
  36188. is a bit neater than just having it appear in the middle of the screen.
  36189. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  36190. be used instead. If no window is focused, it'll just default to the middle of the
  36191. screen.
  36192. */
  36193. void centreAroundComponent (Component* componentToCentreAround,
  36194. const int width, const int height);
  36195. /** Turns the drop-shadow on and off. */
  36196. void setDropShadowEnabled (const bool useShadow);
  36197. /** Sets whether an OS-native title bar will be used, or a Juce one.
  36198. @see isUsingNativeTitleBar
  36199. */
  36200. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  36201. /** Returns true if the window is currently using an OS-native title bar.
  36202. @see setUsingNativeTitleBar
  36203. */
  36204. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  36205. /** Returns the number of TopLevelWindow objects currently in use.
  36206. @see getTopLevelWindow
  36207. */
  36208. static int getNumTopLevelWindows() throw();
  36209. /** Returns one of the TopLevelWindow objects currently in use.
  36210. The index is 0 to (getNumTopLevelWindows() - 1).
  36211. */
  36212. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  36213. /** Returns the currently-active top level window.
  36214. There might not be one, of course, so this can return 0.
  36215. */
  36216. static TopLevelWindow* getActiveTopLevelWindow() throw();
  36217. juce_UseDebuggingNewOperator
  36218. /** @internal */
  36219. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  36220. protected:
  36221. /** This callback happens when this window becomes active or inactive.
  36222. @see isActiveWindow
  36223. */
  36224. virtual void activeWindowStatusChanged();
  36225. /** @internal */
  36226. void focusOfChildComponentChanged (FocusChangeType cause);
  36227. /** @internal */
  36228. void parentHierarchyChanged();
  36229. /** @internal */
  36230. void visibilityChanged();
  36231. /** @internal */
  36232. virtual int getDesktopWindowStyleFlags() const;
  36233. /** @internal */
  36234. void recreateDesktopWindow();
  36235. private:
  36236. friend class TopLevelWindowManager;
  36237. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  36238. DropShadower* shadower;
  36239. void setWindowActive (const bool isNowActive) throw();
  36240. TopLevelWindow (const TopLevelWindow&);
  36241. const TopLevelWindow& operator= (const TopLevelWindow&);
  36242. };
  36243. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36244. /********* End of inlined file: juce_TopLevelWindow.h *********/
  36245. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  36246. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36247. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36248. /**
  36249. A component that resizes its parent window when dragged.
  36250. This component forms a frame around the edge of a component, allowing it to
  36251. be dragged by the edges or corners to resize it - like the way windows are
  36252. resized in MSWindows or Linux.
  36253. To use it, just add it to your component, making it fill the entire parent component
  36254. (there's a mouse hit-test that only traps mouse-events which land around the
  36255. edge of the component, so it's even ok to put it on top of any other components
  36256. you're using). Make sure you rescale the resizer component to fill the parent
  36257. each time the parent's size changes.
  36258. @see ResizableCornerComponent
  36259. */
  36260. class JUCE_API ResizableBorderComponent : public Component
  36261. {
  36262. public:
  36263. /** Creates a resizer.
  36264. Pass in the target component which you want to be resized when this one is
  36265. dragged.
  36266. The target component will usually be a parent of the resizer component, but this
  36267. isn't mandatory.
  36268. Remember that when the target component is resized, it'll need to move and
  36269. resize this component to keep it in place, as this won't happen automatically.
  36270. If the constrainer parameter is non-zero, then this object will be used to enforce
  36271. limits on the size and position that the component can be stretched to. Make sure
  36272. that the constrainer isn't deleted while still in use by this object.
  36273. @see ComponentBoundsConstrainer
  36274. */
  36275. ResizableBorderComponent (Component* const componentToResize,
  36276. ComponentBoundsConstrainer* const constrainer);
  36277. /** Destructor. */
  36278. ~ResizableBorderComponent();
  36279. /** Specifies how many pixels wide the draggable edges of this component are.
  36280. @see getBorderThickness
  36281. */
  36282. void setBorderThickness (const BorderSize& newBorderSize) throw();
  36283. /** Returns the number of pixels wide that the draggable edges of this component are.
  36284. @see setBorderThickness
  36285. */
  36286. const BorderSize getBorderThickness() const throw();
  36287. juce_UseDebuggingNewOperator
  36288. protected:
  36289. /** @internal */
  36290. void paint (Graphics& g);
  36291. /** @internal */
  36292. void mouseEnter (const MouseEvent& e);
  36293. /** @internal */
  36294. void mouseMove (const MouseEvent& e);
  36295. /** @internal */
  36296. void mouseDown (const MouseEvent& e);
  36297. /** @internal */
  36298. void mouseDrag (const MouseEvent& e);
  36299. /** @internal */
  36300. void mouseUp (const MouseEvent& e);
  36301. /** @internal */
  36302. bool hitTest (int x, int y);
  36303. private:
  36304. Component* const component;
  36305. ComponentBoundsConstrainer* constrainer;
  36306. BorderSize borderSize;
  36307. int originalX, originalY, originalW, originalH;
  36308. int mouseZone;
  36309. void updateMouseZone (const MouseEvent& e) throw();
  36310. ResizableBorderComponent (const ResizableBorderComponent&);
  36311. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  36312. };
  36313. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36314. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  36315. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  36316. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36317. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36318. /** A component that resizes a parent window when dragged.
  36319. This is the small triangular stripey resizer component you get in the bottom-right
  36320. of windows (more commonly on the Mac than Windows). Put one in the corner of
  36321. a larger component and it will automatically resize its parent when it gets dragged
  36322. around.
  36323. @see ResizableFrameComponent
  36324. */
  36325. class JUCE_API ResizableCornerComponent : public Component
  36326. {
  36327. public:
  36328. /** Creates a resizer.
  36329. Pass in the target component which you want to be resized when this one is
  36330. dragged.
  36331. The target component will usually be a parent of the resizer component, but this
  36332. isn't mandatory.
  36333. Remember that when the target component is resized, it'll need to move and
  36334. resize this component to keep it in place, as this won't happen automatically.
  36335. If the constrainer parameter is non-zero, then this object will be used to enforce
  36336. limits on the size and position that the component can be stretched to. Make sure
  36337. that the constrainer isn't deleted while still in use by this object. If you
  36338. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  36339. @see ComponentBoundsConstrainer
  36340. */
  36341. ResizableCornerComponent (Component* const componentToResize,
  36342. ComponentBoundsConstrainer* const constrainer);
  36343. /** Destructor. */
  36344. ~ResizableCornerComponent();
  36345. juce_UseDebuggingNewOperator
  36346. protected:
  36347. /** @internal */
  36348. void paint (Graphics& g);
  36349. /** @internal */
  36350. void mouseDown (const MouseEvent& e);
  36351. /** @internal */
  36352. void mouseDrag (const MouseEvent& e);
  36353. /** @internal */
  36354. void mouseUp (const MouseEvent& e);
  36355. /** @internal */
  36356. bool hitTest (int x, int y);
  36357. private:
  36358. Component* const component;
  36359. ComponentBoundsConstrainer* constrainer;
  36360. int originalX, originalY, originalW, originalH;
  36361. ResizableCornerComponent (const ResizableCornerComponent&);
  36362. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  36363. };
  36364. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36365. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  36366. /**
  36367. A base class for top-level windows that can be dragged around and resized.
  36368. To add content to the window, use its setContentComponent() method to
  36369. give it a component that will remain positioned inside it (leaving a gap around
  36370. the edges for a border).
  36371. It's not advisable to add child components directly to a ResizableWindow: put them
  36372. inside your content component instead. And overriding methods like resized(), moved(), etc
  36373. is also not recommended - instead override these methods for your content component.
  36374. (If for some obscure reason you do need to override these methods, always remember to
  36375. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36376. decorations correctly).
  36377. By default resizing isn't enabled - use the setResizable() method to enable it and
  36378. to choose the style of resizing to use.
  36379. @see TopLevelWindow
  36380. */
  36381. class JUCE_API ResizableWindow : public TopLevelWindow
  36382. {
  36383. public:
  36384. /** Creates a ResizableWindow.
  36385. This constructor doesn't specify a background colour, so the LookAndFeel's default
  36386. background colour will be used.
  36387. @param name the name to give the component
  36388. @param addToDesktop if true, the window will be automatically added to the
  36389. desktop; if false, you can use it as a child component
  36390. */
  36391. ResizableWindow (const String& name,
  36392. const bool addToDesktop);
  36393. /** Creates a ResizableWindow.
  36394. @param name the name to give the component
  36395. @param backgroundColour the colour to use for filling the window's background.
  36396. @param addToDesktop if true, the window will be automatically added to the
  36397. desktop; if false, you can use it as a child component
  36398. */
  36399. ResizableWindow (const String& name,
  36400. const Colour& backgroundColour,
  36401. const bool addToDesktop);
  36402. /** Destructor.
  36403. If a content component has been set with setContentComponent(), it
  36404. will be deleted.
  36405. */
  36406. ~ResizableWindow();
  36407. /** Returns the colour currently being used for the window's background.
  36408. As a convenience the window will fill itself with this colour, but you
  36409. can override the paint() method if you need more customised behaviour.
  36410. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  36411. @see setBackgroundColour
  36412. */
  36413. const Colour getBackgroundColour() const throw();
  36414. /** Changes the colour currently being used for the window's background.
  36415. As a convenience the window will fill itself with this colour, but you
  36416. can override the paint() method if you need more customised behaviour.
  36417. Note that the opaque state of this window is altered by this call to reflect
  36418. the opacity of the colour passed-in. On window systems which can't support
  36419. semi-transparent windows this might cause problems, (though it's unlikely you'll
  36420. be using this class as a base for a semi-transparent component anyway).
  36421. You can also use the ResizableWindow::backgroundColourId colour id to set
  36422. this colour.
  36423. @see getBackgroundColour
  36424. */
  36425. void setBackgroundColour (const Colour& newColour);
  36426. /** Make the window resizable or fixed.
  36427. @param shouldBeResizable whether it's resizable at all
  36428. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  36429. bottom-right; if false, it'll use a ResizableBorderComponent
  36430. around the edge
  36431. @see setResizeLimits, isResizable
  36432. */
  36433. void setResizable (const bool shouldBeResizable,
  36434. const bool useBottomRightCornerResizer);
  36435. /** True if resizing is enabled.
  36436. @see setResizable
  36437. */
  36438. bool isResizable() const throw();
  36439. /** This sets the maximum and minimum sizes for the window.
  36440. If the window's current size is outside these limits, it will be resized to
  36441. make sure it's within them.
  36442. Calling setBounds() on the component will bypass any size checking - it's only when
  36443. the window is being resized by the user that these values are enforced.
  36444. @see setResizable, setFixedAspectRatio
  36445. */
  36446. void setResizeLimits (const int newMinimumWidth,
  36447. const int newMinimumHeight,
  36448. const int newMaximumWidth,
  36449. const int newMaximumHeight) throw();
  36450. /** Returns the bounds constrainer object that this window is using.
  36451. You can access this to change its properties.
  36452. */
  36453. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  36454. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  36455. A pointer to the object you pass in will be kept, but it won't be deleted
  36456. by this object, so it's the caller's responsiblity to manage it.
  36457. If you pass 0, then no contraints will be placed on the positioning of the window.
  36458. */
  36459. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  36460. /** Calls the window's setBounds method, after first checking these bounds
  36461. with the current constrainer.
  36462. @see setConstrainer
  36463. */
  36464. void setBoundsConstrained (int x, int y, int width, int height);
  36465. /** Returns true if the window is currently in full-screen mode.
  36466. @see setFullScreen
  36467. */
  36468. bool isFullScreen() const;
  36469. /** Puts the window into full-screen mode, or restores it to its normal size.
  36470. If true, the window will become full-screen; if false, it will return to the
  36471. last size it was before being made full-screen.
  36472. @see isFullScreen
  36473. */
  36474. void setFullScreen (const bool shouldBeFullScreen);
  36475. /** Returns true if the window is currently minimised.
  36476. @see setMinimised
  36477. */
  36478. bool isMinimised() const;
  36479. /** Minimises the window, or restores it to its previous position and size.
  36480. When being un-minimised, it'll return to the last position and size it
  36481. was in before being minimised.
  36482. @see isMinimised
  36483. */
  36484. void setMinimised (const bool shouldMinimise);
  36485. /** Returns a string which encodes the window's current size and position.
  36486. This string will encapsulate the window's size, position, and whether it's
  36487. in full-screen mode. It's intended for letting your application save and
  36488. restore a window's position.
  36489. Use the restoreWindowStateFromString() to restore from a saved state.
  36490. @see restoreWindowStateFromString
  36491. */
  36492. const String getWindowStateAsString();
  36493. /** Restores the window to a previously-saved size and position.
  36494. This restores the window's size, positon and full-screen status from an
  36495. string that was previously created with the getWindowStateAsString()
  36496. method.
  36497. @returns false if the string wasn't a valid window state
  36498. @see getWindowStateAsString
  36499. */
  36500. bool restoreWindowStateFromString (const String& previousState);
  36501. /** Returns the current content component.
  36502. This will be the component set by setContentComponent(), or 0 if none
  36503. has yet been specified.
  36504. @see setContentComponent
  36505. */
  36506. Component* getContentComponent() const throw() { return contentComponent; }
  36507. /** Changes the current content component.
  36508. This sets a component that will be placed in the centre of the ResizableWindow,
  36509. (leaving a space around the edge for the border).
  36510. You should never add components directly to a ResizableWindow (or any of its subclasses)
  36511. with addChildComponent(). Instead, add them to the content component.
  36512. @param newContentComponent the new component to use (or null to not use one) - this
  36513. component will be deleted either when replaced by another call
  36514. to this method, or when the ResizableWindow is deleted.
  36515. To remove a content component without deleting it, use
  36516. setContentComponent (0, false).
  36517. @param deleteOldOne if true, the previous content component will be deleted; if
  36518. false, the previous component will just be removed without
  36519. deleting it.
  36520. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  36521. it always fits around the size of the content component. If false, the
  36522. new content will be resized to fit the current space available.
  36523. */
  36524. void setContentComponent (Component* const newContentComponent,
  36525. const bool deleteOldOne = true,
  36526. const bool resizeToFit = false);
  36527. /** Changes the window so that the content component ends up with the specified size.
  36528. This is basically a setSize call on the window, but which adds on the borders,
  36529. so you can specify the content component's target size.
  36530. */
  36531. void setContentComponentSize (int width, int height);
  36532. /** A set of colour IDs to use to change the colour of various aspects of the window.
  36533. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36534. methods.
  36535. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36536. */
  36537. enum ColourIds
  36538. {
  36539. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  36540. };
  36541. juce_UseDebuggingNewOperator
  36542. protected:
  36543. /** @internal */
  36544. void paint (Graphics& g);
  36545. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  36546. void moved();
  36547. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  36548. void resized();
  36549. /** @internal */
  36550. void mouseDown (const MouseEvent& e);
  36551. /** @internal */
  36552. void mouseDrag (const MouseEvent& e);
  36553. /** @internal */
  36554. void lookAndFeelChanged();
  36555. /** @internal */
  36556. void childBoundsChanged (Component* child);
  36557. /** @internal */
  36558. void parentSizeChanged();
  36559. /** @internal */
  36560. void visibilityChanged();
  36561. /** @internal */
  36562. void activeWindowStatusChanged();
  36563. /** @internal */
  36564. int getDesktopWindowStyleFlags() const;
  36565. /** Returns the width of the border to use around the window.
  36566. @see getContentComponentBorder
  36567. */
  36568. virtual const BorderSize getBorderThickness();
  36569. /** Returns the insets to use when positioning the content component.
  36570. @see getBorderThickness
  36571. */
  36572. virtual const BorderSize getContentComponentBorder();
  36573. #ifdef JUCE_DEBUG
  36574. /** Overridden to warn people about adding components directly to this component
  36575. instead of using setContentComponent().
  36576. If you know what you're doing and are sure you really want to add a component, specify
  36577. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  36578. */
  36579. void addChildComponent (Component* const child, int zOrder = -1);
  36580. /** Overridden to warn people about adding components directly to this component
  36581. instead of using setContentComponent().
  36582. If you know what you're doing and are sure you really want to add a component, specify
  36583. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  36584. */
  36585. void addAndMakeVisible (Component* const child, int zOrder = -1);
  36586. #endif
  36587. ResizableCornerComponent* resizableCorner;
  36588. ResizableBorderComponent* resizableBorder;
  36589. private:
  36590. Component* contentComponent;
  36591. bool resizeToFitContent, fullscreen;
  36592. ComponentDragger dragger;
  36593. Rectangle lastNonFullScreenPos;
  36594. ComponentBoundsConstrainer defaultConstrainer;
  36595. ComponentBoundsConstrainer* constrainer;
  36596. #ifdef JUCE_DEBUG
  36597. bool hasBeenResized;
  36598. #endif
  36599. void updateLastPos();
  36600. ResizableWindow (const ResizableWindow&);
  36601. const ResizableWindow& operator= (const ResizableWindow&);
  36602. // (xxx remove these eventually)
  36603. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  36604. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  36605. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  36606. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  36607. };
  36608. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36609. /********* End of inlined file: juce_ResizableWindow.h *********/
  36610. /**
  36611. A resizable window with a title bar and maximise, minimise and close buttons.
  36612. This subclass of ResizableWindow creates a fairly standard type of window with
  36613. a title bar and various buttons. The name of the component is shown in the
  36614. title bar, and an icon can optionally be specified with setIcon().
  36615. All the methods available to a ResizableWindow are also available to this,
  36616. so it can easily be made resizable, minimised, maximised, etc.
  36617. It's not advisable to add child components directly to a DocumentWindow: put them
  36618. inside your content component instead. And overriding methods like resized(), moved(), etc
  36619. is also not recommended - instead override these methods for your content component.
  36620. (If for some obscure reason you do need to override these methods, always remember to
  36621. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36622. decorations correctly).
  36623. You can also automatically add a menu bar to the window, using the setMenuBar()
  36624. method.
  36625. @see ResizableWindow, DialogWindow
  36626. */
  36627. class JUCE_API DocumentWindow : public ResizableWindow
  36628. {
  36629. public:
  36630. /** The set of available button-types that can be put on the title bar.
  36631. @see setTitleBarButtonsRequired
  36632. */
  36633. enum TitleBarButtons
  36634. {
  36635. minimiseButton = 1,
  36636. maximiseButton = 2,
  36637. closeButton = 4,
  36638. /** A combination of all the buttons above. */
  36639. allButtons = 7
  36640. };
  36641. /** Creates a DocumentWindow.
  36642. @param name the name to give the component - this is also
  36643. the title shown at the top of the window. To change
  36644. this later, use setName()
  36645. @param backgroundColour the colour to use for filling the window's background.
  36646. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36647. should be shown on the title bar. This value is a bitwise
  36648. combination of values from the TitleBarButtons enum. Note
  36649. that it can be "allButtons" to get them all. You
  36650. can change this later with the setTitleBarButtonsRequired()
  36651. method, which can also specify where they are positioned.
  36652. @param addToDesktop if true, the window will be automatically added to the
  36653. desktop; if false, you can use it as a child component
  36654. @see TitleBarButtons
  36655. */
  36656. DocumentWindow (const String& name,
  36657. const Colour& backgroundColour,
  36658. const int requiredButtons,
  36659. const bool addToDesktop = true);
  36660. /** Destructor.
  36661. If a content component has been set with setContentComponent(), it
  36662. will be deleted.
  36663. */
  36664. ~DocumentWindow();
  36665. /** Changes the component's name.
  36666. (This is overridden from Component::setName() to cause a repaint, as
  36667. the name is what gets drawn across the window's title bar).
  36668. */
  36669. void setName (const String& newName);
  36670. /** Sets an icon to show in the title bar, next to the title.
  36671. A copy is made internally of the image, so the caller can delete the
  36672. image after calling this. If 0 is passed-in, any existing icon will be
  36673. removed.
  36674. */
  36675. void setIcon (const Image* imageToUse);
  36676. /** Changes the height of the title-bar. */
  36677. void setTitleBarHeight (const int newHeight);
  36678. /** Returns the current title bar height. */
  36679. int getTitleBarHeight() const;
  36680. /** Changes the set of title-bar buttons being shown.
  36681. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36682. should be shown on the title bar. This value is a bitwise
  36683. combination of values from the TitleBarButtons enum. Note
  36684. that it can be "allButtons" to get them all.
  36685. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  36686. left side of the bar; if false, they'll be placed at the right
  36687. */
  36688. void setTitleBarButtonsRequired (const int requiredButtons,
  36689. const bool positionTitleBarButtonsOnLeft);
  36690. /** Sets whether the title should be centred within the window.
  36691. If true, the title text is shown in the middle of the title-bar; if false,
  36692. it'll be shown at the left of the bar.
  36693. */
  36694. void setTitleBarTextCentred (const bool textShouldBeCentred);
  36695. /** Creates a menu inside this window.
  36696. @param menuBarModel this specifies a MenuBarModel that should be used to
  36697. generate the contents of a menu bar that will be placed
  36698. just below the title bar, and just above any content
  36699. component. If this value is zero, any existing menu bar
  36700. will be removed from the component; if non-zero, one will
  36701. be added if it's required.
  36702. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  36703. or less to use the look-and-feel's default size.
  36704. */
  36705. void setMenuBar (MenuBarModel* menuBarModel,
  36706. const int menuBarHeight = 0);
  36707. /** This method is called when the user tries to close the window.
  36708. This is triggered by the user clicking the close button, or using some other
  36709. OS-specific key shortcut or OS menu for getting rid of a window.
  36710. If the window is just a pop-up, you should override this closeButtonPressed()
  36711. method and make it delete the window in whatever way is appropriate for your
  36712. app. E.g. you might just want to call "delete this".
  36713. If your app is centred around this window such that the whole app should quit when
  36714. the window is closed, then you will probably want to use this method as an opportunity
  36715. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  36716. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  36717. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  36718. or closing it via the taskbar icon on Windows).
  36719. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  36720. redirects it to call this method, so any methods of closing the window that are
  36721. caught by userTriedToCloseWindow() will also end up here).
  36722. */
  36723. virtual void closeButtonPressed();
  36724. /** Callback that is triggered when the minimise button is pressed.
  36725. The default implementation of this calls ResizableWindow::setMinimised(), but
  36726. you can override it to do more customised behaviour.
  36727. */
  36728. virtual void minimiseButtonPressed();
  36729. /** Callback that is triggered when the maximise button is pressed, or when the
  36730. title-bar is double-clicked.
  36731. The default implementation of this calls ResizableWindow::setFullScreen(), but
  36732. you can override it to do more customised behaviour.
  36733. */
  36734. virtual void maximiseButtonPressed();
  36735. /** Returns the close button, (or 0 if there isn't one). */
  36736. Button* getCloseButton() const throw();
  36737. /** Returns the minimise button, (or 0 if there isn't one). */
  36738. Button* getMinimiseButton() const throw();
  36739. /** Returns the maximise button, (or 0 if there isn't one). */
  36740. Button* getMaximiseButton() const throw();
  36741. /** A set of colour IDs to use to change the colour of various aspects of the window.
  36742. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36743. methods.
  36744. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36745. */
  36746. enum ColourIds
  36747. {
  36748. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  36749. and feel class how this is used. */
  36750. };
  36751. /** @internal */
  36752. void paint (Graphics& g);
  36753. /** @internal */
  36754. void resized();
  36755. /** @internal */
  36756. void lookAndFeelChanged();
  36757. /** @internal */
  36758. const BorderSize getBorderThickness();
  36759. /** @internal */
  36760. const BorderSize getContentComponentBorder();
  36761. /** @internal */
  36762. void mouseDoubleClick (const MouseEvent& e);
  36763. /** @internal */
  36764. void userTriedToCloseWindow();
  36765. /** @internal */
  36766. void activeWindowStatusChanged();
  36767. /** @internal */
  36768. int getDesktopWindowStyleFlags() const;
  36769. /** @internal */
  36770. void parentHierarchyChanged();
  36771. juce_UseDebuggingNewOperator
  36772. private:
  36773. int titleBarHeight, menuBarHeight, requiredButtons;
  36774. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  36775. Button* titleBarButtons [3];
  36776. Image* titleBarIcon;
  36777. MenuBarComponent* menuBar;
  36778. MenuBarModel* menuBarModel;
  36779. class ButtonListenerProxy : public ButtonListener
  36780. {
  36781. public:
  36782. ButtonListenerProxy();
  36783. void buttonClicked (Button* button);
  36784. DocumentWindow* owner;
  36785. } buttonListener;
  36786. int getBorderSize() const;
  36787. void repaintTitleBar();
  36788. DocumentWindow (const DocumentWindow&);
  36789. const DocumentWindow& operator= (const DocumentWindow&);
  36790. };
  36791. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36792. /********* End of inlined file: juce_DocumentWindow.h *********/
  36793. class MultiDocumentPanel;
  36794. class MDITabbedComponentInternal;
  36795. /**
  36796. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  36797. component.
  36798. It's like a normal DocumentWindow but has some extra functionality to make sure
  36799. everything works nicely inside a MultiDocumentPanel.
  36800. @see MultiDocumentPanel
  36801. */
  36802. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  36803. {
  36804. public:
  36805. /**
  36806. */
  36807. MultiDocumentPanelWindow (const Colour& backgroundColour);
  36808. /** Destructor. */
  36809. ~MultiDocumentPanelWindow();
  36810. /** @internal */
  36811. void maximiseButtonPressed();
  36812. /** @internal */
  36813. void closeButtonPressed();
  36814. /** @internal */
  36815. void activeWindowStatusChanged();
  36816. /** @internal */
  36817. void broughtToFront();
  36818. juce_UseDebuggingNewOperator
  36819. private:
  36820. void updateOrder();
  36821. MultiDocumentPanel* getOwner() const throw();
  36822. };
  36823. /**
  36824. A component that contains a set of other components either in floating windows
  36825. or tabs.
  36826. This acts as a panel that can be used to hold a set of open document windows, with
  36827. different layout modes.
  36828. Use addDocument() and closeDocument() to add or remove components from the
  36829. panel - never use any of the Component methods to access the panel's child
  36830. components directly, as these are managed internally.
  36831. */
  36832. class JUCE_API MultiDocumentPanel : public Component,
  36833. private ComponentListener
  36834. {
  36835. public:
  36836. /** Creates an empty panel.
  36837. Use addDocument() and closeDocument() to add or remove components from the
  36838. panel - never use any of the Component methods to access the panel's child
  36839. components directly, as these are managed internally.
  36840. */
  36841. MultiDocumentPanel();
  36842. /** Destructor.
  36843. When deleted, this will call closeAllDocuments (false) to make sure all its
  36844. components are deleted. If you need to make sure all documents are saved
  36845. before closing, then you should call closeAllDocuments (true) and check that
  36846. it returns true before deleting the panel.
  36847. */
  36848. ~MultiDocumentPanel();
  36849. /** Tries to close all the documents.
  36850. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36851. be called for each open document, and any of these calls fails, this method
  36852. will stop and return false, leaving some documents still open.
  36853. If checkItsOkToCloseFirst is false, then all documents will be closed
  36854. unconditionally.
  36855. @see closeDocument
  36856. */
  36857. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  36858. /** Adds a document component to the panel.
  36859. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  36860. this will fail and return false. (If it does fail, the component passed-in will not be
  36861. deleted, even if deleteWhenRemoved was set to true).
  36862. The MultiDocumentPanel will deal with creating a window border to go around your component,
  36863. so just pass in the bare content component here, no need to give it a ResizableWindow
  36864. or DocumentWindow.
  36865. @param component the component to add
  36866. @param backgroundColour the background colour to use to fill the component's
  36867. window or tab
  36868. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  36869. or closeAllDocuments(), then it will be deleted. If false, then
  36870. the caller must handle the component's deletion
  36871. */
  36872. bool addDocument (Component* const component,
  36873. const Colour& backgroundColour,
  36874. const bool deleteWhenRemoved);
  36875. /** Closes one of the documents.
  36876. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36877. be called, and if it fails, this method will return false without closing the
  36878. document.
  36879. If checkItsOkToCloseFirst is false, then the documents will be closed
  36880. unconditionally.
  36881. The component will be deleted if the deleteWhenRemoved parameter was set to
  36882. true when it was added with addDocument.
  36883. @see addDocument, closeAllDocuments
  36884. */
  36885. bool closeDocument (Component* component,
  36886. const bool checkItsOkToCloseFirst);
  36887. /** Returns the number of open document windows.
  36888. @see getDocument
  36889. */
  36890. int getNumDocuments() const throw();
  36891. /** Returns one of the open documents.
  36892. The order of the documents in this array may change when they are added, removed
  36893. or moved around.
  36894. @see getNumDocuments
  36895. */
  36896. Component* getDocument (const int index) const throw();
  36897. /** Returns the document component that is currently focused or on top.
  36898. If currently using floating windows, then this will be the component in the currently
  36899. active window, or the top component if none are active.
  36900. If it's currently in tabbed mode, then it'll return the component in the active tab.
  36901. @see setActiveDocument
  36902. */
  36903. Component* getActiveDocument() const throw();
  36904. /** Makes one of the components active and brings it to the top.
  36905. @see getActiveDocument
  36906. */
  36907. void setActiveDocument (Component* component);
  36908. /** Callback which gets invoked when the currently-active document changes. */
  36909. virtual void activeDocumentChanged();
  36910. /** Sets a limit on how many windows can be open at once.
  36911. If this is zero or less there's no limit (the default). addDocument() will fail
  36912. if this number is exceeded.
  36913. */
  36914. void setMaximumNumDocuments (const int maximumNumDocuments);
  36915. /** Sets an option to make the document fullscreen if there's only one document open.
  36916. If set to true, then if there's only one document, it'll fill the whole of this
  36917. component without tabs or a window border. If false, then tabs or a window
  36918. will always be shown, even if there's only one document. If there's more than
  36919. one document open, then this option makes no difference.
  36920. */
  36921. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  36922. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  36923. */
  36924. bool isFullscreenWhenOneDocument() const throw();
  36925. /** The different layout modes available. */
  36926. enum LayoutMode
  36927. {
  36928. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  36929. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  36930. };
  36931. /** Changes the panel's mode.
  36932. @see LayoutMode, getLayoutMode
  36933. */
  36934. void setLayoutMode (const LayoutMode newLayoutMode);
  36935. /** Returns the current layout mode. */
  36936. LayoutMode getLayoutMode() const throw() { return mode; }
  36937. /** Sets the background colour for the whole panel.
  36938. Each document has its own background colour, but this is the one used to fill the areas
  36939. behind them.
  36940. */
  36941. void setBackgroundColour (const Colour& newBackgroundColour);
  36942. /** Returns the current background colour.
  36943. @see setBackgroundColour
  36944. */
  36945. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  36946. /** A subclass must override this to say whether its currently ok for a document
  36947. to be closed.
  36948. This method is called by closeDocument() and closeAllDocuments() to indicate that
  36949. a document should be saved if possible, ready for it to be closed.
  36950. If this method returns true, then it means the document is ok and can be closed.
  36951. If it returns false, then it means that the closeDocument() method should stop
  36952. and not close.
  36953. Normally, you'd use this method to ask the user if they want to save any changes,
  36954. then return true if the save operation went ok. If the user cancelled the save
  36955. operation you could return false here to abort the close operation.
  36956. If your component is based on the FileBasedDocument class, then you'd probably want
  36957. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  36958. FileBasedDocument::savedOk
  36959. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  36960. */
  36961. virtual bool tryToCloseDocument (Component* component) = 0;
  36962. /** Creates a new window to be used for a document.
  36963. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  36964. but you might want to override it to return a custom component.
  36965. */
  36966. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  36967. /** @internal */
  36968. void paint (Graphics& g);
  36969. /** @internal */
  36970. void resized();
  36971. /** @internal */
  36972. void componentNameChanged (Component&);
  36973. juce_UseDebuggingNewOperator
  36974. private:
  36975. LayoutMode mode;
  36976. Array <Component*> components;
  36977. TabbedComponent* tabComponent;
  36978. Colour backgroundColour;
  36979. int maximumNumDocuments, numDocsBeforeTabsUsed;
  36980. friend class MultiDocumentPanelWindow;
  36981. friend class MDITabbedComponentInternal;
  36982. Component* getContainerComp (Component* c) const;
  36983. void updateOrder();
  36984. void addWindow (Component* component);
  36985. };
  36986. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36987. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  36988. #endif
  36989. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36990. #endif
  36991. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36992. #endif
  36993. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  36994. #endif
  36995. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36996. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  36997. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36998. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36999. /**
  37000. For laying out a set of components, where the components have preferred sizes
  37001. and size limits, but where they are allowed to stretch to fill the available
  37002. space.
  37003. For example, if you have a component containing several other components, and
  37004. each one should be given a share of the total size, you could use one of these
  37005. to resize the child components when the parent component is resized. Then
  37006. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  37007. A StretchableLayoutManager operates only in one dimension, so if you have a set
  37008. of components stacked vertically on top of each other, you'd use one to manage their
  37009. heights. To build up complex arrangements of components, e.g. for applications
  37010. with multiple nested panels, you would use more than one StretchableLayoutManager.
  37011. E.g. by using two (one vertical, one horizontal), you could create a resizable
  37012. spreadsheet-style table.
  37013. E.g.
  37014. @code
  37015. class MyComp : public Component
  37016. {
  37017. StretchableLayoutManager myLayout;
  37018. MyComp()
  37019. {
  37020. myLayout.setItemLayout (0, // for item 0
  37021. 50, 100, // must be between 50 and 100 pixels in size
  37022. -0.6); // and its preferred size is 60% of the total available space
  37023. myLayout.setItemLayout (1, // for item 1
  37024. -0.2, -0.6, // size must be between 20% and 60% of the available space
  37025. 50); // and its preferred size is 50 pixels
  37026. }
  37027. void resized()
  37028. {
  37029. // make a list of two of our child components that we want to reposition
  37030. Component* comps[] = { myComp1, myComp2 };
  37031. // this will position the 2 components, one above the other, to fit
  37032. // vertically into the rectangle provided.
  37033. myLayout.layOutComponents (comps, 2,
  37034. 0, 0, getWidth(), getHeight(),
  37035. true);
  37036. }
  37037. };
  37038. @endcode
  37039. @see StretchableLayoutResizerBar
  37040. */
  37041. class JUCE_API StretchableLayoutManager
  37042. {
  37043. public:
  37044. /** Creates an empty layout.
  37045. You'll need to add some item properties to the layout before it can be used
  37046. to resize things - see setItemLayout().
  37047. */
  37048. StretchableLayoutManager();
  37049. /** Destructor. */
  37050. ~StretchableLayoutManager();
  37051. /** For a numbered item, this sets its size limits and preferred size.
  37052. @param itemIndex the index of the item to change.
  37053. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37054. indicates an absolute size in pixels. A negative number indicates a
  37055. proportion of the available space (e.g -0.5 is 50%)
  37056. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37057. indicates an absolute size in pixels. A negative number indicates a
  37058. proportion of the available space
  37059. @param preferredSize the size that this item would like to be, if there's enough room. A
  37060. positive number indicates an absolute size in pixels. A negative number
  37061. indicates a proportion of the available space
  37062. @see getItemLayout
  37063. */
  37064. void setItemLayout (const int itemIndex,
  37065. const double minimumSize,
  37066. const double maximumSize,
  37067. const double preferredSize);
  37068. /** For a numbered item, this returns its size limits and preferred size.
  37069. @param itemIndex the index of the item.
  37070. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37071. indicates an absolute size in pixels. A negative number indicates a
  37072. proportion of the available space (e.g -0.5 is 50%)
  37073. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37074. indicates an absolute size in pixels. A negative number indicates a
  37075. proportion of the available space
  37076. @param preferredSize the size that this item would like to be, if there's enough room. A
  37077. positive number indicates an absolute size in pixels. A negative number
  37078. indicates a proportion of the available space
  37079. @returns false if the item's properties hadn't been set
  37080. @see setItemLayout
  37081. */
  37082. bool getItemLayout (const int itemIndex,
  37083. double& minimumSize,
  37084. double& maximumSize,
  37085. double& preferredSize) const;
  37086. /** Clears all the properties that have been set with setItemLayout() and resets
  37087. this object to its initial state.
  37088. */
  37089. void clearAllItems();
  37090. /** Takes a set of components that correspond to the layout's items, and positions
  37091. them to fill a space.
  37092. This will try to give each item its preferred size, whether that's a relative size
  37093. or an absolute one.
  37094. @param components an array of components that correspond to each of the
  37095. numbered items that the StretchableLayoutManager object
  37096. has been told about with setItemLayout()
  37097. @param numComponents the number of components in the array that is passed-in. This
  37098. should be the same as the number of items this object has been
  37099. told about.
  37100. @param x the left of the rectangle in which the components should
  37101. be laid out
  37102. @param y the top of the rectangle in which the components should
  37103. be laid out
  37104. @param width the width of the rectangle in which the components should
  37105. be laid out
  37106. @param height the height of the rectangle in which the components should
  37107. be laid out
  37108. @param vertically if true, the components will be positioned in a vertical stack,
  37109. so that they fill the height of the rectangle. If false, they
  37110. will be placed side-by-side in a horizontal line, filling the
  37111. available width
  37112. @param resizeOtherDimension if true, this means that the components will have their
  37113. other dimension resized to fit the space - i.e. if the 'vertically'
  37114. parameter is true, their x-positions and widths are adjusted to fit
  37115. the x and width parameters; if 'vertically' is false, their y-positions
  37116. and heights are adjusted to fit the y and height parameters.
  37117. */
  37118. void layOutComponents (Component** const components,
  37119. int numComponents,
  37120. int x, int y, int width, int height,
  37121. const bool vertically,
  37122. const bool resizeOtherDimension);
  37123. /** Returns the current position of one of the items.
  37124. This is only a valid call after layOutComponents() has been called, as it
  37125. returns the last position that this item was placed at. If the layout was
  37126. vertical, the value returned will be the y position of the top of the item,
  37127. relative to the top of the rectangle in which the items were placed (so for
  37128. example, item 0 will always have position of 0, even in the rectangle passed
  37129. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  37130. the position returned is the item's left-hand position, again relative to the
  37131. x position of the rectangle used.
  37132. @see getItemCurrentSize, setItemPosition
  37133. */
  37134. int getItemCurrentPosition (const int itemIndex) const;
  37135. /** Returns the current size of one of the items.
  37136. This is only meaningful after layOutComponents() has been called, as it
  37137. returns the last size that this item was given. If the layout was done
  37138. vertically, it'll return the item's height in pixels; if it was horizontal,
  37139. it'll return its width.
  37140. @see getItemCurrentRelativeSize
  37141. */
  37142. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  37143. /** Returns the current size of one of the items.
  37144. This is only meaningful after layOutComponents() has been called, as it
  37145. returns the last size that this item was given. If the layout was done
  37146. vertically, it'll return a negative value representing the item's height relative
  37147. to the last size used for laying the components out; if the layout was done
  37148. horizontally it'll be the proportion of its width.
  37149. @see getItemCurrentAbsoluteSize
  37150. */
  37151. double getItemCurrentRelativeSize (const int itemIndex) const;
  37152. /** Moves one of the items, shifting along any other items as necessary in
  37153. order to get it to the desired position.
  37154. Calling this method will also update the preferred sizes of the items it
  37155. shuffles along, so that they reflect their new positions.
  37156. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  37157. about when it's dragged).
  37158. @param itemIndex the item to move
  37159. @param newPosition the absolute position that you'd like this item to move
  37160. to. The item might not be able to always reach exactly this position,
  37161. because other items may have minimum sizes that constrain how
  37162. far it can go
  37163. */
  37164. void setItemPosition (const int itemIndex,
  37165. int newPosition);
  37166. juce_UseDebuggingNewOperator
  37167. private:
  37168. struct ItemLayoutProperties
  37169. {
  37170. int itemIndex;
  37171. int currentSize;
  37172. double minSize, maxSize, preferredSize;
  37173. };
  37174. OwnedArray <ItemLayoutProperties> items;
  37175. int totalSize;
  37176. static int sizeToRealSize (double size, int totalSpace);
  37177. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  37178. void setTotalSize (const int newTotalSize);
  37179. int fitComponentsIntoSpace (const int startIndex,
  37180. const int endIndex,
  37181. const int availableSpace,
  37182. int startPos);
  37183. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  37184. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  37185. void updatePrefSizesToMatchCurrentPositions();
  37186. StretchableLayoutManager (const StretchableLayoutManager&);
  37187. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  37188. };
  37189. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37190. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  37191. #endif
  37192. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37193. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37194. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37195. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37196. /**
  37197. A component that acts as one of the vertical or horizontal bars you see being
  37198. used to resize panels in a window.
  37199. One of these acts with a StretchableLayoutManager to resize the other components.
  37200. @see StretchableLayoutManager
  37201. */
  37202. class JUCE_API StretchableLayoutResizerBar : public Component
  37203. {
  37204. public:
  37205. /** Creates a resizer bar for use on a specified layout.
  37206. @param layoutToUse the layout that will be affected when this bar
  37207. is dragged
  37208. @param itemIndexInLayout the item index in the layout that corresponds to
  37209. this bar component. You'll need to set up the item
  37210. properties in a suitable way for a divider bar, e.g.
  37211. for an 8-pixel wide bar which, you could call
  37212. myLayout->setItemLayout (barIndex, 8, 8, 8)
  37213. @param isBarVertical true if it's an upright bar that you drag left and
  37214. right; false for a horizontal one that you drag up and
  37215. down
  37216. */
  37217. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  37218. const int itemIndexInLayout,
  37219. const bool isBarVertical);
  37220. /** Destructor. */
  37221. ~StretchableLayoutResizerBar();
  37222. /** This is called when the bar is dragged.
  37223. This method must update the positions of any components whose position is
  37224. determined by the StretchableLayoutManager, because they might have just
  37225. moved.
  37226. The default implementation calls the resized() method of this component's
  37227. parent component, because that's often where you're likely to apply the
  37228. layout, but it can be overridden for more specific needs.
  37229. */
  37230. virtual void hasBeenMoved();
  37231. /** @internal */
  37232. void paint (Graphics& g);
  37233. /** @internal */
  37234. void mouseDown (const MouseEvent& e);
  37235. /** @internal */
  37236. void mouseDrag (const MouseEvent& e);
  37237. juce_UseDebuggingNewOperator
  37238. private:
  37239. StretchableLayoutManager* layout;
  37240. int itemIndex, mouseDownPos;
  37241. bool isVertical;
  37242. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  37243. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  37244. };
  37245. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37246. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37247. #endif
  37248. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37249. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  37250. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37251. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37252. /**
  37253. A utility class for fitting a set of objects whose sizes can vary between
  37254. a minimum and maximum size, into a space.
  37255. This is a trickier algorithm than it would first seem, so I've put it in this
  37256. class to allow it to be shared by various bits of code.
  37257. To use it, create one of these objects, call addItem() to add the list of items
  37258. you need, then call resizeToFit(), which will change all their sizes. You can
  37259. then retrieve the new sizes with getItemSize() and getNumItems().
  37260. It's currently used by the TableHeaderComponent for stretching out the table
  37261. headings to fill the table's width.
  37262. */
  37263. class StretchableObjectResizer
  37264. {
  37265. public:
  37266. /** Creates an empty object resizer. */
  37267. StretchableObjectResizer();
  37268. /** Destructor. */
  37269. ~StretchableObjectResizer();
  37270. /** Adds an item to the list.
  37271. The order parameter lets you specify groups of items that are resized first when some
  37272. space needs to be found. Those items with an order of 0 will be the first ones to be
  37273. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  37274. will then try resizing the items with an order of 1, then 2, and so on.
  37275. */
  37276. void addItem (const double currentSize,
  37277. const double minSize,
  37278. const double maxSize,
  37279. const int order = 0);
  37280. /** Resizes all the items to fit this amount of space.
  37281. This will attempt to fit them in without exceeding each item's miniumum and
  37282. maximum sizes. In cases where none of the items can be expanded or enlarged any
  37283. further, the final size may be greater or less than the size passed in.
  37284. After calling this method, you can retrieve the new sizes with the getItemSize()
  37285. method.
  37286. */
  37287. void resizeToFit (const double targetSize);
  37288. /** Returns the number of items that have been added. */
  37289. int getNumItems() const throw() { return items.size(); }
  37290. /** Returns the size of one of the items. */
  37291. double getItemSize (const int index) const throw();
  37292. juce_UseDebuggingNewOperator
  37293. private:
  37294. struct Item
  37295. {
  37296. double size;
  37297. double minSize;
  37298. double maxSize;
  37299. int order;
  37300. };
  37301. OwnedArray <Item> items;
  37302. StretchableObjectResizer (const StretchableObjectResizer&);
  37303. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  37304. };
  37305. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37306. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  37307. #endif
  37308. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  37309. #endif
  37310. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  37311. #endif
  37312. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  37313. #endif
  37314. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37315. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  37316. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37317. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37318. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  37319. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37320. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37321. /********* Start of inlined file: juce_FileFilter.h *********/
  37322. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37323. #define __JUCE_FILEFILTER_JUCEHEADER__
  37324. /**
  37325. Interface for deciding which files are suitable for something.
  37326. For example, this is used by DirectoryContentsList to select which files
  37327. go into the list.
  37328. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37329. */
  37330. class JUCE_API FileFilter
  37331. {
  37332. public:
  37333. /** Creates a filter with the given description.
  37334. The description can be returned later with the getDescription() method.
  37335. */
  37336. FileFilter (const String& filterDescription);
  37337. /** Destructor. */
  37338. virtual ~FileFilter();
  37339. /** Returns the description that the filter was created with. */
  37340. const String& getDescription() const throw();
  37341. /** Should return true if this file is suitable for inclusion in whatever context
  37342. the object is being used.
  37343. */
  37344. virtual bool isFileSuitable (const File& file) const = 0;
  37345. /** Should return true if this directory is suitable for inclusion in whatever context
  37346. the object is being used.
  37347. */
  37348. virtual bool isDirectorySuitable (const File& file) const = 0;
  37349. protected:
  37350. String description;
  37351. };
  37352. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  37353. /********* End of inlined file: juce_FileFilter.h *********/
  37354. /**
  37355. A class to asynchronously scan for details about the files in a directory.
  37356. This keeps a list of files and some information about them, using a background
  37357. thread to scan for more files. As files are found, it broadcasts change messages
  37358. to tell any listeners.
  37359. @see FileListComponent, FileBrowserComponent
  37360. */
  37361. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  37362. public TimeSliceClient
  37363. {
  37364. public:
  37365. /** Creates a directory list.
  37366. To set the directory it should point to, use setDirectory(), which will
  37367. also start it scanning for files on the background thread.
  37368. When the background thread finds and adds new files to this list, the
  37369. ChangeBroadcaster class will send a change message, so you can register
  37370. listeners and update them when the list changes.
  37371. @param fileFilter an optional filter to select which files are
  37372. included in the list. If this is 0, then all files
  37373. and directories are included. Make sure that the
  37374. filter doesn't get deleted during the lifetime of this
  37375. object
  37376. @param threadToUse a thread object that this list can use
  37377. to scan for files as a background task. Make sure
  37378. that the thread you give it has been started, or you
  37379. won't get any files!
  37380. */
  37381. DirectoryContentsList (const FileFilter* const fileFilter,
  37382. TimeSliceThread& threadToUse);
  37383. /** Destructor. */
  37384. ~DirectoryContentsList();
  37385. /** Sets the directory to look in for files.
  37386. If the directory that's passed in is different to the current one, this will
  37387. also start the background thread scanning it for files.
  37388. */
  37389. void setDirectory (const File& directory,
  37390. const bool includeDirectories,
  37391. const bool includeFiles);
  37392. /** Returns the directory that's currently being used. */
  37393. const File& getDirectory() const throw();
  37394. /** Clears the list, and stops the thread scanning for files. */
  37395. void clear();
  37396. /** Clears the list and restarts scanning the directory for files. */
  37397. void refresh();
  37398. /** True if the background thread hasn't yet finished scanning for files. */
  37399. bool isStillLoading() const;
  37400. /** Tells the list whether or not to ignore hidden files.
  37401. By default these are ignored.
  37402. */
  37403. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  37404. /** Returns true if hidden files are ignored.
  37405. @see setIgnoresHiddenFiles
  37406. */
  37407. bool ignoresHiddenFiles() const throw() { return ignoreHiddenFiles; }
  37408. /** Contains cached information about one of the files in a DirectoryContentsList.
  37409. */
  37410. struct FileInfo
  37411. {
  37412. /** The filename.
  37413. This isn't a full pathname, it's just the last part of the path, same as you'd
  37414. get from File::getFileName().
  37415. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  37416. */
  37417. String filename;
  37418. /** File size in bytes. */
  37419. int64 fileSize;
  37420. /** File modification time.
  37421. As supplied by File::getLastModificationTime().
  37422. */
  37423. Time modificationTime;
  37424. /** File creation time.
  37425. As supplied by File::getCreationTime().
  37426. */
  37427. Time creationTime;
  37428. /** True if the file is a directory. */
  37429. bool isDirectory;
  37430. /** True if the file is read-only. */
  37431. bool isReadOnly;
  37432. };
  37433. /** Returns the number of files currently available in the list.
  37434. The info about one of these files can be retrieved with getFileInfo() or
  37435. getFile().
  37436. Obviously as the background thread runs and scans the directory for files, this
  37437. number will change.
  37438. @see getFileInfo, getFile
  37439. */
  37440. int getNumFiles() const;
  37441. /** Returns the cached information about one of the files in the list.
  37442. If the index is in-range, this will return true and will copy the file's details
  37443. to the structure that is passed-in.
  37444. If it returns false, then the index wasn't in range, and the structure won't
  37445. be affected.
  37446. @see getNumFiles, getFile
  37447. */
  37448. bool getFileInfo (const int index,
  37449. FileInfo& resultInfo) const;
  37450. /** Returns one of the files in the list.
  37451. @param index should be less than getNumFiles(). If this is out-of-range, the
  37452. return value will be File::nonexistent
  37453. @see getNumFiles, getFileInfo
  37454. */
  37455. const File getFile (const int index) const;
  37456. /** Returns the file filter being used.
  37457. The filter is specified in the constructor.
  37458. */
  37459. const FileFilter* getFilter() const throw() { return fileFilter; }
  37460. /** @internal */
  37461. bool useTimeSlice();
  37462. /** @internal */
  37463. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  37464. /** @internal */
  37465. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  37466. const DirectoryContentsList::FileInfo* const second) throw();
  37467. juce_UseDebuggingNewOperator
  37468. private:
  37469. File root;
  37470. const FileFilter* fileFilter;
  37471. TimeSliceThread& thread;
  37472. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  37473. CriticalSection fileListLock;
  37474. OwnedArray <FileInfo> files;
  37475. void* volatile fileFindHandle;
  37476. bool volatile shouldStop;
  37477. void changed();
  37478. bool checkNextFile (bool& hasChanged);
  37479. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  37480. const int64 fileSize, const Time& modTime,
  37481. const Time& creationTime, const bool isReadOnly);
  37482. DirectoryContentsList (const DirectoryContentsList&);
  37483. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  37484. };
  37485. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37486. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  37487. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  37488. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37489. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37490. /**
  37491. A listener for user selection events in a file browser.
  37492. This is used by a FileBrowserComponent or FileListComponent.
  37493. */
  37494. class JUCE_API FileBrowserListener
  37495. {
  37496. public:
  37497. /** Destructor. */
  37498. virtual ~FileBrowserListener();
  37499. /** Callback when the user selects a different file in the browser. */
  37500. virtual void selectionChanged() = 0;
  37501. /** Callback when the user clicks on a file in the browser. */
  37502. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  37503. /** Callback when the user double-clicks on a file in the browser. */
  37504. virtual void fileDoubleClicked (const File& file) = 0;
  37505. };
  37506. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37507. /********* End of inlined file: juce_FileBrowserListener.h *********/
  37508. /**
  37509. A base class for components that display a list of the files in a directory.
  37510. @see DirectoryContentsList
  37511. */
  37512. class JUCE_API DirectoryContentsDisplayComponent
  37513. {
  37514. public:
  37515. /**
  37516. */
  37517. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  37518. /** Destructor. */
  37519. virtual ~DirectoryContentsDisplayComponent();
  37520. /** Returns the file that the user has currently selected.
  37521. Returns File::nonexistent if none is selected.
  37522. */
  37523. virtual const File getSelectedFile() const = 0;
  37524. /** Scrolls this view to the top. */
  37525. virtual void scrollToTop() = 0;
  37526. /** Adds a listener to be told when files are selected or clicked.
  37527. @see removeListener
  37528. */
  37529. void addListener (FileBrowserListener* const listener) throw();
  37530. /** Removes a listener.
  37531. @see addListener
  37532. */
  37533. void removeListener (FileBrowserListener* const listener) throw();
  37534. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37535. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37536. methods.
  37537. Note that you can also use the constants from TextEditor::ColourIds to change the
  37538. colour of the text editor that is opened when a label is editable.
  37539. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37540. */
  37541. enum ColourIds
  37542. {
  37543. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  37544. textColourId = 0x1000541, /**< The colour for the text. */
  37545. };
  37546. /** @internal */
  37547. void sendSelectionChangeMessage();
  37548. /** @internal */
  37549. void sendDoubleClickMessage (const File& file);
  37550. /** @internal */
  37551. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  37552. juce_UseDebuggingNewOperator
  37553. protected:
  37554. DirectoryContentsList& fileList;
  37555. SortedSet <void*> listeners;
  37556. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  37557. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  37558. };
  37559. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37560. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  37561. #endif
  37562. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37563. #endif
  37564. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37565. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  37566. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37567. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37568. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  37569. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37570. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37571. /**
  37572. Base class for components that live inside a file chooser dialog box and
  37573. show previews of the files that get selected.
  37574. One of these allows special extra information to be displayed for files
  37575. in a dialog box as the user selects them. Each time the current file or
  37576. directory is changed, the selectedFileChanged() method will be called
  37577. to allow it to update itself appropriately.
  37578. @see FileChooser, ImagePreviewComponent
  37579. */
  37580. class JUCE_API FilePreviewComponent : public Component
  37581. {
  37582. public:
  37583. /** Creates a FilePreviewComponent. */
  37584. FilePreviewComponent();
  37585. /** Destructor. */
  37586. ~FilePreviewComponent();
  37587. /** Called to indicate that the user's currently selected file has changed.
  37588. @param newSelectedFile the newly selected file or directory, which may be
  37589. File::nonexistent if none is selected.
  37590. */
  37591. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  37592. juce_UseDebuggingNewOperator
  37593. private:
  37594. FilePreviewComponent (const FilePreviewComponent&);
  37595. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  37596. };
  37597. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37598. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  37599. /**
  37600. A component for browsing and selecting a file or directory to open or save.
  37601. This contains a FileListComponent and adds various boxes and controls for
  37602. navigating and selecting a file. It can work in different modes so that it can
  37603. be used for loading or saving a file, or for choosing a directory.
  37604. @see FileChooserDialogBox, FileChooser, FileListComponent
  37605. */
  37606. class JUCE_API FileBrowserComponent : public Component,
  37607. public ChangeBroadcaster,
  37608. private FileBrowserListener,
  37609. private TextEditorListener,
  37610. private ButtonListener,
  37611. private ComboBoxListener
  37612. {
  37613. public:
  37614. /** Various modes that the browser can be used in.
  37615. One of these is passed into the constructor.
  37616. */
  37617. enum FileChooserMode
  37618. {
  37619. loadFileMode, /**< the component should allow the user to choose an existing
  37620. file with the intention of opening it. */
  37621. saveFileMode, /**< the component should allow the user to specify the name of
  37622. a file that will be used to save something. */
  37623. chooseDirectoryMode /**< the component should allow the user to select an existing
  37624. directory. */
  37625. };
  37626. /** Creates a FileBrowserComponent.
  37627. @param browserMode The intended purpose for the browser - see the
  37628. FileChooserMode enum for the various options
  37629. @param initialFileOrDirectory The file or directory that should be selected when
  37630. the component begins. If this is File::nonexistent,
  37631. a default directory will be chosen.
  37632. @param fileFilter an optional filter to use to determine which files
  37633. are shown. If this is 0 then all files are displayed. Note
  37634. that a pointer is kept internally to this object, so
  37635. make sure that it is not deleted before the browser object
  37636. is deleted.
  37637. @param previewComp an optional preview component that will be used to
  37638. show previews of files that the user selects
  37639. @param useTreeView if this is false, the files are shown in a list; if true,
  37640. they are shown in a treeview
  37641. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  37642. text into the filename box.
  37643. */
  37644. FileBrowserComponent (FileChooserMode browserMode,
  37645. const File& initialFileOrDirectory,
  37646. const FileFilter* fileFilter,
  37647. FilePreviewComponent* previewComp,
  37648. const bool useTreeView = false,
  37649. const bool filenameTextBoxIsReadOnly = false);
  37650. /** Destructor. */
  37651. ~FileBrowserComponent();
  37652. /**
  37653. */
  37654. const File getCurrentFile() const throw();
  37655. /** Returns true if the current file is usable.
  37656. This can be used to decide whether the user can press "ok" for the
  37657. current file. What it does depends on the mode, so for example in an "open"
  37658. mode, the current file is only valid if one has been selected and if the file
  37659. exists. In a "save" mode, a non-existent file would also be valid.
  37660. */
  37661. bool currentFileIsValid() const;
  37662. /** Returns the directory whose contents are currently being shown in the listbox. */
  37663. const File getRoot() const;
  37664. /** Changes the directory that's being shown in the listbox. */
  37665. void setRoot (const File& newRootDirectory);
  37666. /** Equivalent to pressing the "up" button to browse the parent directory. */
  37667. void goUp();
  37668. /** Refreshes the directory that's currently being listed. */
  37669. void refresh();
  37670. /** Returns the browser's current mode. */
  37671. FileChooserMode getMode() const throw() { return mode; }
  37672. /** Returns a verb to describe what should happen when the file is accepted.
  37673. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  37674. mode, it'll be "Save", etc.
  37675. */
  37676. virtual const String getActionVerb() const;
  37677. /** Adds a listener to be told when the user selects and clicks on files.
  37678. @see removeListener
  37679. */
  37680. void addListener (FileBrowserListener* const listener) throw();
  37681. /** Removes a listener.
  37682. @see addListener
  37683. */
  37684. void removeListener (FileBrowserListener* const listener) throw();
  37685. /** @internal */
  37686. void resized();
  37687. /** @internal */
  37688. void buttonClicked (Button* b);
  37689. /** @internal */
  37690. void comboBoxChanged (ComboBox*);
  37691. /** @internal */
  37692. void textEditorTextChanged (TextEditor& editor);
  37693. /** @internal */
  37694. void textEditorReturnKeyPressed (TextEditor& editor);
  37695. /** @internal */
  37696. void textEditorEscapeKeyPressed (TextEditor& editor);
  37697. /** @internal */
  37698. void textEditorFocusLost (TextEditor& editor);
  37699. /** @internal */
  37700. bool keyPressed (const KeyPress& key);
  37701. /** @internal */
  37702. void selectionChanged();
  37703. /** @internal */
  37704. void fileClicked (const File& f, const MouseEvent& e);
  37705. /** @internal */
  37706. void fileDoubleClicked (const File& f);
  37707. /** @internal */
  37708. FilePreviewComponent* getPreviewComponent() const throw();
  37709. juce_UseDebuggingNewOperator
  37710. protected:
  37711. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  37712. private:
  37713. DirectoryContentsList* fileList;
  37714. FileFilter* directoriesOnlyFilter;
  37715. FileChooserMode mode;
  37716. File currentRoot;
  37717. SortedSet <void*> listeners;
  37718. DirectoryContentsDisplayComponent* fileListComponent;
  37719. FilePreviewComponent* previewComp;
  37720. ComboBox* currentPathBox;
  37721. TextEditor* filenameBox;
  37722. Button* goUpButton;
  37723. TimeSliceThread thread;
  37724. void sendListenerChangeMessage();
  37725. FileBrowserComponent (const FileBrowserComponent&);
  37726. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  37727. };
  37728. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37729. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  37730. #endif
  37731. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37732. #endif
  37733. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37734. /********* Start of inlined file: juce_FileChooser.h *********/
  37735. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37736. #define __JUCE_FILECHOOSER_JUCEHEADER__
  37737. /**
  37738. Creates a dialog box to choose a file or directory to load or save.
  37739. To use a FileChooser:
  37740. - create one (as a local stack variable is the neatest way)
  37741. - call one of its browseFor.. methods
  37742. - if this returns true, the user has selected a file, so you can retrieve it
  37743. with the getResult() method.
  37744. e.g. @code
  37745. void loadMooseFile()
  37746. {
  37747. FileChooser myChooser ("Please select the moose you want to load...",
  37748. File::getSpecialLocation (File::userHomeDirectory),
  37749. "*.moose");
  37750. if (myChooser.browseForFileToOpen())
  37751. {
  37752. File mooseFile (myChooser.getResult());
  37753. loadMoose (mooseFile);
  37754. }
  37755. }
  37756. @endcode
  37757. */
  37758. class JUCE_API FileChooser
  37759. {
  37760. public:
  37761. /** Creates a FileChooser.
  37762. After creating one of these, use one of the browseFor... methods to display it.
  37763. @param dialogBoxTitle a text string to display in the dialog box to
  37764. tell the user what's going on
  37765. @param initialFileOrDirectory the file or directory that should be selected when
  37766. the dialog box opens. If this parameter is set to
  37767. File::nonexistent, a sensible default directory
  37768. will be used instead.
  37769. @param filePatternsAllowed a set of file patterns to specify which files can be
  37770. selected - each pattern should be separated by a
  37771. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  37772. empty string means that all files are allowed
  37773. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  37774. possible; if false, then a Juce-based browser dialog
  37775. box will always be used
  37776. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  37777. */
  37778. FileChooser (const String& dialogBoxTitle,
  37779. const File& initialFileOrDirectory = File::nonexistent,
  37780. const String& filePatternsAllowed = String::empty,
  37781. const bool useOSNativeDialogBox = true);
  37782. /** Destructor. */
  37783. ~FileChooser();
  37784. /** Shows a dialog box to choose a file to open.
  37785. This will display the dialog box modally, using an "open file" mode, so that
  37786. it won't allow non-existent files or directories to be chosen.
  37787. @param previewComponent an optional component to display inside the dialog
  37788. box to show special info about the files that the user
  37789. is browsing. The component will not be deleted by this
  37790. object, so the caller must take care of it.
  37791. @returns true if the user selected a file, in which case, use the getResult()
  37792. method to find out what it was. Returns false if they cancelled instead.
  37793. @see browseForFileToSave, browseForDirectory
  37794. */
  37795. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  37796. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  37797. The files that are returned can be obtained by calling getResults(). See
  37798. browseForFileToOpen() for more info about the behaviour of this method.
  37799. */
  37800. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  37801. /** Shows a dialog box to choose a file to save.
  37802. This will display the dialog box modally, using an "save file" mode, so it
  37803. will allow non-existent files to be chosen, but not directories.
  37804. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  37805. the user if they're sure they want to overwrite a file that already
  37806. exists
  37807. @returns true if the user chose a file and pressed 'ok', in which case, use
  37808. the getResult() method to find out what the file was. Returns false
  37809. if they cancelled instead.
  37810. @see browseForFileToOpen, browseForDirectory
  37811. */
  37812. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  37813. /** Shows a dialog box to choose a directory.
  37814. This will display the dialog box modally, using an "open directory" mode, so it
  37815. will only allow directories to be returned, not files.
  37816. @returns true if the user chose a directory and pressed 'ok', in which case, use
  37817. the getResult() method to find out what they chose. Returns false
  37818. if they cancelled instead.
  37819. @see browseForFileToOpen, browseForFileToSave
  37820. */
  37821. bool browseForDirectory();
  37822. /** Returns the last file that was chosen by one of the browseFor methods.
  37823. After calling the appropriate browseFor... method, this method lets you
  37824. find out what file or directory they chose.
  37825. Note that the file returned is only valid if the browse method returned true (i.e.
  37826. if the user pressed 'ok' rather than cancelling).
  37827. If you're using a multiple-file select, then use the getResults() method instead,
  37828. to obtain the list of all files chosen.
  37829. @see getResults
  37830. */
  37831. const File getResult() const;
  37832. /** Returns a list of all the files that were chosen during the last call to a
  37833. browse method.
  37834. This array may be empty if no files were chosen, or can contain multiple entries
  37835. if multiple files were chosen.
  37836. @see getResult
  37837. */
  37838. const OwnedArray <File>& getResults() const;
  37839. juce_UseDebuggingNewOperator
  37840. private:
  37841. String title, filters;
  37842. File startingFile;
  37843. OwnedArray <File> results;
  37844. bool useNativeDialogBox;
  37845. bool showDialog (const bool isDirectory,
  37846. const bool isSave,
  37847. const bool warnAboutOverwritingExistingFiles,
  37848. const bool selectMultipleFiles,
  37849. FilePreviewComponent* const previewComponent);
  37850. static void showPlatformDialog (OwnedArray<File>& results,
  37851. const String& title,
  37852. const File& file,
  37853. const String& filters,
  37854. bool isDirectory,
  37855. bool isSave,
  37856. bool warnAboutOverwritingExistingFiles,
  37857. bool selectMultipleFiles,
  37858. FilePreviewComponent* previewComponent);
  37859. };
  37860. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  37861. /********* End of inlined file: juce_FileChooser.h *********/
  37862. #endif
  37863. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37864. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  37865. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37866. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37867. /**
  37868. A file open/save dialog box.
  37869. This is a Juce-based file dialog box; to use a native file chooser, see the
  37870. FileChooser class.
  37871. To use one of these, create it and call its show() method. e.g.
  37872. @code
  37873. {
  37874. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  37875. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37876. File::nonexistent,
  37877. &wildcardFilter,
  37878. 0);
  37879. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  37880. T("Please choose some kind of file that you want to open..."),
  37881. browser,
  37882. getLookAndFeel().alertWindowBackground);
  37883. if (dialogBox.show())
  37884. {
  37885. File selectedFile = browser.getCurrentFile();
  37886. ...
  37887. }
  37888. }
  37889. @endcode
  37890. @see FileChooser
  37891. */
  37892. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37893. public ButtonListener,
  37894. public FileBrowserListener
  37895. {
  37896. public:
  37897. /** Creates a file chooser box.
  37898. @param title the main title to show at the top of the box
  37899. @param instructions an optional longer piece of text to show below the title in
  37900. a smaller font, describing in more detail what's required.
  37901. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37902. box. Make sure you delete this after (but not before!) the
  37903. dialog box has been deleted.
  37904. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37905. if they try to select a file that already exists. (This
  37906. flag is only used when saving files)
  37907. @param backgroundColour the background colour for the top level window
  37908. @see FileBrowserComponent, FilePreviewComponent
  37909. */
  37910. FileChooserDialogBox (const String& title,
  37911. const String& instructions,
  37912. FileBrowserComponent& browserComponent,
  37913. const bool warnAboutOverwritingExistingFiles,
  37914. const Colour& backgroundColour);
  37915. /** Destructor. */
  37916. ~FileChooserDialogBox();
  37917. /** Displays and runs the dialog box modally.
  37918. This will show the box with the specified size, returning true if the user
  37919. pressed 'ok', or false if they cancelled.
  37920. Leave the width or height as 0 to use the default size
  37921. */
  37922. bool show (int width = 0,int height = 0);
  37923. /** @internal */
  37924. void buttonClicked (Button* button);
  37925. /** @internal */
  37926. void closeButtonPressed();
  37927. /** @internal */
  37928. void selectionChanged();
  37929. /** @internal */
  37930. void fileClicked (const File& file, const MouseEvent& e);
  37931. /** @internal */
  37932. void fileDoubleClicked (const File& file);
  37933. juce_UseDebuggingNewOperator
  37934. private:
  37935. class ContentComponent : public Component
  37936. {
  37937. public:
  37938. ContentComponent();
  37939. ~ContentComponent();
  37940. void paint (Graphics& g);
  37941. void resized();
  37942. String instructions;
  37943. GlyphArrangement text;
  37944. FileBrowserComponent* chooserComponent;
  37945. FilePreviewComponent* previewComponent;
  37946. TextButton* okButton;
  37947. TextButton* cancelButton;
  37948. };
  37949. ContentComponent* content;
  37950. const bool warnAboutOverwritingExistingFiles;
  37951. FileChooserDialogBox (const FileChooserDialogBox&);
  37952. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37953. };
  37954. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37955. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  37956. #endif
  37957. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37958. #endif
  37959. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37960. /********* Start of inlined file: juce_FileListComponent.h *********/
  37961. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37962. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37963. /**
  37964. A component that displays the files in a directory as a listbox.
  37965. This implements the DirectoryContentsDisplayComponent base class so that
  37966. it can be used in a FileBrowserComponent.
  37967. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37968. class and the FileBrowserListener class.
  37969. @see DirectoryContentsList, FileTreeComponent
  37970. */
  37971. class JUCE_API FileListComponent : public ListBox,
  37972. public DirectoryContentsDisplayComponent,
  37973. private ListBoxModel,
  37974. private ChangeListener
  37975. {
  37976. public:
  37977. /** Creates a listbox to show the contents of a specified directory.
  37978. */
  37979. FileListComponent (DirectoryContentsList& listToShow);
  37980. /** Destructor. */
  37981. ~FileListComponent();
  37982. /** Returns the file that the user has currently selected.
  37983. Returns File::nonexistent if none is selected.
  37984. */
  37985. const File getSelectedFile() const;
  37986. /** Scrolls to the top of the list. */
  37987. void scrollToTop();
  37988. /** @internal */
  37989. void changeListenerCallback (void*);
  37990. /** @internal */
  37991. int getNumRows();
  37992. /** @internal */
  37993. void paintListBoxItem (int, Graphics&, int, int, bool);
  37994. /** @internal */
  37995. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37996. /** @internal */
  37997. void selectedRowsChanged (int lastRowSelected);
  37998. /** @internal */
  37999. void deleteKeyPressed (int currentSelectedRow);
  38000. /** @internal */
  38001. void returnKeyPressed (int currentSelectedRow);
  38002. juce_UseDebuggingNewOperator
  38003. private:
  38004. FileListComponent (const FileListComponent&);
  38005. const FileListComponent& operator= (const FileListComponent&);
  38006. File lastDirectory;
  38007. };
  38008. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38009. /********* End of inlined file: juce_FileListComponent.h *********/
  38010. #endif
  38011. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38012. #endif
  38013. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38014. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  38015. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38016. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38017. /**
  38018. Shows a set of file paths in a list, allowing them to be added, removed or
  38019. re-ordered.
  38020. @see FileSearchPath
  38021. */
  38022. class JUCE_API FileSearchPathListComponent : public Component,
  38023. public SettableTooltipClient,
  38024. public FileDragAndDropTarget,
  38025. private ButtonListener,
  38026. private ListBoxModel
  38027. {
  38028. public:
  38029. /** Creates an empty FileSearchPathListComponent.
  38030. */
  38031. FileSearchPathListComponent();
  38032. /** Destructor. */
  38033. ~FileSearchPathListComponent();
  38034. /** Returns the path as it is currently shown. */
  38035. const FileSearchPath& getPath() const throw() { return path; }
  38036. /** Changes the current path. */
  38037. void setPath (const FileSearchPath& newPath);
  38038. /** Sets a file or directory to be the default starting point for the browser to show.
  38039. This is only used if the current file hasn't been set.
  38040. */
  38041. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  38042. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38043. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38044. methods.
  38045. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38046. */
  38047. enum ColourIds
  38048. {
  38049. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  38050. Make this transparent if you don't want the background to be filled. */
  38051. };
  38052. /** @internal */
  38053. int getNumRows();
  38054. /** @internal */
  38055. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  38056. /** @internal */
  38057. void deleteKeyPressed (int lastRowSelected);
  38058. /** @internal */
  38059. void returnKeyPressed (int lastRowSelected);
  38060. /** @internal */
  38061. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  38062. /** @internal */
  38063. void selectedRowsChanged (int lastRowSelected);
  38064. /** @internal */
  38065. void resized();
  38066. /** @internal */
  38067. void paint (Graphics& g);
  38068. /** @internal */
  38069. bool isInterestedInFileDrag (const StringArray& files);
  38070. /** @internal */
  38071. void filesDropped (const StringArray& files, int, int);
  38072. /** @internal */
  38073. void buttonClicked (Button* button);
  38074. juce_UseDebuggingNewOperator
  38075. private:
  38076. FileSearchPath path;
  38077. File defaultBrowseTarget;
  38078. ListBox* listBox;
  38079. Button* addButton;
  38080. Button* removeButton;
  38081. Button* changeButton;
  38082. Button* upButton;
  38083. Button* downButton;
  38084. void changed() throw();
  38085. void updateButtons() throw();
  38086. FileSearchPathListComponent (const FileSearchPathListComponent&);
  38087. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  38088. };
  38089. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38090. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  38091. #endif
  38092. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38093. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  38094. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38095. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38096. /**
  38097. A component that displays the files in a directory as a treeview.
  38098. This implements the DirectoryContentsDisplayComponent base class so that
  38099. it can be used in a FileBrowserComponent.
  38100. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38101. class and the FileBrowserListener class.
  38102. @see DirectoryContentsList, FileListComponent
  38103. */
  38104. class JUCE_API FileTreeComponent : public TreeView,
  38105. public DirectoryContentsDisplayComponent
  38106. {
  38107. public:
  38108. /** Creates a listbox to show the contents of a specified directory.
  38109. */
  38110. FileTreeComponent (DirectoryContentsList& listToShow);
  38111. /** Destructor. */
  38112. ~FileTreeComponent();
  38113. /** Returns the number of selected files in the tree.
  38114. */
  38115. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  38116. /** Returns one of the files that the user has currently selected.
  38117. Returns File::nonexistent if none is selected.
  38118. */
  38119. const File getSelectedFile (int index) const throw();
  38120. /** Returns the first of the files that the user has currently selected.
  38121. Returns File::nonexistent if none is selected.
  38122. */
  38123. const File getSelectedFile() const;
  38124. /** Scrolls the list to the top. */
  38125. void scrollToTop();
  38126. /** Setting a name for this allows tree items to be dragged.
  38127. The string that you pass in here will be returned by the getDragSourceDescription()
  38128. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  38129. */
  38130. void setDragAndDropDescription (const String& description) throw();
  38131. /** Returns the last value that was set by setDragAndDropDescription().
  38132. */
  38133. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  38134. juce_UseDebuggingNewOperator
  38135. private:
  38136. String dragAndDropDescription;
  38137. FileTreeComponent (const FileTreeComponent&);
  38138. const FileTreeComponent& operator= (const FileTreeComponent&);
  38139. };
  38140. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38141. /********* End of inlined file: juce_FileTreeComponent.h *********/
  38142. #endif
  38143. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38144. /********* Start of inlined file: juce_FilenameComponent.h *********/
  38145. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38146. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38147. class FilenameComponent;
  38148. /**
  38149. Listens for events happening to a FilenameComponent.
  38150. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  38151. register one of these objects for event callbacks when the filename is changed.
  38152. @see FilenameComponent
  38153. */
  38154. class JUCE_API FilenameComponentListener
  38155. {
  38156. public:
  38157. /** Destructor. */
  38158. virtual ~FilenameComponentListener() {}
  38159. /** This method is called after the FilenameComponent's file has been changed. */
  38160. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  38161. };
  38162. /**
  38163. Shows a filename as an editable text box, with a 'browse' button and a
  38164. drop-down list for recently selected files.
  38165. A handy component for dialogue boxes where you want the user to be able to
  38166. select a file or directory.
  38167. Attach an FilenameComponentListener using the addListener() method, and it will
  38168. get called each time the user changes the filename, either by browsing for a file
  38169. and clicking 'ok', or by typing a new filename into the box and pressing return.
  38170. @see FileChooser, ComboBox
  38171. */
  38172. class JUCE_API FilenameComponent : public Component,
  38173. public SettableTooltipClient,
  38174. public FileDragAndDropTarget,
  38175. private AsyncUpdater,
  38176. private ButtonListener,
  38177. private ComboBoxListener
  38178. {
  38179. public:
  38180. /** Creates a FilenameComponent.
  38181. @param name the name for this component.
  38182. @param currentFile the file to initially show in the box
  38183. @param canEditFilename if true, the user can manually edit the filename; if false,
  38184. they can only change it by browsing for a new file
  38185. @param isDirectory if true, the file will be treated as a directory, and
  38186. an appropriate directory browser used
  38187. @param isForSaving if true, the file browser will allow non-existent files to
  38188. be picked, as the file is assumed to be used for saving rather
  38189. than loading
  38190. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  38191. If an empty string is passed in, then the pattern is assumed to be "*"
  38192. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  38193. to any filenames that are entered or chosen
  38194. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  38195. will only appear if the initial file isn't valid)
  38196. */
  38197. FilenameComponent (const String& name,
  38198. const File& currentFile,
  38199. const bool canEditFilename,
  38200. const bool isDirectory,
  38201. const bool isForSaving,
  38202. const String& fileBrowserWildcard,
  38203. const String& enforcedSuffix,
  38204. const String& textWhenNothingSelected);
  38205. /** Destructor. */
  38206. ~FilenameComponent();
  38207. /** Returns the currently displayed filename. */
  38208. const File getCurrentFile() const;
  38209. /** Changes the current filename.
  38210. If addToRecentlyUsedList is true, the filename will also be added to the
  38211. drop-down list of recent files.
  38212. If sendChangeNotification is false, then the listeners won't be told of the
  38213. change.
  38214. */
  38215. void setCurrentFile (File newFile,
  38216. const bool addToRecentlyUsedList,
  38217. const bool sendChangeNotification = true);
  38218. /** Changes whether the use can type into the filename box.
  38219. */
  38220. void setFilenameIsEditable (const bool shouldBeEditable);
  38221. /** Sets a file or directory to be the default starting point for the browser to show.
  38222. This is only used if the current file hasn't been set.
  38223. */
  38224. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  38225. /** Returns all the entries on the recent files list.
  38226. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  38227. state of this list.
  38228. @see setRecentlyUsedFilenames
  38229. */
  38230. const StringArray getRecentlyUsedFilenames() const;
  38231. /** Sets all the entries on the recent files list.
  38232. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  38233. state of this list.
  38234. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  38235. */
  38236. void setRecentlyUsedFilenames (const StringArray& filenames);
  38237. /** Adds an entry to the recently-used files dropdown list.
  38238. If the file is already in the list, it will be moved to the top. A limit
  38239. is also placed on the number of items that are kept in the list.
  38240. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  38241. */
  38242. void addRecentlyUsedFile (const File& file);
  38243. /** Changes the limit for the number of files that will be stored in the recent-file list.
  38244. */
  38245. void setMaxNumberOfRecentFiles (const int newMaximum);
  38246. /** Changes the text shown on the 'browse' button.
  38247. By default this button just says "..." but you can change it. The button itself
  38248. can be changed using the look-and-feel classes, so it might not actually have any
  38249. text on it.
  38250. */
  38251. void setBrowseButtonText (const String& browseButtonText);
  38252. /** Adds a listener that will be called when the selected file is changed. */
  38253. void addListener (FilenameComponentListener* const listener) throw();
  38254. /** Removes a previously-registered listener. */
  38255. void removeListener (FilenameComponentListener* const listener) throw();
  38256. /** Gives the component a tooltip. */
  38257. void setTooltip (const String& newTooltip);
  38258. /** @internal */
  38259. void paintOverChildren (Graphics& g);
  38260. /** @internal */
  38261. void resized();
  38262. /** @internal */
  38263. void lookAndFeelChanged();
  38264. /** @internal */
  38265. bool isInterestedInFileDrag (const StringArray& files);
  38266. /** @internal */
  38267. void filesDropped (const StringArray& files, int, int);
  38268. /** @internal */
  38269. void fileDragEnter (const StringArray& files, int, int);
  38270. /** @internal */
  38271. void fileDragExit (const StringArray& files);
  38272. juce_UseDebuggingNewOperator
  38273. private:
  38274. ComboBox* filenameBox;
  38275. String lastFilename;
  38276. Button* browseButton;
  38277. int maxRecentFiles;
  38278. bool isDir, isSaving, isFileDragOver;
  38279. String wildcard, enforcedSuffix, browseButtonText;
  38280. SortedSet <void*> listeners;
  38281. File defaultBrowseFile;
  38282. void comboBoxChanged (ComboBox*);
  38283. void buttonClicked (Button* button);
  38284. void handleAsyncUpdate();
  38285. FilenameComponent (const FilenameComponent&);
  38286. const FilenameComponent& operator= (const FilenameComponent&);
  38287. };
  38288. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38289. /********* End of inlined file: juce_FilenameComponent.h *********/
  38290. #endif
  38291. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38292. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  38293. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38294. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38295. /**
  38296. A simple preview component that shows thumbnails of image files.
  38297. @see FileChooserDialogBox, FilePreviewComponent
  38298. */
  38299. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  38300. private Timer
  38301. {
  38302. public:
  38303. /** Creates an ImagePreviewComponent. */
  38304. ImagePreviewComponent();
  38305. /** Destructor. */
  38306. ~ImagePreviewComponent();
  38307. /** @internal */
  38308. void selectedFileChanged (const File& newSelectedFile);
  38309. /** @internal */
  38310. void paint (Graphics& g);
  38311. /** @internal */
  38312. void timerCallback();
  38313. juce_UseDebuggingNewOperator
  38314. private:
  38315. File fileToLoad;
  38316. Image* currentThumbnail;
  38317. String currentDetails;
  38318. void getThumbSize (int& w, int& h) const;
  38319. ImagePreviewComponent (const ImagePreviewComponent&);
  38320. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  38321. };
  38322. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38323. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  38324. #endif
  38325. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38326. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  38327. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38328. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38329. /**
  38330. A type of FileFilter that works by wildcard pattern matching.
  38331. This filter only allows files that match one of the specified patterns, but
  38332. allows all directories through.
  38333. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38334. */
  38335. class JUCE_API WildcardFileFilter : public FileFilter
  38336. {
  38337. public:
  38338. /**
  38339. Creates a wildcard filter for one or more patterns.
  38340. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  38341. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  38342. or .aiff.
  38343. The description is a name to show the user in a list of possible patterns, so
  38344. for the wav/aiff example, your description might be "audio files".
  38345. */
  38346. WildcardFileFilter (const String& wildcardPatterns,
  38347. const String& description);
  38348. /** Destructor. */
  38349. ~WildcardFileFilter();
  38350. /** Returns true if the filename matches one of the patterns specified. */
  38351. bool isFileSuitable (const File& file) const;
  38352. /** This always returns true. */
  38353. bool isDirectorySuitable (const File& file) const;
  38354. juce_UseDebuggingNewOperator
  38355. private:
  38356. StringArray wildcards;
  38357. };
  38358. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38359. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  38360. #endif
  38361. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  38362. /********* Start of inlined file: juce_AlertWindow.h *********/
  38363. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  38364. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  38365. /** A window that displays a message and has buttons for the user to react to it.
  38366. For simple dialog boxes with just a couple of buttons on them, there are
  38367. some static methods for running these.
  38368. For more complex dialogs, an AlertWindow can be created, then it can have some
  38369. buttons and components added to it, and its runModalLoop() method is then used to
  38370. show it. The value returned by runModalLoop() shows which button the
  38371. user pressed to dismiss the box.
  38372. @see ThreadWithProgressWindow
  38373. */
  38374. class JUCE_API AlertWindow : public TopLevelWindow,
  38375. private ButtonListener
  38376. {
  38377. public:
  38378. /** The type of icon to show in the dialog box. */
  38379. enum AlertIconType
  38380. {
  38381. NoIcon, /**< No icon will be shown on the dialog box. */
  38382. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  38383. user to answer a question. */
  38384. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  38385. warning about something and shouldn't be ignored. */
  38386. InfoIcon /**< An icon that indicates that the dialog box is just
  38387. giving the user some information, which doesn't require
  38388. a response from them. */
  38389. };
  38390. /** Creates an AlertWindow.
  38391. @param title the headline to show at the top of the dialog box
  38392. @param message a longer, more descriptive message to show underneath the
  38393. headline
  38394. @param iconType the type of icon to display
  38395. @param associatedComponent if this is non-zero, it specifies the component that the
  38396. alert window should be associated with. Depending on the look
  38397. and feel, this might be used for positioning of the alert window.
  38398. */
  38399. AlertWindow (const String& title,
  38400. const String& message,
  38401. AlertIconType iconType,
  38402. Component* associatedComponent = 0);
  38403. /** Destroys the AlertWindow */
  38404. ~AlertWindow();
  38405. /** Returns the type of alert icon that was specified when the window
  38406. was created. */
  38407. AlertIconType getAlertType() const throw() { return alertIconType; }
  38408. /** Changes the dialog box's message.
  38409. This will also resize the window to fit the new message if required.
  38410. */
  38411. void setMessage (const String& message);
  38412. /** Adds a button to the window.
  38413. @param name the text to show on the button
  38414. @param returnValue the value that should be returned from runModalLoop()
  38415. if this is the button that the user presses.
  38416. @param shortcutKey1 an optional key that can be pressed to trigger this button
  38417. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  38418. */
  38419. void addButton (const String& name,
  38420. const int returnValue,
  38421. const KeyPress& shortcutKey1 = KeyPress(),
  38422. const KeyPress& shortcutKey2 = KeyPress());
  38423. /** Returns the number of buttons that the window currently has. */
  38424. int getNumButtons() const;
  38425. /** Adds a textbox to the window for entering strings.
  38426. @param name an internal name for the text-box. This is the name to pass to
  38427. the getTextEditorContents() method to find out what the
  38428. user typed-in.
  38429. @param initialContents a string to show in the text box when it's first shown
  38430. @param onScreenLabel if this is non-empty, it will be displayed next to the
  38431. text-box to label it.
  38432. @param isPasswordBox if true, the text editor will display asterisks instead of
  38433. the actual text
  38434. @see getTextEditorContents
  38435. */
  38436. void addTextEditor (const String& name,
  38437. const String& initialContents,
  38438. const String& onScreenLabel = String::empty,
  38439. const bool isPasswordBox = false);
  38440. /** Returns the contents of a named textbox.
  38441. After showing an AlertWindow that contains a text editor, this can be
  38442. used to find out what the user has typed into it.
  38443. @param nameOfTextEditor the name of the text box that you're interested in
  38444. @see addTextEditor
  38445. */
  38446. const String getTextEditorContents (const String& nameOfTextEditor) const;
  38447. /** Adds a drop-down list of choices to the box.
  38448. After the box has been shown, the getComboBoxComponent() method can
  38449. be used to find out which item the user picked.
  38450. @param name the label to use for the drop-down list
  38451. @param items the list of items to show in it
  38452. @param onScreenLabel if this is non-empty, it will be displayed next to the
  38453. combo-box to label it.
  38454. @see getComboBoxComponent
  38455. */
  38456. void addComboBox (const String& name,
  38457. const StringArray& items,
  38458. const String& onScreenLabel = String::empty);
  38459. /** Returns a drop-down list that was added to the AlertWindow.
  38460. @param nameOfList the name that was passed into the addComboBox() method
  38461. when creating the drop-down
  38462. @returns the ComboBox component, or 0 if none was found for the given name.
  38463. */
  38464. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  38465. /** Adds a block of text.
  38466. This is handy for adding a multi-line note next to a textbox or combo-box,
  38467. to provide more details about what's going on.
  38468. */
  38469. void addTextBlock (const String& text);
  38470. /** Adds a progress-bar to the window.
  38471. @param progressValue a variable that will be repeatedly checked while the
  38472. dialog box is visible, to see how far the process has
  38473. got. The value should be in the range 0 to 1.0
  38474. */
  38475. void addProgressBarComponent (double& progressValue);
  38476. /** Adds a user-defined component to the dialog box.
  38477. @param component the component to add - its size should be set up correctly
  38478. before it is passed in. The caller is responsible for deleting
  38479. the component later on - the AlertWindow won't delete it.
  38480. */
  38481. void addCustomComponent (Component* const component);
  38482. /** Returns the number of custom components in the dialog box.
  38483. @see getCustomComponent, addCustomComponent
  38484. */
  38485. int getNumCustomComponents() const;
  38486. /** Returns one of the custom components in the dialog box.
  38487. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  38488. will return 0
  38489. @see getNumCustomComponents, addCustomComponent
  38490. */
  38491. Component* getCustomComponent (const int index) const;
  38492. /** Removes one of the custom components in the dialog box.
  38493. Note that this won't delete it, it just removes the component from the window
  38494. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  38495. will return 0
  38496. @returns the component that was removed (or zero)
  38497. @see getNumCustomComponents, addCustomComponent
  38498. */
  38499. Component* removeCustomComponent (const int index);
  38500. /** Returns true if the window contains any components other than just buttons.*/
  38501. bool containsAnyExtraComponents() const;
  38502. // easy-to-use message box functions:
  38503. /** Shows a dialog box that just has a message and a single button to get rid of it.
  38504. The box is shown modally, and the method returns after the user
  38505. has clicked the button (or pressed the escape or return keys).
  38506. @param iconType the type of icon to show
  38507. @param title the headline to show at the top of the box
  38508. @param message a longer, more descriptive message to show underneath the
  38509. headline
  38510. @param buttonText the text to show in the button - if this string is empty, the
  38511. default string "ok" (or a localised version) will be used.
  38512. @param associatedComponent if this is non-zero, it specifies the component that the
  38513. alert window should be associated with. Depending on the look
  38514. and feel, this might be used for positioning of the alert window.
  38515. */
  38516. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  38517. const String& title,
  38518. const String& message,
  38519. const String& buttonText = String::empty,
  38520. Component* associatedComponent = 0);
  38521. /** Shows a dialog box with two buttons.
  38522. Ideal for ok/cancel or yes/no choices. The return key can also be used
  38523. to trigger the first button, and the escape key for the second button.
  38524. @param iconType the type of icon to show
  38525. @param title the headline to show at the top of the box
  38526. @param message a longer, more descriptive message to show underneath the
  38527. headline
  38528. @param button1Text the text to show in the first button - if this string is
  38529. empty, the default string "ok" (or a localised version of it)
  38530. will be used.
  38531. @param button2Text the text to show in the second button - if this string is
  38532. empty, the default string "cancel" (or a localised version of it)
  38533. will be used.
  38534. @param associatedComponent if this is non-zero, it specifies the component that the
  38535. alert window should be associated with. Depending on the look
  38536. and feel, this might be used for positioning of the alert window.
  38537. @returns true if button 1 was clicked, false if it was button 2
  38538. */
  38539. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  38540. const String& title,
  38541. const String& message,
  38542. const String& button1Text = String::empty,
  38543. const String& button2Text = String::empty,
  38544. Component* associatedComponent = 0);
  38545. /** Shows a dialog box with three buttons.
  38546. Ideal for yes/no/cancel boxes.
  38547. The escape key can be used to trigger the third button.
  38548. @param iconType the type of icon to show
  38549. @param title the headline to show at the top of the box
  38550. @param message a longer, more descriptive message to show underneath the
  38551. headline
  38552. @param button1Text the text to show in the first button - if an empty string, then
  38553. "yes" will be used (or a localised version of it)
  38554. @param button2Text the text to show in the first button - if an empty string, then
  38555. "no" will be used (or a localised version of it)
  38556. @param button3Text the text to show in the first button - if an empty string, then
  38557. "cancel" will be used (or a localised version of it)
  38558. @param associatedComponent if this is non-zero, it specifies the component that the
  38559. alert window should be associated with. Depending on the look
  38560. and feel, this might be used for positioning of the alert window.
  38561. @returns one of the following values:
  38562. - 0 if the third button was pressed (normally used for 'cancel')
  38563. - 1 if the first button was pressed (normally used for 'yes')
  38564. - 2 if the middle button was pressed (normally used for 'no')
  38565. */
  38566. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  38567. const String& title,
  38568. const String& message,
  38569. const String& button1Text = String::empty,
  38570. const String& button2Text = String::empty,
  38571. const String& button3Text = String::empty,
  38572. Component* associatedComponent = 0);
  38573. /** Shows an operating-system native dialog box.
  38574. @param title the title to use at the top
  38575. @param bodyText the longer message to show
  38576. @param isOkCancel if true, this will show an ok/cancel box, if false,
  38577. it'll show a box with just an ok button
  38578. @returns true if the ok button was pressed, false if they pressed cancel.
  38579. */
  38580. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  38581. const String& bodyText,
  38582. bool isOkCancel);
  38583. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  38584. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38585. methods.
  38586. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38587. */
  38588. enum ColourIds
  38589. {
  38590. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  38591. textColourId = 0x1001810, /**< The colour for the text. */
  38592. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  38593. };
  38594. juce_UseDebuggingNewOperator
  38595. protected:
  38596. /** @internal */
  38597. void paint (Graphics& g);
  38598. /** @internal */
  38599. void mouseDown (const MouseEvent& e);
  38600. /** @internal */
  38601. void mouseDrag (const MouseEvent& e);
  38602. /** @internal */
  38603. bool keyPressed (const KeyPress& key);
  38604. /** @internal */
  38605. void buttonClicked (Button* button);
  38606. /** @internal */
  38607. void lookAndFeelChanged();
  38608. /** @internal */
  38609. void userTriedToCloseWindow();
  38610. /** @internal */
  38611. int getDesktopWindowStyleFlags() const;
  38612. private:
  38613. String text;
  38614. TextLayout textLayout;
  38615. AlertIconType alertIconType;
  38616. ComponentBoundsConstrainer constrainer;
  38617. ComponentDragger dragger;
  38618. Rectangle textArea;
  38619. VoidArray buttons, textBoxes, comboBoxes;
  38620. VoidArray progressBars, customComps, textBlocks, allComps;
  38621. StringArray textboxNames, comboBoxNames;
  38622. Font font;
  38623. Component* associatedComponent;
  38624. void updateLayout (const bool onlyIncreaseSize);
  38625. // disable copy constructor
  38626. AlertWindow (const AlertWindow&);
  38627. const AlertWindow& operator= (const AlertWindow&);
  38628. };
  38629. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  38630. /********* End of inlined file: juce_AlertWindow.h *********/
  38631. #endif
  38632. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  38633. #endif
  38634. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  38635. /********* Start of inlined file: juce_DialogWindow.h *********/
  38636. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  38637. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  38638. /**
  38639. A dialog-box style window.
  38640. This class is a convenient way of creating a DocumentWindow with a close button
  38641. that can be triggered by pressing the escape key.
  38642. Any of the methods available to a DocumentWindow or ResizableWindow are also
  38643. available to this, so it can be made resizable, have a menu bar, etc.
  38644. To add items to the box, see the ResizableWindow::setContentComponent() method.
  38645. Don't add components directly to this class - always put them in a content component!
  38646. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  38647. the user clicking the close button - for more info, see the DocumentWindow
  38648. help.
  38649. @see DocumentWindow, ResizableWindow
  38650. */
  38651. class JUCE_API DialogWindow : public DocumentWindow
  38652. {
  38653. public:
  38654. /** Creates a DialogWindow.
  38655. @param name the name to give the component - this is also
  38656. the title shown at the top of the window. To change
  38657. this later, use setName()
  38658. @param backgroundColour the colour to use for filling the window's background.
  38659. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  38660. close button to be triggered
  38661. @param addToDesktop if true, the window will be automatically added to the
  38662. desktop; if false, you can use it as a child component
  38663. */
  38664. DialogWindow (const String& name,
  38665. const Colour& backgroundColour,
  38666. const bool escapeKeyTriggersCloseButton,
  38667. const bool addToDesktop = true);
  38668. /** Destructor.
  38669. If a content component has been set with setContentComponent(), it
  38670. will be deleted.
  38671. */
  38672. ~DialogWindow();
  38673. /** Easy way of quickly showing a dialog box containing a given component.
  38674. This will open and display a DialogWindow containing a given component, returning
  38675. when the user clicks its close button.
  38676. It returns the value that was returned by the dialog box's runModalLoop() call.
  38677. To close the dialog programatically, you should call exitModalState (returnValue) on
  38678. the DialogWindow that is created. To find a pointer to this window from your
  38679. contentComponent, you can do something like this:
  38680. @code
  38681. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  38682. if (dw != 0)
  38683. dw->exitModalState (1234);
  38684. @endcode
  38685. @param dialogTitle the dialog box's title
  38686. @param contentComponent the content component for the dialog box. Make sure
  38687. that this has been set to the size you want it to
  38688. be before calling this method. The component won't
  38689. be deleted by this call, so you can re-use it or delete
  38690. it afterwards
  38691. @param componentToCentreAround if this is non-zero, it indicates a component that
  38692. you'd like to show this dialog box in front of. See the
  38693. DocumentWindow::centreAroundComponent() method for more
  38694. info on this parameter
  38695. @param backgroundColour a colour to use for the dialog box's background colour
  38696. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  38697. close button to be triggered
  38698. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  38699. a corner resizer
  38700. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  38701. to use a border or corner resizer component. See ResizableWindow::setResizable()
  38702. */
  38703. static int showModalDialog (const String& dialogTitle,
  38704. Component* contentComponent,
  38705. Component* componentToCentreAround,
  38706. const Colour& backgroundColour,
  38707. const bool escapeKeyTriggersCloseButton,
  38708. const bool shouldBeResizable = false,
  38709. const bool useBottomRightCornerResizer = false);
  38710. juce_UseDebuggingNewOperator
  38711. protected:
  38712. /** @internal */
  38713. void resized();
  38714. private:
  38715. bool escapeKeyTriggersCloseButton;
  38716. DialogWindow (const DialogWindow&);
  38717. const DialogWindow& operator= (const DialogWindow&);
  38718. };
  38719. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  38720. /********* End of inlined file: juce_DialogWindow.h *********/
  38721. #endif
  38722. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38723. #endif
  38724. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  38725. #endif
  38726. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38727. /********* Start of inlined file: juce_SplashScreen.h *********/
  38728. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38729. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  38730. /** A component for showing a splash screen while your app starts up.
  38731. This will automatically position itself, and delete itself when the app has
  38732. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  38733. this).
  38734. To use it, just create one of these in your JUCEApplication::initialise() method,
  38735. call its show() method and let the object delete itself later.
  38736. E.g. @code
  38737. void MyApp::initialise (const String& commandLine)
  38738. {
  38739. SplashScreen* splash = new SplashScreen();
  38740. splash->show (T("welcome to my app"),
  38741. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  38742. 4000, false);
  38743. .. no need to delete the splash screen - it'll do that itself.
  38744. }
  38745. @endcode
  38746. */
  38747. class JUCE_API SplashScreen : public Component,
  38748. public Timer,
  38749. private DeletedAtShutdown
  38750. {
  38751. public:
  38752. /** Creates a SplashScreen object.
  38753. After creating one of these (or your subclass of it), call one of the show()
  38754. methods to display it.
  38755. */
  38756. SplashScreen();
  38757. /** Destructor. */
  38758. ~SplashScreen();
  38759. /** Creates a SplashScreen object that will display an image.
  38760. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38761. screen. This method will also dispatch any pending messages to make sure that when
  38762. it returns, the splash screen has been completely drawn, and your initialisation
  38763. code can carry on.
  38764. @param title the name to give the component
  38765. @param backgroundImage an image to draw on the component. The component's size
  38766. will be set to the size of this image, and if the image is
  38767. semi-transparent, the component will be made semi-transparent
  38768. too. This image will be deleted (or released from the ImageCache
  38769. if that's how it was created) by the splash screen object when
  38770. it is itself deleted.
  38771. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38772. should stay visible for. If the initialisation takes longer than
  38773. this time, the splash screen will wait for it to finish before
  38774. disappearing, but if initialisation is very quick, this lets
  38775. you make sure that people get a good look at your splash.
  38776. @param useDropShadow if true, the window will have a drop shadow
  38777. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38778. the mouse (anywhere)
  38779. */
  38780. void show (const String& title,
  38781. Image* const backgroundImage,
  38782. const int minimumTimeToDisplayFor,
  38783. const bool useDropShadow,
  38784. const bool removeOnMouseClick = true);
  38785. /** Creates a SplashScreen object with a specified size.
  38786. For a custom splash screen, you can use this method to display it at a certain size
  38787. and then override the paint() method yourself to do whatever's necessary.
  38788. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38789. screen. This method will also dispatch any pending messages to make sure that when
  38790. it returns, the splash screen has been completely drawn, and your initialisation
  38791. code can carry on.
  38792. @param title the name to give the component
  38793. @param width the width to use
  38794. @param height the height to use
  38795. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38796. should stay visible for. If the initialisation takes longer than
  38797. this time, the splash screen will wait for it to finish before
  38798. disappearing, but if initialisation is very quick, this lets
  38799. you make sure that people get a good look at your splash.
  38800. @param useDropShadow if true, the window will have a drop shadow
  38801. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38802. the mouse (anywhere)
  38803. */
  38804. void show (const String& title,
  38805. const int width,
  38806. const int height,
  38807. const int minimumTimeToDisplayFor,
  38808. const bool useDropShadow,
  38809. const bool removeOnMouseClick = true);
  38810. /** @internal */
  38811. void paint (Graphics& g);
  38812. /** @internal */
  38813. void timerCallback();
  38814. juce_UseDebuggingNewOperator
  38815. private:
  38816. Image* backgroundImage;
  38817. Time earliestTimeToDelete;
  38818. int originalClickCounter;
  38819. bool isImageInCache;
  38820. SplashScreen (const SplashScreen&);
  38821. const SplashScreen& operator= (const SplashScreen&);
  38822. };
  38823. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  38824. /********* End of inlined file: juce_SplashScreen.h *********/
  38825. #endif
  38826. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38827. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  38828. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38829. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38830. /**
  38831. A thread that automatically pops up a modal dialog box with a progress bar
  38832. and cancel button while it's busy running.
  38833. These are handy for performing some sort of task while giving the user feedback
  38834. about how long there is to go, etc.
  38835. E.g. @code
  38836. class MyTask : public ThreadWithProgressWindow
  38837. {
  38838. public:
  38839. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  38840. {
  38841. }
  38842. ~MyTask()
  38843. {
  38844. }
  38845. void run()
  38846. {
  38847. for (int i = 0; i < thingsToDo; ++i)
  38848. {
  38849. // must check this as often as possible, because this is
  38850. // how we know if the user's pressed 'cancel'
  38851. if (threadShouldExit())
  38852. break;
  38853. // this will update the progress bar on the dialog box
  38854. setProgress (i / (double) thingsToDo);
  38855. // ... do the business here...
  38856. }
  38857. }
  38858. };
  38859. void doTheTask()
  38860. {
  38861. MyTask m;
  38862. if (m.runThread())
  38863. {
  38864. // thread finished normally..
  38865. }
  38866. else
  38867. {
  38868. // user pressed the cancel button..
  38869. }
  38870. }
  38871. @endcode
  38872. @see Thread, AlertWindow
  38873. */
  38874. class JUCE_API ThreadWithProgressWindow : public Thread,
  38875. private Timer
  38876. {
  38877. public:
  38878. /** Creates the thread.
  38879. Initially, the dialog box won't be visible, it'll only appear when the
  38880. runThread() method is called.
  38881. @param windowTitle the title to go at the top of the dialog box
  38882. @param hasProgressBar whether the dialog box should have a progress bar (see
  38883. setProgress() )
  38884. @param hasCancelButton whether the dialog box should have a cancel button
  38885. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  38886. the thread to stop before killing it forcibly (see
  38887. Thread::stopThread() )
  38888. @param cancelButtonText the text that should be shown in the cancel button
  38889. (if it has one)
  38890. */
  38891. ThreadWithProgressWindow (const String& windowTitle,
  38892. const bool hasProgressBar,
  38893. const bool hasCancelButton,
  38894. const int timeOutMsWhenCancelling = 10000,
  38895. const String& cancelButtonText = JUCE_T("Cancel"));
  38896. /** Destructor. */
  38897. ~ThreadWithProgressWindow();
  38898. /** Starts the thread and waits for it to finish.
  38899. This will start the thread, make the dialog box appear, and wait until either
  38900. the thread finishes normally, or until the cancel button is pressed.
  38901. Before returning, the dialog box will be hidden.
  38902. @param threadPriority the priority to use when starting the thread - see
  38903. Thread::startThread() for values
  38904. @returns true if the thread finished normally; false if the user pressed cancel
  38905. */
  38906. bool runThread (const int threadPriority = 5);
  38907. /** The thread should call this periodically to update the position of the progress bar.
  38908. @param newProgress the progress, from 0.0 to 1.0
  38909. @see setStatusMessage
  38910. */
  38911. void setProgress (const double newProgress);
  38912. /** The thread can call this to change the message that's displayed in the dialog box.
  38913. */
  38914. void setStatusMessage (const String& newStatusMessage);
  38915. juce_UseDebuggingNewOperator
  38916. private:
  38917. void timerCallback();
  38918. double progress;
  38919. AlertWindow* alertWindow;
  38920. String message;
  38921. CriticalSection messageLock;
  38922. const int timeOutMsWhenCancelling;
  38923. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  38924. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  38925. };
  38926. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38927. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  38928. #endif
  38929. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  38930. #endif
  38931. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  38932. #endif
  38933. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38934. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  38935. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38936. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38937. #if JUCE_WIN32 || DOXYGEN
  38938. /**
  38939. A Windows-specific class that can create and embed an ActiveX control inside
  38940. itself.
  38941. To use it, create one of these, put it in place and make sure it's visible in a
  38942. window, then use createControl() to instantiate an ActiveX control. The control
  38943. will then be moved and resized to follow the movements of this component.
  38944. Of course, since the control is a heavyweight window, it'll obliterate any
  38945. juce components that may overlap this component, but that's life.
  38946. */
  38947. class JUCE_API ActiveXControlComponent : public Component
  38948. {
  38949. public:
  38950. /** Create an initially-empty container. */
  38951. ActiveXControlComponent();
  38952. /** Destructor. */
  38953. ~ActiveXControlComponent();
  38954. /** Tries to create an ActiveX control and embed it in this peer.
  38955. The peer controlIID is a pointer to an IID structure - it's treated
  38956. as a void* because when including the Juce headers, you might not always
  38957. have included windows.h first, in which case IID wouldn't be defined.
  38958. e.g. @code
  38959. const IID myIID = __uuidof (QTControl);
  38960. myControlComp->createControl (&myIID);
  38961. @endcode
  38962. */
  38963. bool createControl (const void* controlIID);
  38964. /** Deletes the ActiveX control, if one has been created.
  38965. */
  38966. void deleteControl();
  38967. /** Returns true if a control is currently in use. */
  38968. bool isControlOpen() const throw() { return control != 0; }
  38969. /** Does a QueryInterface call on the embedded control object.
  38970. This allows you to cast the control to whatever type of COM object you need.
  38971. The iid parameter is a pointer to an IID structure - it's treated
  38972. as a void* because when including the Juce headers, you might not always
  38973. have included windows.h first, in which case IID wouldn't be defined, but
  38974. you should just pass a pointer to an IID.
  38975. e.g. @code
  38976. const IID iid = __uuidof (IOleWindow);
  38977. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  38978. if (oleWindow != 0)
  38979. {
  38980. HWND hwnd;
  38981. oleWindow->GetWindow (&hwnd);
  38982. ...
  38983. oleWindow->Release();
  38984. }
  38985. @endcode
  38986. */
  38987. void* queryInterface (const void* iid) const;
  38988. /** Set this to false to stop mouse events being allowed through to the control.
  38989. */
  38990. void setMouseEventsAllowed (const bool eventsCanReachControl);
  38991. /** Returns true if mouse events are allowed to get through to the control.
  38992. */
  38993. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  38994. /** @internal */
  38995. void paint (Graphics& g);
  38996. /** @internal */
  38997. void* originalWndProc;
  38998. juce_UseDebuggingNewOperator
  38999. private:
  39000. friend class ActiveXControlData;
  39001. void* control;
  39002. bool mouseEventsAllowed;
  39003. ActiveXControlComponent (const ActiveXControlComponent&);
  39004. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  39005. void setControlBounds (const Rectangle& bounds) const;
  39006. void setControlVisible (const bool b) const;
  39007. };
  39008. #endif
  39009. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39010. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  39011. #endif
  39012. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39013. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39014. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39015. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39016. class MidiInputSelectorComponentListBox;
  39017. /**
  39018. A component containing controls to let the user change the audio settings of
  39019. an AudioDeviceManager object.
  39020. Very easy to use - just create one of these and show it to the user.
  39021. @see AudioDeviceManager
  39022. */
  39023. class JUCE_API AudioDeviceSelectorComponent : public Component,
  39024. public ComboBoxListener,
  39025. public ButtonListener,
  39026. public ChangeListener
  39027. {
  39028. public:
  39029. /** Creates the component.
  39030. If your app needs only output channels, you might ask for a maximum of 0 input
  39031. channels, and the component won't display any options for choosing the input
  39032. channels. And likewise if you're doing an input-only app.
  39033. @param deviceManager the device manager that this component should control
  39034. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  39035. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  39036. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  39037. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  39038. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  39039. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  39040. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  39041. treated as a set of separate mono channels.
  39042. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  39043. are shown, with an "advanced" button that shows the rest of them
  39044. */
  39045. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  39046. const int minAudioInputChannels,
  39047. const int maxAudioInputChannels,
  39048. const int minAudioOutputChannels,
  39049. const int maxAudioOutputChannels,
  39050. const bool showMidiInputOptions,
  39051. const bool showMidiOutputSelector,
  39052. const bool showChannelsAsStereoPairs,
  39053. const bool hideAdvancedOptionsWithButton);
  39054. /** Destructor */
  39055. ~AudioDeviceSelectorComponent();
  39056. /** @internal */
  39057. void resized();
  39058. /** @internal */
  39059. void comboBoxChanged (ComboBox*);
  39060. /** @internal */
  39061. void buttonClicked (Button*);
  39062. /** @internal */
  39063. void changeListenerCallback (void*);
  39064. /** @internal */
  39065. void childBoundsChanged (Component*);
  39066. juce_UseDebuggingNewOperator
  39067. private:
  39068. AudioDeviceManager& deviceManager;
  39069. ComboBox* deviceTypeDropDown;
  39070. Label* deviceTypeDropDownLabel;
  39071. Component* audioDeviceSettingsComp;
  39072. String audioDeviceSettingsCompType;
  39073. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  39074. const bool showChannelsAsStereoPairs;
  39075. const bool hideAdvancedOptionsWithButton;
  39076. MidiInputSelectorComponentListBox* midiInputsList;
  39077. Label* midiInputsLabel;
  39078. ComboBox* midiOutputSelector;
  39079. Label* midiOutputLabel;
  39080. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  39081. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  39082. };
  39083. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39084. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39085. #endif
  39086. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39087. /********* Start of inlined file: juce_BubbleComponent.h *********/
  39088. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39089. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39090. /**
  39091. A component for showing a message or other graphics inside a speech-bubble-shaped
  39092. outline, pointing at a location on the screen.
  39093. This is a base class that just draws and positions the bubble shape, but leaves
  39094. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  39095. that draws a text message.
  39096. To use it, create your subclass, then either add it to a parent component or
  39097. put it on the desktop with addToDesktop (0), use setPosition() to
  39098. resize and position it, then make it visible.
  39099. @see BubbleMessageComponent
  39100. */
  39101. class JUCE_API BubbleComponent : public Component
  39102. {
  39103. protected:
  39104. /** Creates a BubbleComponent.
  39105. Your subclass will need to implement the getContentSize() and paintContent()
  39106. methods to draw the bubble's contents.
  39107. */
  39108. BubbleComponent();
  39109. public:
  39110. /** Destructor. */
  39111. ~BubbleComponent();
  39112. /** A list of permitted placements for the bubble, relative to the co-ordinates
  39113. at which it should be pointing.
  39114. @see setAllowedPlacement
  39115. */
  39116. enum BubblePlacement
  39117. {
  39118. above = 1,
  39119. below = 2,
  39120. left = 4,
  39121. right = 8
  39122. };
  39123. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  39124. point at which it's pointing.
  39125. By default when setPosition() is called, the bubble will place itself either
  39126. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  39127. the values in BubblePlacement to restrict this choice.
  39128. E.g. if you only want your bubble to appear above or below the target area,
  39129. use setAllowedPlacement (above | below);
  39130. @see BubblePlacement
  39131. */
  39132. void setAllowedPlacement (const int newPlacement);
  39133. /** Moves and resizes the bubble to point at a given component.
  39134. This will resize the bubble to fit its content, then find a position for it
  39135. so that it's next to, but doesn't overlap the given component.
  39136. It'll put itself either above, below, or to the side of the component depending
  39137. on where there's the most space, honouring any restrictions that were set
  39138. with setAllowedPlacement().
  39139. */
  39140. void setPosition (Component* componentToPointTo);
  39141. /** Moves and resizes the bubble to point at a given point.
  39142. This will resize the bubble to fit its content, then position it
  39143. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  39144. are relative to either the bubble component's parent component if it has one, or
  39145. they are screen co-ordinates if not.
  39146. It'll put itself either above, below, or to the side of this point, depending
  39147. on where there's the most space, honouring any restrictions that were set
  39148. with setAllowedPlacement().
  39149. */
  39150. void setPosition (const int arrowTipX,
  39151. const int arrowTipY);
  39152. /** Moves and resizes the bubble to point at a given rectangle.
  39153. This will resize the bubble to fit its content, then find a position for it
  39154. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  39155. co-ordinates are relative to either the bubble component's parent component
  39156. if it has one, or they are screen co-ordinates if not.
  39157. It'll put itself either above, below, or to the side of the component depending
  39158. on where there's the most space, honouring any restrictions that were set
  39159. with setAllowedPlacement().
  39160. */
  39161. void setPosition (const Rectangle& rectangleToPointTo);
  39162. protected:
  39163. /** Subclasses should override this to return the size of the content they
  39164. want to draw inside the bubble.
  39165. */
  39166. virtual void getContentSize (int& width, int& height) = 0;
  39167. /** Subclasses should override this to draw their bubble's contents.
  39168. The graphics object's clip region and the dimensions passed in here are
  39169. set up to paint just the rectangle inside the bubble.
  39170. */
  39171. virtual void paintContent (Graphics& g, int width, int height) = 0;
  39172. public:
  39173. /** @internal */
  39174. void paint (Graphics& g);
  39175. juce_UseDebuggingNewOperator
  39176. private:
  39177. Rectangle content;
  39178. int side, allowablePlacements;
  39179. float arrowTipX, arrowTipY;
  39180. DropShadowEffect shadow;
  39181. BubbleComponent (const BubbleComponent&);
  39182. const BubbleComponent& operator= (const BubbleComponent&);
  39183. };
  39184. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39185. /********* End of inlined file: juce_BubbleComponent.h *********/
  39186. #endif
  39187. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39188. /********* Start of inlined file: juce_ColourSelector.h *********/
  39189. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39190. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  39191. /**
  39192. A component that lets the user choose a colour.
  39193. This shows RGB sliders and a colourspace that the user can pick colours from.
  39194. This class is also a ChangeBroadcaster, so listeners can register to be told
  39195. when the colour changes.
  39196. */
  39197. class JUCE_API ColourSelector : public Component,
  39198. public ChangeBroadcaster,
  39199. protected SliderListener
  39200. {
  39201. public:
  39202. /** Options for the type of selector to show. These are passed into the constructor. */
  39203. enum ColourSelectorOptions
  39204. {
  39205. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  39206. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  39207. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  39208. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  39209. };
  39210. /** Creates a ColourSelector object.
  39211. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  39212. which of the selector's features should be visible.
  39213. The edgeGap value specifies the amount of space to leave around the edge.
  39214. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  39215. colourspace and hue selector components.
  39216. */
  39217. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  39218. const int edgeGap = 4,
  39219. const int gapAroundColourSpaceComponent = 7);
  39220. /** Destructor. */
  39221. ~ColourSelector();
  39222. /** Returns the colour that the user has currently selected.
  39223. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  39224. register to be told when the colour changes.
  39225. @see setCurrentColour
  39226. */
  39227. const Colour getCurrentColour() const;
  39228. /** Changes the colour that is currently being shown.
  39229. */
  39230. void setCurrentColour (const Colour& newColour);
  39231. /** Tells the selector how many preset colour swatches you want to have on the component.
  39232. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39233. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39234. their values.
  39235. */
  39236. virtual int getNumSwatches() const;
  39237. /** Called by the selector to find out the colour of one of the swatches.
  39238. Your subclass should return the colour of the swatch with the given index.
  39239. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39240. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39241. their values.
  39242. */
  39243. virtual const Colour getSwatchColour (const int index) const;
  39244. /** Called by the selector when the user puts a new colour into one of the swatches.
  39245. Your subclass should change the colour of the swatch with the given index.
  39246. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39247. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39248. their values.
  39249. */
  39250. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  39251. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39252. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39253. methods.
  39254. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39255. */
  39256. enum ColourIds
  39257. {
  39258. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  39259. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  39260. };
  39261. juce_UseDebuggingNewOperator
  39262. private:
  39263. friend class ColourSpaceView;
  39264. friend class HueSelectorComp;
  39265. Colour colour;
  39266. float h, s, v;
  39267. Slider* sliders[4];
  39268. Component* colourSpace;
  39269. Component* hueSelector;
  39270. VoidArray swatchComponents;
  39271. const int flags;
  39272. int topSpace, edgeGap;
  39273. void setHue (float newH);
  39274. void setSV (float newS, float newV);
  39275. void updateHSV();
  39276. void update();
  39277. void sliderValueChanged (Slider*);
  39278. void paint (Graphics& g);
  39279. void resized();
  39280. ColourSelector (const ColourSelector&);
  39281. const ColourSelector& operator= (const ColourSelector&);
  39282. // this constructor is here temporarily to prevent old code compiling, because the parameters
  39283. // have changed - if you get an error here, update your code to use the new constructor instead..
  39284. // (xxx - note to self: remember to remove this at some point in the future)
  39285. ColourSelector (const bool);
  39286. };
  39287. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  39288. /********* End of inlined file: juce_ColourSelector.h *********/
  39289. #endif
  39290. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39291. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  39292. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39293. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39294. /**
  39295. A speech-bubble component that displays a short message.
  39296. This can be used to show a message with the tail of the speech bubble
  39297. pointing to a particular component or location on the screen.
  39298. @see BubbleComponent
  39299. */
  39300. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  39301. private Timer
  39302. {
  39303. public:
  39304. /** Creates a bubble component.
  39305. After creating one a BubbleComponent, do the following:
  39306. - add it to an appropriate parent component, or put it on the
  39307. desktop with Component::addToDesktop (0).
  39308. - use the showAt() method to show a message.
  39309. - it will make itself invisible after it times-out (and can optionally
  39310. also delete itself), or you can reuse it somewhere else by calling
  39311. showAt() again.
  39312. */
  39313. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  39314. /** Destructor. */
  39315. ~BubbleMessageComponent();
  39316. /** Shows a message bubble at a particular position.
  39317. This shows the bubble with its stem pointing to the given location
  39318. (co-ordinates being relative to its parent component).
  39319. For details about exactly how it decides where to position itself, see
  39320. BubbleComponent::updatePosition().
  39321. @param x the x co-ordinate of end of the bubble's tail
  39322. @param y the y co-ordinate of end of the bubble's tail
  39323. @param message the text to display
  39324. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39325. from its parent compnent. If this is 0 or less, it
  39326. will stay there until manually removed.
  39327. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39328. mouse button is pressed (anywhere on the screen)
  39329. @param deleteSelfAfterUse if true, then the component will delete itself after
  39330. it becomes invisible
  39331. */
  39332. void showAt (int x, int y,
  39333. const String& message,
  39334. const int numMillisecondsBeforeRemoving,
  39335. const bool removeWhenMouseClicked = true,
  39336. const bool deleteSelfAfterUse = false);
  39337. /** Shows a message bubble next to a particular component.
  39338. This shows the bubble with its stem pointing at the given component.
  39339. For details about exactly how it decides where to position itself, see
  39340. BubbleComponent::updatePosition().
  39341. @param component the component that you want to point at
  39342. @param message the text to display
  39343. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39344. from its parent compnent. If this is 0 or less, it
  39345. will stay there until manually removed.
  39346. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39347. mouse button is pressed (anywhere on the screen)
  39348. @param deleteSelfAfterUse if true, then the component will delete itself after
  39349. it becomes invisible
  39350. */
  39351. void showAt (Component* const component,
  39352. const String& message,
  39353. const int numMillisecondsBeforeRemoving,
  39354. const bool removeWhenMouseClicked = true,
  39355. const bool deleteSelfAfterUse = false);
  39356. /** @internal */
  39357. void getContentSize (int& w, int& h);
  39358. /** @internal */
  39359. void paintContent (Graphics& g, int w, int h);
  39360. /** @internal */
  39361. void timerCallback();
  39362. juce_UseDebuggingNewOperator
  39363. private:
  39364. int fadeOutLength, mouseClickCounter;
  39365. TextLayout textLayout;
  39366. int64 expiryTime;
  39367. bool deleteAfterUse;
  39368. void init (const int numMillisecondsBeforeRemoving,
  39369. const bool removeWhenMouseClicked,
  39370. const bool deleteSelfAfterUse);
  39371. BubbleMessageComponent (const BubbleMessageComponent&);
  39372. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  39373. };
  39374. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39375. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  39376. #endif
  39377. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  39378. #endif
  39379. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39380. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  39381. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39382. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39383. /**
  39384. A component that contains another component, and can magnify or shrink it.
  39385. This component will continually update its size so that it fits the zoomed
  39386. version of the content component that you put inside it, so don't try to
  39387. change the size of this component directly - instead change that of the
  39388. content component.
  39389. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  39390. to remap mouse events correctly. This means that the content component won't
  39391. appear to be a direct child of this component, and instead will think its
  39392. on the desktop.
  39393. */
  39394. class JUCE_API MagnifierComponent : public Component
  39395. {
  39396. public:
  39397. /** Creates a MagnifierComponent.
  39398. This component will continually update its size so that it fits the zoomed
  39399. version of the content component that you put inside it, so don't try to
  39400. change the size of this component directly - instead change that of the
  39401. content component.
  39402. @param contentComponent the component to add as the magnified one
  39403. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  39404. be deleted when this component is deleted. If false,
  39405. it's the caller's responsibility to delete it later.
  39406. */
  39407. MagnifierComponent (Component* const contentComponent,
  39408. const bool deleteContentCompWhenNoLongerNeeded);
  39409. /** Destructor. */
  39410. ~MagnifierComponent();
  39411. /** Returns the current content component. */
  39412. Component* getContentComponent() const throw() { return content; }
  39413. /** Changes the zoom level.
  39414. The scale factor must be greater than zero. Values less than 1 will shrink the
  39415. image; values greater than 1 will multiply its size by this amount.
  39416. When this is called, this component will change its size to fit the full extent
  39417. of the newly zoomed content.
  39418. */
  39419. void setScaleFactor (double newScaleFactor);
  39420. /** Returns the current zoom factor. */
  39421. double getScaleFactor() const throw() { return scaleFactor; }
  39422. /** Changes the quality setting used to rescale the graphics.
  39423. */
  39424. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  39425. juce_UseDebuggingNewOperator
  39426. /** @internal */
  39427. void childBoundsChanged (Component*);
  39428. private:
  39429. Component* content;
  39430. Component* holderComp;
  39431. double scaleFactor;
  39432. ComponentPeer* peer;
  39433. bool deleteContent;
  39434. Graphics::ResamplingQuality quality;
  39435. void paint (Graphics& g);
  39436. void mouseDown (const MouseEvent& e);
  39437. void mouseUp (const MouseEvent& e);
  39438. void mouseDrag (const MouseEvent& e);
  39439. void mouseMove (const MouseEvent& e);
  39440. void mouseEnter (const MouseEvent& e);
  39441. void mouseExit (const MouseEvent& e);
  39442. void mouseWheelMove (const MouseEvent& e, float, float);
  39443. int scaleInt (const int n) const throw();
  39444. MagnifierComponent (const MagnifierComponent&);
  39445. const MagnifierComponent& operator= (const MagnifierComponent&);
  39446. };
  39447. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39448. /********* End of inlined file: juce_MagnifierComponent.h *********/
  39449. #endif
  39450. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39451. /********* Start of inlined file: juce_NSViewComponent.h *********/
  39452. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39453. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39454. #if ! DOXYGEN
  39455. class NSViewComponentInternal;
  39456. #endif
  39457. #if JUCE_MAC || DOXYGEN
  39458. /**
  39459. A Mac-specific class that can create and embed an NSView inside itself.
  39460. To use it, create one of these, put it in place and make sure it's visible in a
  39461. window, then use setView() to assign an NSView to it. The view will then be
  39462. moved and resized to follow the movements of this component.
  39463. Of course, since the view is a native object, it'll obliterate any
  39464. juce components that may overlap this component, but that's life.
  39465. */
  39466. class JUCE_API NSViewComponent : public Component
  39467. {
  39468. public:
  39469. /** Create an initially-empty container. */
  39470. NSViewComponent();
  39471. /** Destructor. */
  39472. ~NSViewComponent();
  39473. /** Assigns an NSView to this peer.
  39474. The view will be retained and released by this component for as long as
  39475. it is needed. To remove the current view, just call setView (0).
  39476. Note: a void* is used here to avoid including the cocoa headers as
  39477. part of the juce.h, but the method expects an NSView*.
  39478. */
  39479. void setView (void* nsView);
  39480. /** Returns the current NSView.
  39481. Note: a void* is returned here to avoid including the cocoa headers as
  39482. a requirement of juce.h, so you should just cast the object to an NSView*.
  39483. */
  39484. void* getView() const;
  39485. /** @internal */
  39486. void paint (Graphics& g);
  39487. juce_UseDebuggingNewOperator
  39488. private:
  39489. friend class NSViewComponentInternal;
  39490. NSViewComponentInternal* info;
  39491. NSViewComponent (const NSViewComponent&);
  39492. const NSViewComponent& operator= (const NSViewComponent&);
  39493. };
  39494. #endif
  39495. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39496. /********* End of inlined file: juce_NSViewComponent.h *********/
  39497. #endif
  39498. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39499. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  39500. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39501. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39502. /**
  39503. A component that displays a piano keyboard, whose notes can be clicked on.
  39504. This component will mimic a physical midi keyboard, showing the current state of
  39505. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  39506. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  39507. Another feature is that the computer keyboard can also be used to play notes. By
  39508. default it maps the top two rows of a standard querty keyboard to the notes, but
  39509. these can be remapped if needed. It will only respond to keypresses when it has
  39510. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  39511. The component is also a ChangeBroadcaster, so if you want to be informed when the
  39512. keyboard is scrolled, you can register a ChangeListener for callbacks.
  39513. @see MidiKeyboardState
  39514. */
  39515. class JUCE_API MidiKeyboardComponent : public Component,
  39516. public MidiKeyboardStateListener,
  39517. public ChangeBroadcaster,
  39518. private Timer,
  39519. private AsyncUpdater
  39520. {
  39521. public:
  39522. /** The direction of the keyboard.
  39523. @see setOrientation
  39524. */
  39525. enum Orientation
  39526. {
  39527. horizontalKeyboard,
  39528. verticalKeyboardFacingLeft,
  39529. verticalKeyboardFacingRight,
  39530. };
  39531. /** Creates a MidiKeyboardComponent.
  39532. @param state the midi keyboard model that this component will represent
  39533. @param orientation whether the keyboard is horizonal or vertical
  39534. */
  39535. MidiKeyboardComponent (MidiKeyboardState& state,
  39536. const Orientation orientation);
  39537. /** Destructor. */
  39538. ~MidiKeyboardComponent();
  39539. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  39540. on the component.
  39541. Values are 0 to 1.0, where 1.0 is the heaviest.
  39542. @see setMidiChannel
  39543. */
  39544. void setVelocity (const float velocity);
  39545. /** Changes the midi channel number that will be used for events triggered by clicking
  39546. on the component.
  39547. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  39548. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  39549. Although this is the channel used for outgoing events, the component can display
  39550. incoming events from more than one channel - see setMidiChannelsToDisplay()
  39551. @see setVelocity
  39552. */
  39553. void setMidiChannel (const int midiChannelNumber);
  39554. /** Returns the midi channel that the keyboard is using for midi messages.
  39555. @see setMidiChannel
  39556. */
  39557. int getMidiChannel() const throw() { return midiChannel; }
  39558. /** Sets a mask to indicate which incoming midi channels should be represented by
  39559. key movements.
  39560. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  39561. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  39562. in this mask, the on-screen keys will also go down.
  39563. By default, this mask is set to 0xffff (all channels displayed).
  39564. @see setMidiChannel
  39565. */
  39566. void setMidiChannelsToDisplay (const int midiChannelMask);
  39567. /** Returns the current set of midi channels represented by the component.
  39568. This is the value that was set with setMidiChannelsToDisplay().
  39569. */
  39570. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  39571. /** Changes the width used to draw the white keys. */
  39572. void setKeyWidth (const float widthInPixels);
  39573. /** Returns the width that was set by setKeyWidth(). */
  39574. float getKeyWidth() const throw() { return keyWidth; }
  39575. /** Changes the keyboard's current direction. */
  39576. void setOrientation (const Orientation newOrientation);
  39577. /** Returns the keyboard's current direction. */
  39578. const Orientation getOrientation() const throw() { return orientation; }
  39579. /** Sets the range of midi notes that the keyboard will be limited to.
  39580. By default the range is 0 to 127 (inclusive), but you can limit this if you
  39581. only want a restricted set of the keys to be shown.
  39582. Note that the values here are inclusive and must be between 0 and 127.
  39583. */
  39584. void setAvailableRange (const int lowestNote,
  39585. const int highestNote);
  39586. /** Returns the first note in the available range.
  39587. @see setAvailableRange
  39588. */
  39589. int getRangeStart() const throw() { return rangeStart; }
  39590. /** Returns the last note in the available range.
  39591. @see setAvailableRange
  39592. */
  39593. int getRangeEnd() const throw() { return rangeEnd; }
  39594. /** If the keyboard extends beyond the size of the component, this will scroll
  39595. it to show the given key at the start.
  39596. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  39597. base class to send a callback to any ChangeListeners that have been registered.
  39598. */
  39599. void setLowestVisibleKey (int noteNumber);
  39600. /** Returns the number of the first key shown in the component.
  39601. @see setLowestVisibleKey
  39602. */
  39603. int getLowestVisibleKey() const throw() { return firstKey; }
  39604. /** Returns the length of the black notes.
  39605. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  39606. */
  39607. int getBlackNoteLength() const throw() { return blackNoteLength; }
  39608. /** If set to true, then scroll buttons will appear at either end of the keyboard
  39609. if there are too many notes to fit them all in the component at once.
  39610. */
  39611. void setScrollButtonsVisible (const bool canScroll);
  39612. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39613. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39614. methods.
  39615. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39616. */
  39617. enum ColourIds
  39618. {
  39619. whiteNoteColourId = 0x1005000,
  39620. blackNoteColourId = 0x1005001,
  39621. keySeparatorLineColourId = 0x1005002,
  39622. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  39623. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  39624. textLabelColourId = 0x1005005,
  39625. upDownButtonBackgroundColourId = 0x1005006,
  39626. upDownButtonArrowColourId = 0x1005007
  39627. };
  39628. /** Returns the position within the component of the left-hand edge of a key.
  39629. Depending on the keyboard's orientation, this may be a horizontal or vertical
  39630. distance, in either direction.
  39631. */
  39632. int getKeyStartPosition (const int midiNoteNumber) const;
  39633. /** Deletes all key-mappings.
  39634. @see setKeyPressForNote
  39635. */
  39636. void clearKeyMappings();
  39637. /** Maps a key-press to a given note.
  39638. @param key the key that should trigger the note
  39639. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  39640. be. The actual midi note that gets played will be
  39641. this value + (12 * the current base octave). To change
  39642. the base octave, see setKeyPressBaseOctave()
  39643. */
  39644. void setKeyPressForNote (const KeyPress& key,
  39645. const int midiNoteOffsetFromC);
  39646. /** Removes any key-mappings for a given note.
  39647. For a description of what the note number means, see setKeyPressForNote().
  39648. */
  39649. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  39650. /** Changes the base note above which key-press-triggered notes are played.
  39651. The set of key-mappings that trigger notes can be moved up and down to cover
  39652. the entire scale using this method.
  39653. The value passed in is an octave number between 0 and 10 (inclusive), and
  39654. indicates which C is the base note to which the key-mapped notes are
  39655. relative.
  39656. */
  39657. void setKeyPressBaseOctave (const int newOctaveNumber);
  39658. /** This sets the octave number which is shown as the octave number for middle C.
  39659. This affects only the default implementation of getWhiteNoteText(), which
  39660. passes this octave number to MidiMessage::getMidiNoteName() in order to
  39661. get the note text. See MidiMessage::getMidiNoteName() for more info about
  39662. the parameter.
  39663. By default this value is set to 3.
  39664. @see getOctaveForMiddleC
  39665. */
  39666. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  39667. /** This returns the value set by setOctaveForMiddleC().
  39668. @see setOctaveForMiddleC
  39669. */
  39670. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  39671. /** @internal */
  39672. void paint (Graphics& g);
  39673. /** @internal */
  39674. void resized();
  39675. /** @internal */
  39676. void mouseMove (const MouseEvent& e);
  39677. /** @internal */
  39678. void mouseDrag (const MouseEvent& e);
  39679. /** @internal */
  39680. void mouseDown (const MouseEvent& e);
  39681. /** @internal */
  39682. void mouseUp (const MouseEvent& e);
  39683. /** @internal */
  39684. void mouseEnter (const MouseEvent& e);
  39685. /** @internal */
  39686. void mouseExit (const MouseEvent& e);
  39687. /** @internal */
  39688. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39689. /** @internal */
  39690. void timerCallback();
  39691. /** @internal */
  39692. bool keyStateChanged (const bool isKeyDown);
  39693. /** @internal */
  39694. void focusLost (FocusChangeType cause);
  39695. /** @internal */
  39696. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  39697. /** @internal */
  39698. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  39699. /** @internal */
  39700. void handleAsyncUpdate();
  39701. /** @internal */
  39702. void colourChanged();
  39703. juce_UseDebuggingNewOperator
  39704. protected:
  39705. friend class MidiKeyboardUpDownButton;
  39706. /** Draws a white note in the given rectangle.
  39707. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39708. currently pressed down.
  39709. When doing this, be sure to note the keyboard's orientation.
  39710. */
  39711. virtual void drawWhiteNote (int midiNoteNumber,
  39712. Graphics& g,
  39713. int x, int y, int w, int h,
  39714. bool isDown, bool isOver,
  39715. const Colour& lineColour,
  39716. const Colour& textColour);
  39717. /** Draws a black note in the given rectangle.
  39718. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39719. currently pressed down.
  39720. When doing this, be sure to note the keyboard's orientation.
  39721. */
  39722. virtual void drawBlackNote (int midiNoteNumber,
  39723. Graphics& g,
  39724. int x, int y, int w, int h,
  39725. bool isDown, bool isOver,
  39726. const Colour& noteFillColour);
  39727. /** Allows text to be drawn on the white notes.
  39728. By default this is used to label the C in each octave, but could be used for other things.
  39729. @see setOctaveForMiddleC
  39730. */
  39731. virtual const String getWhiteNoteText (const int midiNoteNumber);
  39732. /** Draws the up and down buttons that change the base note. */
  39733. virtual void drawUpDownButton (Graphics& g, int w, int h,
  39734. const bool isMouseOver,
  39735. const bool isButtonPressed,
  39736. const bool movesOctavesUp);
  39737. /** Callback when the mouse is clicked on a key.
  39738. You could use this to do things like handle right-clicks on keys, etc.
  39739. Return true if you want the click to trigger the note, or false if you
  39740. want to handle it yourself and not have the note played.
  39741. @see mouseDraggedToKey
  39742. */
  39743. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  39744. /** Callback when the mouse is dragged from one key onto another.
  39745. @see mouseDownOnKey
  39746. */
  39747. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  39748. /** Calculates the positon of a given midi-note.
  39749. This can be overridden to create layouts with custom key-widths.
  39750. @param midiNoteNumber the note to find
  39751. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  39752. @param x the x position of the left-hand edge of the key (this method
  39753. always works in terms of a horizontal keyboard)
  39754. @param w the width of the key
  39755. */
  39756. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  39757. int& x, int& w) const;
  39758. private:
  39759. MidiKeyboardState& state;
  39760. int xOffset, blackNoteLength;
  39761. float keyWidth;
  39762. Orientation orientation;
  39763. int midiChannel, midiInChannelMask;
  39764. float velocity;
  39765. int noteUnderMouse, mouseDownNote;
  39766. BitArray keysPressed, keysCurrentlyDrawnDown;
  39767. int rangeStart, rangeEnd, firstKey;
  39768. bool canScroll, mouseDragging;
  39769. Button* scrollDown;
  39770. Button* scrollUp;
  39771. Array <KeyPress> keyPresses;
  39772. Array <int> keyPressNotes;
  39773. int keyMappingOctave;
  39774. int octaveNumForMiddleC;
  39775. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  39776. int xyToNote (int x, int y);
  39777. int remappedXYToNote (int x, int y) const;
  39778. void resetAnyKeysInUse();
  39779. void updateNoteUnderMouse (int x, int y);
  39780. void repaintNote (const int midiNoteNumber);
  39781. MidiKeyboardComponent (const MidiKeyboardComponent&);
  39782. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  39783. };
  39784. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39785. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  39786. #endif
  39787. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39788. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  39789. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39790. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39791. // this is used to disable OpenGL, and is defined in juce_Config.h
  39792. #if JUCE_OPENGL || DOXYGEN
  39793. class OpenGLComponentWatcher;
  39794. /**
  39795. Represents the various properties of an OpenGL bitmap format.
  39796. @see OpenGLComponent::setPixelFormat
  39797. */
  39798. struct OpenGLPixelFormat
  39799. {
  39800. /** Creates an OpenGLPixelFormat.
  39801. The default constructor just initialises the object as a simple 8-bit
  39802. RGBA format.
  39803. */
  39804. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  39805. const int alphaBits = 8,
  39806. const int depthBufferBits = 16,
  39807. const int stencilBufferBits = 0) throw();
  39808. int redBits; /**< The number of bits per pixel to use for the red channel. */
  39809. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  39810. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  39811. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  39812. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  39813. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  39814. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  39815. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  39816. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  39817. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  39818. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  39819. /** Returns a list of all the pixel formats that can be used in this system.
  39820. A reference component is needed in case there are multiple screens with different
  39821. capabilities - in which case, the one that the component is on will be used.
  39822. */
  39823. static void getAvailablePixelFormats (Component* component,
  39824. OwnedArray <OpenGLPixelFormat>& results);
  39825. bool operator== (const OpenGLPixelFormat&) const throw();
  39826. juce_UseDebuggingNewOperator
  39827. };
  39828. /**
  39829. A base class for types of OpenGL context.
  39830. An OpenGLComponent will supply its own context for drawing in its window.
  39831. */
  39832. class OpenGLContext
  39833. {
  39834. public:
  39835. /** Destructor. */
  39836. virtual ~OpenGLContext();
  39837. /** Makes this context the currently active one. */
  39838. virtual bool makeActive() const throw() = 0;
  39839. /** If this context is currently active, it is disactivated. */
  39840. virtual bool makeInactive() const throw() = 0;
  39841. /** Returns true if this context is currently active. */
  39842. virtual bool isActive() const throw() = 0;
  39843. /** Swaps the buffers (if the context can do this). */
  39844. virtual void swapBuffers() = 0;
  39845. /** Sets whether the context checks the vertical sync before swapping.
  39846. The value is the number of frames to allow between buffer-swapping. This is
  39847. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  39848. and greater numbers indicate that it should swap less often.
  39849. Returns true if it sets the value successfully.
  39850. */
  39851. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  39852. /** Returns the current swap-sync interval.
  39853. See setSwapInterval() for info about the value returned.
  39854. */
  39855. virtual int getSwapInterval() const = 0;
  39856. /** Returns the pixel format being used by this context. */
  39857. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  39858. /** For windowed contexts, this moves the context within the bounds of
  39859. its parent window.
  39860. */
  39861. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  39862. /** For windowed contexts, this triggers a repaint of the window.
  39863. (Not relevent on all platforms).
  39864. */
  39865. virtual void repaint() = 0;
  39866. /** Returns an OS-dependent handle to the raw GL context.
  39867. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  39868. a GLXContext.
  39869. */
  39870. virtual void* getRawContext() const throw() = 0;
  39871. /** This tries to create a context that can be used for drawing into the
  39872. area occupied by the specified component.
  39873. Note that you probably shouldn't use this method directly unless you know what
  39874. you're doing - the OpenGLComponent calls this and manages the context for you.
  39875. */
  39876. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  39877. const OpenGLPixelFormat& pixelFormat,
  39878. const OpenGLContext* const contextToShareWith);
  39879. /** Returns the context that's currently in active use by the calling thread.
  39880. Returns 0 if there isn't an active context.
  39881. */
  39882. static OpenGLContext* getCurrentContext();
  39883. juce_UseDebuggingNewOperator
  39884. protected:
  39885. OpenGLContext() throw();
  39886. };
  39887. /**
  39888. A component that contains an OpenGL canvas.
  39889. Override this, add it to whatever component you want to, and use the renderOpenGL()
  39890. method to draw its contents.
  39891. */
  39892. class JUCE_API OpenGLComponent : public Component
  39893. {
  39894. public:
  39895. /** Creates an OpenGLComponent.
  39896. */
  39897. OpenGLComponent();
  39898. /** Destructor. */
  39899. ~OpenGLComponent();
  39900. /** Changes the pixel format used by this component.
  39901. @see OpenGLPixelFormat::getAvailablePixelFormats()
  39902. */
  39903. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  39904. /** Returns the pixel format that this component is currently using. */
  39905. const OpenGLPixelFormat getPixelFormat() const;
  39906. /** Specifies an OpenGL context which should be shared with the one that this
  39907. component is using.
  39908. This is an OpenGL feature that lets two contexts share their texture data.
  39909. Note that this pointer is stored by the component, and when the component
  39910. needs to recreate its internal context for some reason, the same context
  39911. will be used again to share lists. So if you pass a context in here,
  39912. don't delete the context while this component is still using it! You can
  39913. call shareWith (0) to stop this component from sharing with it.
  39914. */
  39915. void shareWith (OpenGLContext* contextToShareListsWith);
  39916. /** Returns the context that this component is sharing with.
  39917. @see shareWith
  39918. */
  39919. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  39920. /** Flips the openGL buffers over. */
  39921. void swapBuffers();
  39922. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  39923. When this is called, makeCurrentContextActive() will already have been called
  39924. for you, so you just need to draw.
  39925. */
  39926. virtual void renderOpenGL() = 0;
  39927. /** This method is called when the component creates a new OpenGL context.
  39928. A new context may be created when the component is first used, or when it
  39929. is moved to a different window, or when the window is hidden and re-shown,
  39930. etc.
  39931. You can use this callback as an opportunity to set up things like textures
  39932. that your context needs.
  39933. New contexts are created on-demand by the makeCurrentContextActive() method - so
  39934. if the context is deleted, e.g. by changing the pixel format or window, no context
  39935. will be created until the next call to makeCurrentContextActive(), which will
  39936. synchronously create one and call this method. This means that if you're using
  39937. a non-GUI thread for rendering, you can make sure this method is be called by
  39938. your renderer thread.
  39939. When this callback happens, the context will already have been made current
  39940. using the makeCurrentContextActive() method, so there's no need to call it
  39941. again in your code.
  39942. */
  39943. virtual void newOpenGLContextCreated() = 0;
  39944. /** Returns the context that will draw into this component.
  39945. This may return 0 if the component is currently invisible or hasn't currently
  39946. got a context. The context object can be deleted and a new one created during
  39947. the lifetime of this component, and there may be times when it doesn't have one.
  39948. @see newOpenGLContextCreated()
  39949. */
  39950. OpenGLContext* getCurrentContext() const throw() { return context; }
  39951. /** Makes this component the current openGL context.
  39952. You might want to use this in things like your resize() method, before calling
  39953. GL commands.
  39954. If this returns false, then the context isn't active, so you should avoid
  39955. making any calls.
  39956. This call may actually create a context if one isn't currently initialised. If
  39957. it does this, it will also synchronously call the newOpenGLContextCreated()
  39958. method to let you initialise it as necessary.
  39959. @see OpenGLContext::makeActive
  39960. */
  39961. bool makeCurrentContextActive();
  39962. /** Stops the current component being the active OpenGL context.
  39963. This is the opposite of makeCurrentContextActive()
  39964. @see OpenGLContext::makeInactive
  39965. */
  39966. void makeCurrentContextInactive();
  39967. /** Returns true if this component is the active openGL context for the
  39968. current thread.
  39969. @see OpenGLContext::isActive
  39970. */
  39971. bool isActiveContext() const throw();
  39972. /** Calls the rendering callback, and swaps the buffers afterwards.
  39973. This is called automatically by paint() when the component needs to be rendered.
  39974. It can be overridden if you need to decouple the rendering from the paint callback
  39975. and render with a custom thread.
  39976. Returns true if the operation succeeded.
  39977. */
  39978. virtual bool renderAndSwapBuffers();
  39979. /** This returns a critical section that can be used to lock the current context.
  39980. Because the context that is used by this component can change, e.g. when the
  39981. component is shown or hidden, then if you're rendering to it on a background
  39982. thread, this allows you to lock the context for the duration of your rendering
  39983. routine.
  39984. */
  39985. CriticalSection& getContextLock() throw() { return contextLock; }
  39986. /** @internal */
  39987. void paint (Graphics& g);
  39988. /** Returns the native handle of an embedded heavyweight window, if there is one.
  39989. E.g. On windows, this will return the HWND of the sub-window containing
  39990. the opengl context, on the mac it'll be the NSOpenGLView.
  39991. */
  39992. void* getNativeWindowHandle() const;
  39993. juce_UseDebuggingNewOperator
  39994. private:
  39995. friend class OpenGLComponentWatcher;
  39996. OpenGLComponentWatcher* componentWatcher;
  39997. OpenGLContext* context;
  39998. OpenGLContext* contextToShareListsWith;
  39999. CriticalSection contextLock;
  40000. OpenGLPixelFormat preferredPixelFormat;
  40001. bool needToUpdateViewport;
  40002. void deleteContext();
  40003. void updateContextPosition();
  40004. void internalRepaint (int x, int y, int w, int h);
  40005. OpenGLComponent (const OpenGLComponent&);
  40006. const OpenGLComponent& operator= (const OpenGLComponent&);
  40007. };
  40008. #endif
  40009. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40010. /********* End of inlined file: juce_OpenGLComponent.h *********/
  40011. #endif
  40012. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40013. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  40014. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40015. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40016. /**
  40017. A component with a set of buttons at the top for changing between pages of
  40018. preferences.
  40019. This is just a handy way of writing a Mac-style preferences panel where you
  40020. have a row of buttons along the top for the different preference categories,
  40021. each button having an icon above its name. Clicking these will show an
  40022. appropriate prefs page below it.
  40023. You can either put one of these inside your own component, or just use the
  40024. showInDialogBox() method to show it in a window and run it modally.
  40025. To use it, just add a set of named pages with the addSettingsPage() method,
  40026. and implement the createComponentForPage() method to create suitable components
  40027. for each of these pages.
  40028. */
  40029. class JUCE_API PreferencesPanel : public Component,
  40030. private ButtonListener
  40031. {
  40032. public:
  40033. /** Creates an empty panel.
  40034. Use addSettingsPage() to add some pages to it in your constructor.
  40035. */
  40036. PreferencesPanel();
  40037. /** Destructor. */
  40038. ~PreferencesPanel();
  40039. /** Creates a page using a set of drawables to define the page's icon.
  40040. Note that the other version of this method is much easier if you're using
  40041. an image instead of a custom drawable.
  40042. @param pageTitle the name of this preferences page - you'll need to
  40043. make sure your createComponentForPage() method creates
  40044. a suitable component when it is passed this name
  40045. @param normalIcon the drawable to display in the page's button normally
  40046. @param overIcon the drawable to display in the page's button when the mouse is over
  40047. @param downIcon the drawable to display in the page's button when the button is down
  40048. @see DrawableButton
  40049. */
  40050. void addSettingsPage (const String& pageTitle,
  40051. const Drawable* normalIcon,
  40052. const Drawable* overIcon,
  40053. const Drawable* downIcon);
  40054. /** Creates a page using a set of drawables to define the page's icon.
  40055. The other version of this method gives you more control over the icon, but this
  40056. one is much easier if you're just loading it from a file.
  40057. @param pageTitle the name of this preferences page - you'll need to
  40058. make sure your createComponentForPage() method creates
  40059. a suitable component when it is passed this name
  40060. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  40061. For this to look good, you'll probably want to use a nice
  40062. transparent png file.
  40063. @param imageDataSize the size of the image data, in bytes
  40064. */
  40065. void addSettingsPage (const String& pageTitle,
  40066. const char* imageData,
  40067. const int imageDataSize);
  40068. /** Utility method to display this panel in a DialogWindow.
  40069. Calling this will create a DialogWindow containing this panel with the
  40070. given size and title, and will run it modally, returning when the user
  40071. closes the dialog box.
  40072. */
  40073. void showInDialogBox (const String& dialogtitle,
  40074. int dialogWidth,
  40075. int dialogHeight,
  40076. const Colour& backgroundColour = Colours::white);
  40077. /** Subclasses must override this to return a component for each preferences page.
  40078. The subclass should return a pointer to a new component representing the named
  40079. page, which the panel will then display.
  40080. The panel will delete the component later when the user goes to another page
  40081. or deletes the panel.
  40082. */
  40083. virtual Component* createComponentForPage (const String& pageName) = 0;
  40084. /** Changes the current page being displayed. */
  40085. void setCurrentPage (const String& pageName);
  40086. /** @internal */
  40087. void resized();
  40088. /** @internal */
  40089. void paint (Graphics& g);
  40090. /** @internal */
  40091. void buttonClicked (Button* button);
  40092. juce_UseDebuggingNewOperator
  40093. private:
  40094. String currentPageName;
  40095. Component* currentPage;
  40096. int buttonSize;
  40097. PreferencesPanel (const PreferencesPanel&);
  40098. const PreferencesPanel& operator= (const PreferencesPanel&);
  40099. };
  40100. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40101. /********* End of inlined file: juce_PreferencesPanel.h *********/
  40102. #endif
  40103. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40104. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  40105. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40106. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40107. // this is used to disable QuickTime, and is defined in juce_Config.h
  40108. #if JUCE_QUICKTIME || DOXYGEN
  40109. #if JUCE_WIN32
  40110. typedef ActiveXControlComponent QTCompBaseClass;
  40111. #else
  40112. typedef NSViewComponent QTCompBaseClass;
  40113. #endif
  40114. /**
  40115. A window that can play back a QuickTime movie.
  40116. */
  40117. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  40118. {
  40119. public:
  40120. /** Creates a QuickTimeMovieComponent, initially blank.
  40121. Use the loadMovie() method to load a movie once you've added the
  40122. component to a window, (or put it on the desktop as a heavyweight window).
  40123. Loading a movie when the component isn't visible can cause problems, as
  40124. QuickTime needs a window handle to initialise properly.
  40125. */
  40126. QuickTimeMovieComponent();
  40127. /** Destructor. */
  40128. ~QuickTimeMovieComponent();
  40129. /** Returns true if QT is installed and working on this machine.
  40130. */
  40131. static bool isQuickTimeAvailable() throw();
  40132. /** Tries to load a QuickTime movie into the player.
  40133. It's best to call this function once you've added the component to a window,
  40134. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40135. component isn't visible can cause problems, because QuickTime needs a window
  40136. handle to do its stuff.
  40137. @param movieFile the .mov file to open
  40138. @param isControllerVisible whether to show a controller bar at the bottom
  40139. @returns true if the movie opens successfully
  40140. */
  40141. bool loadMovie (const File& movieFile,
  40142. const bool isControllerVisible);
  40143. bool loadMovie (InputStream* movieStream,
  40144. const bool isControllerVisible);
  40145. /** Closes the movie, if one is open. */
  40146. void closeMovie();
  40147. /** Returns the movie file that is currently open.
  40148. If there isn't one, this returns File::nonexistent
  40149. */
  40150. const File getCurrentMovieFile() const;
  40151. /** Returns true if there's currently a movie open. */
  40152. bool isMovieOpen() const;
  40153. /** Returns the length of the movie, in seconds. */
  40154. double getMovieDuration() const;
  40155. /** Returns the movie's natural size, in pixels.
  40156. You can use this to resize the component to show the movie at its preferred
  40157. scale.
  40158. If no movie is loaded, the size returned will be 0 x 0.
  40159. */
  40160. void getMovieNormalSize (int& width, int& height) const;
  40161. /** This will position the component within a given area, keeping its aspect
  40162. ratio correct according to the movie's normal size.
  40163. The component will be made as large as it can go within the space, and will
  40164. be aligned according to the justification value if this means there are gaps at
  40165. the top or sides.
  40166. */
  40167. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  40168. const RectanglePlacement& placement);
  40169. /** Starts the movie playing. */
  40170. void play();
  40171. /** Stops the movie playing. */
  40172. void stop();
  40173. /** Returns true if the movie is currently playing. */
  40174. bool isPlaying() const;
  40175. /** Moves the movie's position back to the start. */
  40176. void goToStart();
  40177. /** Sets the movie's position to a given time. */
  40178. void setPosition (const double seconds);
  40179. /** Returns the current play position of the movie. */
  40180. double getPosition() const;
  40181. /** Changes the movie playback rate.
  40182. A value of 1 is normal speed, greater values play it proportionately faster,
  40183. smaller values play it slower.
  40184. */
  40185. void setSpeed (const float newSpeed);
  40186. /** Changes the movie's playback volume.
  40187. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  40188. */
  40189. void setMovieVolume (const float newVolume);
  40190. /** Returns the movie's playback volume.
  40191. @returns the volume in the range 0 (silent) to 1.0 (full)
  40192. */
  40193. float getMovieVolume() const;
  40194. /** Tells the movie whether it should loop. */
  40195. void setLooping (const bool shouldLoop);
  40196. /** Returns true if the movie is currently looping.
  40197. @see setLooping
  40198. */
  40199. bool isLooping() const;
  40200. /** True if the native QuickTime controller bar is shown in the window.
  40201. @see loadMovie
  40202. */
  40203. bool isControllerVisible() const;
  40204. /** @internal */
  40205. void paint (Graphics& g);
  40206. juce_UseDebuggingNewOperator
  40207. private:
  40208. File movieFile;
  40209. bool movieLoaded, controllerVisible, looping;
  40210. #if JUCE_WIN32
  40211. /** @internal */
  40212. void parentHierarchyChanged();
  40213. /** @internal */
  40214. void visibilityChanged();
  40215. void createControlIfNeeded();
  40216. bool isControlCreated() const;
  40217. void* internal;
  40218. #else
  40219. void* movie;
  40220. #endif
  40221. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  40222. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  40223. };
  40224. #endif
  40225. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40226. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  40227. #endif
  40228. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40229. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  40230. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40231. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40232. #if JUCE_WEB_BROWSER || DOXYGEN
  40233. #if ! DOXYGEN
  40234. class WebBrowserComponentInternal;
  40235. #endif
  40236. /**
  40237. A component that displays an embedded web browser.
  40238. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  40239. Windows, probably IE.
  40240. */
  40241. class JUCE_API WebBrowserComponent : public Component
  40242. {
  40243. public:
  40244. /** Creates a WebBrowserComponent.
  40245. Once it's created and visible, send the browser to a URL using goToURL().
  40246. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  40247. component is taken offscreen, it'll clear the current page
  40248. and replace it with a blank page - this can be handy to stop
  40249. the browser using resources in the background when it's not
  40250. actually being used.
  40251. */
  40252. WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden = true);
  40253. /** Destructor. */
  40254. ~WebBrowserComponent();
  40255. /** Sends the browser to a particular URL.
  40256. @param url the URL to go to.
  40257. @param headers an optional set of parameters to put in the HTTP header. If
  40258. you supply this, it should be a set of string in the form
  40259. "HeaderKey: HeaderValue"
  40260. @param postData an optional block of data that will be attached to the HTTP
  40261. POST request
  40262. */
  40263. void goToURL (const String& url,
  40264. const StringArray* headers = 0,
  40265. const MemoryBlock* postData = 0);
  40266. /** Stops the current page loading.
  40267. */
  40268. void stop();
  40269. /** Sends the browser back one page.
  40270. */
  40271. void goBack();
  40272. /** Sends the browser forward one page.
  40273. */
  40274. void goForward();
  40275. /** Refreshes the browser.
  40276. */
  40277. void refresh();
  40278. /** This callback is called when the browser is about to navigate
  40279. to a new location.
  40280. You can override this method to perform some action when the user
  40281. tries to go to a particular URL. To allow the operation to carry on,
  40282. return true, or return false to stop the navigation happening.
  40283. */
  40284. virtual bool pageAboutToLoad (const String& newURL);
  40285. /** @internal */
  40286. void paint (Graphics& g);
  40287. /** @internal */
  40288. void resized();
  40289. /** @internal */
  40290. void parentHierarchyChanged();
  40291. /** @internal */
  40292. void visibilityChanged();
  40293. juce_UseDebuggingNewOperator
  40294. private:
  40295. WebBrowserComponentInternal* browser;
  40296. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  40297. String lastURL;
  40298. StringArray lastHeaders;
  40299. MemoryBlock lastPostData;
  40300. void reloadLastURL();
  40301. void checkWindowAssociation();
  40302. WebBrowserComponent (const WebBrowserComponent&);
  40303. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  40304. };
  40305. #endif
  40306. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40307. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  40308. #endif
  40309. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40310. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  40311. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40312. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40313. #if JUCE_WIN32 || JUCE_LINUX || DOXYGEN
  40314. /**
  40315. On Windows only, this component sits in the taskbar tray as a small icon.
  40316. To use it, just create one of these components, but don't attempt to make it
  40317. visible, add it to a parent, or put it on the desktop.
  40318. You can then call setIconImage() to create an icon for it in the taskbar.
  40319. To change the icon's tooltip, you can use setIconTooltip().
  40320. To respond to mouse-events, you can override the normal mouseDown(),
  40321. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  40322. position will not be valid, you can use this to respond to clicks. Traditionally
  40323. you'd use a left-click to show your application's window, and a right-click
  40324. to show a pop-up menu.
  40325. */
  40326. class JUCE_API SystemTrayIconComponent : public Component
  40327. {
  40328. public:
  40329. SystemTrayIconComponent();
  40330. /** Destructor. */
  40331. ~SystemTrayIconComponent();
  40332. /** Changes the image shown in the taskbar.
  40333. */
  40334. void setIconImage (const Image& newImage);
  40335. /** Changes the tooltip that Windows shows above the icon. */
  40336. void setIconTooltip (const String& tooltip);
  40337. #if JUCE_LINUX
  40338. /** @internal */
  40339. void paint (Graphics& g);
  40340. #endif
  40341. juce_UseDebuggingNewOperator
  40342. private:
  40343. SystemTrayIconComponent (const SystemTrayIconComponent&);
  40344. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  40345. };
  40346. #endif
  40347. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40348. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  40349. #endif
  40350. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40351. /********* Start of inlined file: juce_LookAndFeel.h *********/
  40352. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40353. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  40354. class ToggleButton;
  40355. class TextButton;
  40356. class AlertWindow;
  40357. class TextLayout;
  40358. class ScrollBar;
  40359. class BubbleComponent;
  40360. class ComboBox;
  40361. class Button;
  40362. class FilenameComponent;
  40363. class DocumentWindow;
  40364. class ResizableWindow;
  40365. class GroupComponent;
  40366. class MenuBarComponent;
  40367. class DropShadower;
  40368. class GlyphArrangement;
  40369. class PropertyComponent;
  40370. class TableHeaderComponent;
  40371. class Toolbar;
  40372. class ToolbarItemComponent;
  40373. class PopupMenu;
  40374. class ProgressBar;
  40375. class FileBrowserComponent;
  40376. class DirectoryContentsDisplayComponent;
  40377. class FilePreviewComponent;
  40378. class ImageButton;
  40379. /**
  40380. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  40381. can be used to apply different 'skins' to the application.
  40382. */
  40383. class JUCE_API LookAndFeel
  40384. {
  40385. public:
  40386. /** Creates the default JUCE look and feel. */
  40387. LookAndFeel();
  40388. /** Destructor. */
  40389. virtual ~LookAndFeel();
  40390. /** Returns the current default look-and-feel for a component to use when it
  40391. hasn't got one explicitly set.
  40392. @see setDefaultLookAndFeel
  40393. */
  40394. static LookAndFeel& getDefaultLookAndFeel() throw();
  40395. /** Changes the default look-and-feel.
  40396. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  40397. set to 0, it will revert to using the default one. The
  40398. object passed-in must be deleted by the caller when
  40399. it's no longer needed.
  40400. @see getDefaultLookAndFeel
  40401. */
  40402. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  40403. /** Looks for a colour that has been registered with the given colour ID number.
  40404. If a colour has been set for this ID number using setColour(), then it is
  40405. returned. If none has been set, it will just return Colours::black.
  40406. The colour IDs for various purposes are stored as enums in the components that
  40407. they are relevent to - for an example, see Slider::ColourIds,
  40408. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  40409. If you're looking up a colour for use in drawing a component, it's usually
  40410. best not to call this directly, but to use the Component::findColour() method
  40411. instead. That will first check whether a suitable colour has been registered
  40412. directly with the component, and will fall-back on calling the component's
  40413. LookAndFeel's findColour() method if none is found.
  40414. @see setColour, Component::findColour, Component::setColour
  40415. */
  40416. const Colour findColour (const int colourId) const throw();
  40417. /** Registers a colour to be used for a particular purpose.
  40418. For more details, see the comments for findColour().
  40419. @see findColour, Component::findColour, Component::setColour
  40420. */
  40421. void setColour (const int colourId, const Colour& colour) throw();
  40422. /** Returns true if the specified colour ID has been explicitly set using the
  40423. setColour() method.
  40424. */
  40425. bool isColourSpecified (const int colourId) const throw();
  40426. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  40427. /** Allows you to change the default sans-serif font.
  40428. If you need to supply your own Typeface object for any of the default fonts, rather
  40429. than just supplying the name (e.g. if you want to use an embedded font), then
  40430. you should instead override getTypefaceForFont() to create and return the typeface.
  40431. */
  40432. void setDefaultSansSerifTypefaceName (const String& newName);
  40433. /** Draws the lozenge-shaped background for a standard button. */
  40434. virtual void drawButtonBackground (Graphics& g,
  40435. Button& button,
  40436. const Colour& backgroundColour,
  40437. bool isMouseOverButton,
  40438. bool isButtonDown);
  40439. virtual const Font getFontForTextButton (TextButton& button);
  40440. /** Draws the text for a TextButton. */
  40441. virtual void drawButtonText (Graphics& g,
  40442. TextButton& button,
  40443. bool isMouseOverButton,
  40444. bool isButtonDown);
  40445. /** Draws the contents of a standard ToggleButton. */
  40446. virtual void drawToggleButton (Graphics& g,
  40447. ToggleButton& button,
  40448. bool isMouseOverButton,
  40449. bool isButtonDown);
  40450. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  40451. virtual void drawTickBox (Graphics& g,
  40452. Component& component,
  40453. int x, int y, int w, int h,
  40454. const bool ticked,
  40455. const bool isEnabled,
  40456. const bool isMouseOverButton,
  40457. const bool isButtonDown);
  40458. /* AlertWindow handling..
  40459. */
  40460. virtual AlertWindow* createAlertWindow (const String& title,
  40461. const String& message,
  40462. const String& button1,
  40463. const String& button2,
  40464. const String& button3,
  40465. AlertWindow::AlertIconType iconType,
  40466. int numButtons,
  40467. Component* associatedComponent);
  40468. virtual void drawAlertBox (Graphics& g,
  40469. AlertWindow& alert,
  40470. const Rectangle& textArea,
  40471. TextLayout& textLayout);
  40472. virtual int getAlertBoxWindowFlags();
  40473. virtual int getAlertWindowButtonHeight();
  40474. virtual const Font getAlertWindowFont();
  40475. /** Draws a progress bar.
  40476. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  40477. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  40478. isn't known). It can use the current time as a basis for playing an animation.
  40479. (Used by progress bars in AlertWindow).
  40480. */
  40481. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40482. int width, int height,
  40483. double progress, const String& textToShow);
  40484. // Draws a small image that spins to indicate that something's happening..
  40485. // This method should use the current time to animate itself, so just keep
  40486. // repainting it every so often.
  40487. virtual void drawSpinningWaitAnimation (Graphics& g, int x, int y, int w, int h);
  40488. /** Draws one of the buttons on a scrollbar.
  40489. @param g the context to draw into
  40490. @param scrollbar the bar itself
  40491. @param width the width of the button
  40492. @param height the height of the button
  40493. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  40494. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40495. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  40496. @param isButtonDown whether the mouse button's held down
  40497. */
  40498. virtual void drawScrollbarButton (Graphics& g,
  40499. ScrollBar& scrollbar,
  40500. int width, int height,
  40501. int buttonDirection,
  40502. bool isScrollbarVertical,
  40503. bool isMouseOverButton,
  40504. bool isButtonDown);
  40505. /** Draws the thumb area of a scrollbar.
  40506. @param g the context to draw into
  40507. @param scrollbar the bar itself
  40508. @param x the x position of the left edge of the thumb area to draw in
  40509. @param y the y position of the top edge of the thumb area to draw in
  40510. @param width the width of the thumb area to draw in
  40511. @param height the height of the thumb area to draw in
  40512. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40513. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  40514. thumb, or its x position for horizontal bars
  40515. @param thumbSize for vertical bars, the height of the thumb, or its width for
  40516. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  40517. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  40518. currently dragging the thumb
  40519. @param isMouseDown whether the mouse is currently dragging the scrollbar
  40520. */
  40521. virtual void drawScrollbar (Graphics& g,
  40522. ScrollBar& scrollbar,
  40523. int x, int y,
  40524. int width, int height,
  40525. bool isScrollbarVertical,
  40526. int thumbStartPosition,
  40527. int thumbSize,
  40528. bool isMouseOver,
  40529. bool isMouseDown);
  40530. /** Returns the component effect to use for a scrollbar */
  40531. virtual ImageEffectFilter* getScrollbarEffect();
  40532. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  40533. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  40534. /** Returns the default thickness to use for a scrollbar. */
  40535. virtual int getDefaultScrollbarWidth();
  40536. /** Returns the length in pixels to use for a scrollbar button. */
  40537. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  40538. /** Returns a tick shape for use in yes/no boxes, etc. */
  40539. virtual const Path getTickShape (const float height);
  40540. /** Returns a cross shape for use in yes/no boxes, etc. */
  40541. virtual const Path getCrossShape (const float height);
  40542. /** Draws the + or - box in a treeview. */
  40543. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  40544. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  40545. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  40546. // these return an image from the ImageCache, so use ImageCache::release() to free it
  40547. virtual Image* getDefaultFolderImage();
  40548. virtual Image* getDefaultDocumentFileImage();
  40549. virtual void createFileChooserHeaderText (const String& title,
  40550. const String& instructions,
  40551. GlyphArrangement& destArrangement,
  40552. int width);
  40553. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  40554. const String& filename, Image* icon,
  40555. const String& fileSizeDescription,
  40556. const String& fileTimeDescription,
  40557. const bool isDirectory,
  40558. const bool isItemSelected,
  40559. const int itemIndex);
  40560. virtual Button* createFileBrowserGoUpButton();
  40561. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  40562. DirectoryContentsDisplayComponent* fileListComponent,
  40563. FilePreviewComponent* previewComp,
  40564. ComboBox* currentPathBox,
  40565. TextEditor* filenameBox,
  40566. Button* goUpButton);
  40567. virtual void drawBubble (Graphics& g,
  40568. float tipX, float tipY,
  40569. float boxX, float boxY, float boxW, float boxH);
  40570. /** Fills the background of a popup menu component. */
  40571. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40572. /** Draws one of the items in a popup menu. */
  40573. virtual void drawPopupMenuItem (Graphics& g,
  40574. int width, int height,
  40575. const bool isSeparator,
  40576. const bool isActive,
  40577. const bool isHighlighted,
  40578. const bool isTicked,
  40579. const bool hasSubMenu,
  40580. const String& text,
  40581. const String& shortcutKeyText,
  40582. Image* image,
  40583. const Colour* const textColour);
  40584. /** Returns the size and style of font to use in popup menus. */
  40585. virtual const Font getPopupMenuFont();
  40586. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40587. int width, int height,
  40588. bool isScrollUpArrow);
  40589. /** Finds the best size for an item in a popup menu. */
  40590. virtual void getIdealPopupMenuItemSize (const String& text,
  40591. const bool isSeparator,
  40592. int standardMenuItemHeight,
  40593. int& idealWidth,
  40594. int& idealHeight);
  40595. virtual int getMenuWindowFlags();
  40596. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40597. bool isMouseOverBar,
  40598. MenuBarComponent& menuBar);
  40599. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40600. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40601. virtual void drawMenuBarItem (Graphics& g,
  40602. int width, int height,
  40603. int itemIndex,
  40604. const String& itemText,
  40605. bool isMouseOverItem,
  40606. bool isMenuOpen,
  40607. bool isMouseOverBar,
  40608. MenuBarComponent& menuBar);
  40609. virtual void drawComboBox (Graphics& g, int width, int height,
  40610. const bool isButtonDown,
  40611. int buttonX, int buttonY,
  40612. int buttonW, int buttonH,
  40613. ComboBox& box);
  40614. virtual const Font getComboBoxFont (ComboBox& box);
  40615. virtual Label* createComboBoxTextBox (ComboBox& box);
  40616. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40617. virtual void drawLabel (Graphics& g, Label& label);
  40618. virtual void drawLinearSlider (Graphics& g,
  40619. int x, int y,
  40620. int width, int height,
  40621. float sliderPos,
  40622. float minSliderPos,
  40623. float maxSliderPos,
  40624. const Slider::SliderStyle style,
  40625. Slider& slider);
  40626. virtual void drawLinearSliderBackground (Graphics& g,
  40627. int x, int y,
  40628. int width, int height,
  40629. float sliderPos,
  40630. float minSliderPos,
  40631. float maxSliderPos,
  40632. const Slider::SliderStyle style,
  40633. Slider& slider);
  40634. virtual void drawLinearSliderThumb (Graphics& g,
  40635. int x, int y,
  40636. int width, int height,
  40637. float sliderPos,
  40638. float minSliderPos,
  40639. float maxSliderPos,
  40640. const Slider::SliderStyle style,
  40641. Slider& slider);
  40642. virtual int getSliderThumbRadius (Slider& slider);
  40643. virtual void drawRotarySlider (Graphics& g,
  40644. int x, int y,
  40645. int width, int height,
  40646. float sliderPosProportional,
  40647. const float rotaryStartAngle,
  40648. const float rotaryEndAngle,
  40649. Slider& slider);
  40650. virtual Button* createSliderButton (const bool isIncrement);
  40651. virtual Label* createSliderTextBox (Slider& slider);
  40652. virtual ImageEffectFilter* getSliderEffect();
  40653. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40654. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40655. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40656. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40657. ComboBox* filenameBox, Button* browseButton);
  40658. virtual void drawCornerResizer (Graphics& g,
  40659. int w, int h,
  40660. bool isMouseOver,
  40661. bool isMouseDragging);
  40662. virtual void drawResizableFrame (Graphics& g,
  40663. int w, int h,
  40664. const BorderSize& borders);
  40665. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  40666. const BorderSize& border,
  40667. ResizableWindow& window);
  40668. virtual void drawResizableWindowBorder (Graphics& g,
  40669. int w, int h,
  40670. const BorderSize& border,
  40671. ResizableWindow& window);
  40672. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40673. Graphics& g, int w, int h,
  40674. int titleSpaceX, int titleSpaceW,
  40675. const Image* icon,
  40676. bool drawTitleTextOnLeft);
  40677. virtual Button* createDocumentWindowButton (int buttonType);
  40678. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40679. int titleBarX, int titleBarY,
  40680. int titleBarW, int titleBarH,
  40681. Button* minimiseButton,
  40682. Button* maximiseButton,
  40683. Button* closeButton,
  40684. bool positionTitleBarButtonsOnLeft);
  40685. virtual int getDefaultMenuBarHeight();
  40686. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40687. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40688. int w, int h,
  40689. bool isVerticalBar,
  40690. bool isMouseOver,
  40691. bool isMouseDragging);
  40692. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40693. const String& text,
  40694. const Justification& position,
  40695. GroupComponent& group);
  40696. virtual void createTabButtonShape (Path& p,
  40697. int width, int height,
  40698. int tabIndex,
  40699. const String& text,
  40700. Button& button,
  40701. TabbedButtonBar::Orientation orientation,
  40702. const bool isMouseOver,
  40703. const bool isMouseDown,
  40704. const bool isFrontTab);
  40705. virtual void fillTabButtonShape (Graphics& g,
  40706. const Path& path,
  40707. const Colour& preferredBackgroundColour,
  40708. int tabIndex,
  40709. const String& text,
  40710. Button& button,
  40711. TabbedButtonBar::Orientation orientation,
  40712. const bool isMouseOver,
  40713. const bool isMouseDown,
  40714. const bool isFrontTab);
  40715. virtual void drawTabButtonText (Graphics& g,
  40716. int x, int y, int w, int h,
  40717. const Colour& preferredBackgroundColour,
  40718. int tabIndex,
  40719. const String& text,
  40720. Button& button,
  40721. TabbedButtonBar::Orientation orientation,
  40722. const bool isMouseOver,
  40723. const bool isMouseDown,
  40724. const bool isFrontTab);
  40725. virtual int getTabButtonOverlap (int tabDepth);
  40726. virtual int getTabButtonSpaceAroundImage();
  40727. virtual int getTabButtonBestWidth (int tabIndex,
  40728. const String& text,
  40729. int tabDepth,
  40730. Button& button);
  40731. virtual void drawTabButton (Graphics& g,
  40732. int w, int h,
  40733. const Colour& preferredColour,
  40734. int tabIndex,
  40735. const String& text,
  40736. Button& button,
  40737. TabbedButtonBar::Orientation orientation,
  40738. const bool isMouseOver,
  40739. const bool isMouseDown,
  40740. const bool isFrontTab);
  40741. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40742. int w, int h,
  40743. TabbedButtonBar& tabBar,
  40744. TabbedButtonBar::Orientation orientation);
  40745. virtual Button* createTabBarExtrasButton();
  40746. virtual void drawImageButton (Graphics& g, Image* image,
  40747. int imageX, int imageY, int imageW, int imageH,
  40748. const Colour& overlayColour,
  40749. float imageOpacity,
  40750. ImageButton& button);
  40751. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40752. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40753. int width, int height,
  40754. bool isMouseOver, bool isMouseDown,
  40755. int columnFlags);
  40756. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40757. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40758. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40759. bool isMouseOver, bool isMouseDown,
  40760. ToolbarItemComponent& component);
  40761. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40762. const String& text, ToolbarItemComponent& component);
  40763. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40764. bool isOpen, int width, int height);
  40765. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40766. PropertyComponent& component);
  40767. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40768. PropertyComponent& component);
  40769. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  40770. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40771. /**
  40772. */
  40773. virtual void playAlertSound();
  40774. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40775. static void drawGlassSphere (Graphics& g,
  40776. const float x, const float y,
  40777. const float diameter,
  40778. const Colour& colour,
  40779. const float outlineThickness) throw();
  40780. static void drawGlassPointer (Graphics& g,
  40781. const float x, const float y,
  40782. const float diameter,
  40783. const Colour& colour, const float outlineThickness,
  40784. const int direction) throw();
  40785. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40786. static void drawGlassLozenge (Graphics& g,
  40787. const float x, const float y,
  40788. const float width, const float height,
  40789. const Colour& colour,
  40790. const float outlineThickness,
  40791. const float cornerSize,
  40792. const bool flatOnLeft, const bool flatOnRight,
  40793. const bool flatOnTop, const bool flatOnBottom) throw();
  40794. juce_UseDebuggingNewOperator
  40795. protected:
  40796. // xxx the following methods are only here to cause a compiler error, because they've been
  40797. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  40798. // error if you try to build a subclass with the old versions.
  40799. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  40800. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  40801. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  40802. virtual void getTabButtonBestWidth (int, const String&, int) {}
  40803. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  40804. private:
  40805. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40806. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40807. Array <int> colourIds;
  40808. Array <Colour> colours;
  40809. // default typeface names
  40810. String defaultSans, defaultSerif, defaultFixed;
  40811. void drawShinyButtonShape (Graphics& g,
  40812. float x, float y, float w, float h, float maxCornerSize,
  40813. const Colour& baseColour,
  40814. const float strokeWidth,
  40815. const bool flatOnLeft,
  40816. const bool flatOnRight,
  40817. const bool flatOnTop,
  40818. const bool flatOnBottom) throw();
  40819. LookAndFeel (const LookAndFeel&);
  40820. const LookAndFeel& operator= (const LookAndFeel&);
  40821. };
  40822. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40823. /********* End of inlined file: juce_LookAndFeel.h *********/
  40824. #endif
  40825. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40826. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40827. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40828. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40829. /**
  40830. The original Juce look-and-feel.
  40831. */
  40832. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40833. {
  40834. public:
  40835. /** Creates the default JUCE look and feel. */
  40836. OldSchoolLookAndFeel();
  40837. /** Destructor. */
  40838. virtual ~OldSchoolLookAndFeel();
  40839. /** Draws the lozenge-shaped background for a standard button. */
  40840. virtual void drawButtonBackground (Graphics& g,
  40841. Button& button,
  40842. const Colour& backgroundColour,
  40843. bool isMouseOverButton,
  40844. bool isButtonDown);
  40845. /** Draws the contents of a standard ToggleButton. */
  40846. virtual void drawToggleButton (Graphics& g,
  40847. ToggleButton& button,
  40848. bool isMouseOverButton,
  40849. bool isButtonDown);
  40850. virtual void drawTickBox (Graphics& g,
  40851. Component& component,
  40852. int x, int y, int w, int h,
  40853. const bool ticked,
  40854. const bool isEnabled,
  40855. const bool isMouseOverButton,
  40856. const bool isButtonDown);
  40857. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40858. int width, int height,
  40859. double progress, const String& textToShow);
  40860. virtual void drawScrollbarButton (Graphics& g,
  40861. ScrollBar& scrollbar,
  40862. int width, int height,
  40863. int buttonDirection,
  40864. bool isScrollbarVertical,
  40865. bool isMouseOverButton,
  40866. bool isButtonDown);
  40867. virtual void drawScrollbar (Graphics& g,
  40868. ScrollBar& scrollbar,
  40869. int x, int y,
  40870. int width, int height,
  40871. bool isScrollbarVertical,
  40872. int thumbStartPosition,
  40873. int thumbSize,
  40874. bool isMouseOver,
  40875. bool isMouseDown);
  40876. virtual ImageEffectFilter* getScrollbarEffect();
  40877. virtual void drawTextEditorOutline (Graphics& g,
  40878. int width, int height,
  40879. TextEditor& textEditor);
  40880. /** Fills the background of a popup menu component. */
  40881. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40882. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40883. bool isMouseOverBar,
  40884. MenuBarComponent& menuBar);
  40885. virtual void drawComboBox (Graphics& g, int width, int height,
  40886. const bool isButtonDown,
  40887. int buttonX, int buttonY,
  40888. int buttonW, int buttonH,
  40889. ComboBox& box);
  40890. virtual const Font getComboBoxFont (ComboBox& box);
  40891. virtual void drawLinearSlider (Graphics& g,
  40892. int x, int y,
  40893. int width, int height,
  40894. float sliderPos,
  40895. float minSliderPos,
  40896. float maxSliderPos,
  40897. const Slider::SliderStyle style,
  40898. Slider& slider);
  40899. virtual int getSliderThumbRadius (Slider& slider);
  40900. virtual Button* createSliderButton (const bool isIncrement);
  40901. virtual ImageEffectFilter* getSliderEffect();
  40902. virtual void drawCornerResizer (Graphics& g,
  40903. int w, int h,
  40904. bool isMouseOver,
  40905. bool isMouseDragging);
  40906. virtual Button* createDocumentWindowButton (int buttonType);
  40907. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40908. int titleBarX, int titleBarY,
  40909. int titleBarW, int titleBarH,
  40910. Button* minimiseButton,
  40911. Button* maximiseButton,
  40912. Button* closeButton,
  40913. bool positionTitleBarButtonsOnLeft);
  40914. juce_UseDebuggingNewOperator
  40915. private:
  40916. DropShadowEffect scrollbarShadow;
  40917. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40918. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40919. };
  40920. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40921. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40922. #endif
  40923. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  40924. #endif
  40925. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40926. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  40927. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40928. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40929. /**
  40930. A class to take care of the logic involved with the loading/saving of some kind
  40931. of document.
  40932. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  40933. functions you need for documents that get saved to a file, so this class attempts
  40934. to abstract most of the boring stuff.
  40935. Your subclass should just implement all the pure virtual methods, and you can
  40936. then use the higher-level public methods to do the load/save dialogs, to warn the user
  40937. about overwriting files, etc.
  40938. The document object keeps track of whether it has changed since it was last saved or
  40939. loaded, so when you change something, call its changed() method. This will set a
  40940. flag so it knows it needs saving, and will also broadcast a change message using the
  40941. ChangeBroadcaster base class.
  40942. @see ChangeBroadcaster
  40943. */
  40944. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  40945. {
  40946. public:
  40947. /** Creates a FileBasedDocument.
  40948. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  40949. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  40950. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  40951. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  40952. */
  40953. FileBasedDocument (const String& fileExtension,
  40954. const String& fileWildCard,
  40955. const String& openFileDialogTitle,
  40956. const String& saveFileDialogTitle);
  40957. /** Destructor. */
  40958. virtual ~FileBasedDocument();
  40959. /** Returns true if the changed() method has been called since the file was
  40960. last saved or loaded.
  40961. @see resetChangedFlag, changed
  40962. */
  40963. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  40964. /** Called to indicate that the document has changed and needs saving.
  40965. This method will also trigger a change message to be sent out using the
  40966. ChangeBroadcaster base class.
  40967. After calling the method, the hasChangedSinceSaved() method will return true, until
  40968. it is reset either by saving to a file or using the resetChangedFlag() method.
  40969. @see hasChangedSinceSaved, resetChangedFlag
  40970. */
  40971. virtual void changed();
  40972. /** Sets the state of the 'changed' flag.
  40973. The 'changed' flag is set to true when the changed() method is called - use this method
  40974. to reset it or to set it without also broadcasting a change message.
  40975. @see changed, hasChangedSinceSaved
  40976. */
  40977. void setChangedFlag (const bool hasChanged);
  40978. /** Tries to open a file.
  40979. If the file opens correctly, the document's file (see the getFile() method) is set
  40980. to this new one; if it fails, the document's file is left unchanged, and optionally
  40981. a message box is shown telling the user there was an error.
  40982. @returns true if the new file loaded successfully
  40983. @see loadDocument, loadFromUserSpecifiedFile
  40984. */
  40985. bool loadFrom (const File& fileToLoadFrom,
  40986. const bool showMessageOnFailure);
  40987. /** Asks the user for a file and tries to load it.
  40988. This will pop up a dialog box using the title, file extension and
  40989. wildcard specified in the document's constructor, and asks the user
  40990. for a file. If they pick one, the loadFrom() method is used to
  40991. try to load it, optionally showing a message if it fails.
  40992. @returns true if a file was loaded; false if the user cancelled or if they
  40993. picked a file which failed to load correctly
  40994. @see loadFrom
  40995. */
  40996. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  40997. /** A set of possible outcomes of one of the save() methods
  40998. */
  40999. enum SaveResult
  41000. {
  41001. savedOk = 0, /**< indicates that a file was saved successfully. */
  41002. userCancelledSave, /**< indicates that the user aborted the save operation. */
  41003. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  41004. };
  41005. /** Tries to save the document to the last file it was saved or loaded from.
  41006. This will always try to write to the file, even if the document isn't flagged as
  41007. having changed.
  41008. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  41009. true, it will prompt the user to pick a file, as if
  41010. saveAsInteractive() was called.
  41011. @param showMessageOnFailure if true it will show a warning message when if the
  41012. save operation fails
  41013. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  41014. */
  41015. SaveResult save (const bool askUserForFileIfNotSpecified,
  41016. const bool showMessageOnFailure);
  41017. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  41018. it if they say yes.
  41019. If you've got a document open and want to close it (e.g. to quit the app), this is the
  41020. method to call.
  41021. If the document doesn't need saving it'll return the value savedOk so
  41022. you can go ahead and delete the document.
  41023. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  41024. return savedOk, so again, you can safely delete the document.
  41025. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  41026. close-document operation.
  41027. And if they click "save changes", it'll try to save and either return savedOk, or
  41028. failedToWriteToFile if there was a problem.
  41029. @see save, saveAs, saveAsInteractive
  41030. */
  41031. SaveResult saveIfNeededAndUserAgrees();
  41032. /** Tries to save the document to a specified file.
  41033. If this succeeds, it'll also change the document's internal file (as returned by
  41034. the getFile() method). If it fails, the file will be left unchanged.
  41035. @param newFile the file to try to write to
  41036. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  41037. the user first if they want to overwrite it
  41038. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  41039. use the saveAsInteractive() method to ask the user for a
  41040. filename
  41041. @param showMessageOnFailure if true and the write operation fails, it'll show
  41042. a message box to warn the user
  41043. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  41044. */
  41045. SaveResult saveAs (const File& newFile,
  41046. const bool warnAboutOverwritingExistingFiles,
  41047. const bool askUserForFileIfNotSpecified,
  41048. const bool showMessageOnFailure);
  41049. /** Prompts the user for a filename and tries to save to it.
  41050. This will pop up a dialog box using the title, file extension and
  41051. wildcard specified in the document's constructor, and asks the user
  41052. for a file. If they pick one, the saveAs() method is used to try to save
  41053. to this file.
  41054. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  41055. the user first if they want to overwrite it
  41056. @see saveIfNeededAndUserAgrees, save, saveAs
  41057. */
  41058. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  41059. /** Returns the file that this document was last successfully saved or loaded from.
  41060. When the document object is created, this will be set to File::nonexistent.
  41061. It is changed when one of the load or save methods is used, or when setFile()
  41062. is used to explicitly set it.
  41063. */
  41064. const File getFile() const throw() { return documentFile; }
  41065. /** Sets the file that this document thinks it was loaded from.
  41066. This won't actually load anything - it just changes the file stored internally.
  41067. @see getFile
  41068. */
  41069. void setFile (const File& newFile);
  41070. protected:
  41071. /** Overload this to return the title of the document.
  41072. This is used in message boxes, filenames and file choosers, so it should be
  41073. something sensible.
  41074. */
  41075. virtual const String getDocumentTitle() = 0;
  41076. /** This method should try to load your document from the given file.
  41077. If it fails, it should return an error message. If it succeeds, it should return
  41078. an empty string.
  41079. */
  41080. virtual const String loadDocument (const File& file) = 0;
  41081. /** This method should try to write your document to the given file.
  41082. If it fails, it should return an error message. If it succeeds, it should return
  41083. an empty string.
  41084. */
  41085. virtual const String saveDocument (const File& file) = 0;
  41086. /** This is used for dialog boxes to make them open at the last folder you
  41087. were using.
  41088. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  41089. the last document that was used - you might want to store this value
  41090. in a static variable, or even in your application's properties. It should
  41091. be a global setting rather than a property of this object.
  41092. This method works very well in conjunction with a RecentlyOpenedFilesList
  41093. object to manage your recent-files list.
  41094. As a default value, it's ok to return File::nonexistent, and the document
  41095. object will use a sensible one instead.
  41096. @see RecentlyOpenedFilesList
  41097. */
  41098. virtual const File getLastDocumentOpened() = 0;
  41099. /** This is used for dialog boxes to make them open at the last folder you
  41100. were using.
  41101. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  41102. the last document that was used - you might want to store this value
  41103. in a static variable, or even in your application's properties. It should
  41104. be a global setting rather than a property of this object.
  41105. This method works very well in conjunction with a RecentlyOpenedFilesList
  41106. object to manage your recent-files list.
  41107. @see RecentlyOpenedFilesList
  41108. */
  41109. virtual void setLastDocumentOpened (const File& file) = 0;
  41110. public:
  41111. juce_UseDebuggingNewOperator
  41112. private:
  41113. File documentFile;
  41114. bool changedSinceSave;
  41115. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  41116. FileBasedDocument (const FileBasedDocument&);
  41117. const FileBasedDocument& operator= (const FileBasedDocument&);
  41118. };
  41119. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41120. /********* End of inlined file: juce_FileBasedDocument.h *********/
  41121. #endif
  41122. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  41123. #endif
  41124. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41125. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  41126. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41127. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41128. /**
  41129. Manages a set of files for use as a list of recently-opened documents.
  41130. This is a handy class for holding your list of recently-opened documents, with
  41131. helpful methods for things like purging any non-existent files, automatically
  41132. adding them to a menu, and making persistence easy.
  41133. @see File, FileBasedDocument
  41134. */
  41135. class JUCE_API RecentlyOpenedFilesList
  41136. {
  41137. public:
  41138. /** Creates an empty list.
  41139. */
  41140. RecentlyOpenedFilesList();
  41141. /** Destructor. */
  41142. ~RecentlyOpenedFilesList();
  41143. /** Sets a limit for the number of files that will be stored in the list.
  41144. When addFile() is called, then if there is no more space in the list, the
  41145. least-recently added file will be dropped.
  41146. @see getMaxNumberOfItems
  41147. */
  41148. void setMaxNumberOfItems (const int newMaxNumber);
  41149. /** Returns the number of items that this list will store.
  41150. @see setMaxNumberOfItems
  41151. */
  41152. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  41153. /** Returns the number of files in the list.
  41154. The most recently added file is always at index 0.
  41155. */
  41156. int getNumFiles() const;
  41157. /** Returns one of the files in the list.
  41158. The most recently added file is always at index 0.
  41159. */
  41160. const File getFile (const int index) const;
  41161. /** Returns an array of all the absolute pathnames in the list.
  41162. */
  41163. const StringArray& getAllFilenames() const throw() { return files; }
  41164. /** Clears all the files from the list. */
  41165. void clear();
  41166. /** Adds a file to the list.
  41167. The file will be added at index 0. If this file is already in the list, it will
  41168. be moved up to index 0, but a file can only appear once in the list.
  41169. If the list already contains the maximum number of items that is permitted, the
  41170. least-recently added file will be dropped from the end.
  41171. */
  41172. void addFile (const File& file);
  41173. /** Checks each of the files in the list, removing any that don't exist.
  41174. You might want to call this after reloading a list of files, or before putting them
  41175. on a menu.
  41176. */
  41177. void removeNonExistentFiles();
  41178. /** Adds entries to a menu, representing each of the files in the list.
  41179. This is handy for creating an "open recent file..." menu in your app. The
  41180. menu items are numbered consecutively starting with the baseItemId value,
  41181. and can either be added as complete pathnames, or just the last part of the
  41182. filename.
  41183. If dontAddNonExistentFiles is true, then each file will be checked and only those
  41184. that exist will be added.
  41185. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  41186. pointers to file objects. Any files that appear in this list will not be added to the
  41187. menu - the reason for this is that you might have a number of files already open, so
  41188. might not want these to be shown in the menu.
  41189. It returns the number of items that were added.
  41190. */
  41191. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  41192. const int baseItemId,
  41193. const bool showFullPaths,
  41194. const bool dontAddNonExistentFiles,
  41195. const File** filesToAvoid = 0);
  41196. /** Returns a string that encapsulates all the files in the list.
  41197. The string that is returned can later be passed into restoreFromString() in
  41198. order to recreate the list. This is handy for persisting your list, e.g. in
  41199. a PropertiesFile object.
  41200. @see restoreFromString
  41201. */
  41202. const String toString() const;
  41203. /** Restores the list from a previously stringified version of the list.
  41204. Pass in a stringified version created with toString() in order to persist/restore
  41205. your list.
  41206. @see toString
  41207. */
  41208. void restoreFromString (const String& stringifiedVersion);
  41209. juce_UseDebuggingNewOperator
  41210. private:
  41211. StringArray files;
  41212. int maxNumberOfItems;
  41213. };
  41214. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41215. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  41216. #endif
  41217. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  41218. #endif
  41219. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41220. /********* Start of inlined file: juce_SystemClipboard.h *********/
  41221. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41222. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41223. /**
  41224. Handles reading/writing to the system's clipboard.
  41225. */
  41226. class JUCE_API SystemClipboard
  41227. {
  41228. public:
  41229. /** Copies a string of text onto the clipboard */
  41230. static void copyTextToClipboard (const String& text) throw();
  41231. /** Gets the current clipboard's contents.
  41232. Obviously this might have come from another app, so could contain
  41233. anything..
  41234. */
  41235. static const String getTextFromClipboard() throw();
  41236. };
  41237. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41238. /********* End of inlined file: juce_SystemClipboard.h *********/
  41239. #endif
  41240. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  41241. #endif
  41242. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  41243. #endif
  41244. #endif
  41245. /********* End of inlined file: juce_app_includes.h *********/
  41246. #endif
  41247. #if JUCE_MSVC
  41248. #pragma warning (pop)
  41249. #pragma pack (pop)
  41250. #endif
  41251. #if JUCE_MAC
  41252. #pragma align=reset
  41253. #endif
  41254. END_JUCE_NAMESPACE
  41255. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  41256. #ifdef JUCE_NAMESPACE
  41257. // this will obviously save a lot of typing, but can be disabled by
  41258. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  41259. using namespace JUCE_NAMESPACE;
  41260. /* On the Mac, these symbols are defined in the Mac libraries, so
  41261. these macros make it easier to reference them without writing out
  41262. the namespace every time.
  41263. If you run into difficulties where these macros interfere with the contents
  41264. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  41265. the comments in that file for more information.
  41266. */
  41267. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  41268. #define Component JUCE_NAMESPACE::Component
  41269. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  41270. #define Point JUCE_NAMESPACE::Point
  41271. #define Button JUCE_NAMESPACE::Button
  41272. #endif
  41273. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  41274. it easier to use the juce version explicitly.
  41275. If you run into difficulties where this macro interferes with other 3rd party header
  41276. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  41277. file for more information.
  41278. */
  41279. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  41280. #define Rectangle JUCE_NAMESPACE::Rectangle
  41281. #endif
  41282. #endif
  41283. #endif
  41284. /* Easy autolinking to the right JUCE libraries under win32.
  41285. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  41286. including this header file.
  41287. */
  41288. #if JUCE_MSVC
  41289. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  41290. /** If you want your application to link to Juce as a DLL instead of
  41291. a static library (on win32), just define the JUCE_DLL macro before
  41292. including juce.h
  41293. */
  41294. #ifdef JUCE_DLL
  41295. #ifdef JUCE_DEBUG
  41296. #define AUTOLINKEDLIB "JUCE_debug.lib"
  41297. #else
  41298. #define AUTOLINKEDLIB "JUCE.lib"
  41299. #endif
  41300. #else
  41301. #ifdef JUCE_DEBUG
  41302. #ifdef _WIN64
  41303. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  41304. #else
  41305. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  41306. #endif
  41307. #else
  41308. #ifdef _WIN64
  41309. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  41310. #else
  41311. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  41312. #endif
  41313. #endif
  41314. #endif
  41315. #pragma comment(lib, AUTOLINKEDLIB)
  41316. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  41317. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  41318. #endif
  41319. // Auto-link the other win32 libs that are needed by library calls..
  41320. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  41321. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  41322. // Auto-links to various win32 libs that are needed by library calls..
  41323. #pragma comment(lib, "kernel32.lib")
  41324. #pragma comment(lib, "user32.lib")
  41325. #pragma comment(lib, "shell32.lib")
  41326. #pragma comment(lib, "gdi32.lib")
  41327. #pragma comment(lib, "vfw32.lib")
  41328. #pragma comment(lib, "comdlg32.lib")
  41329. #pragma comment(lib, "winmm.lib")
  41330. #pragma comment(lib, "wininet.lib")
  41331. #pragma comment(lib, "ole32.lib")
  41332. #pragma comment(lib, "advapi32.lib")
  41333. #pragma comment(lib, "ws2_32.lib")
  41334. #pragma comment(lib, "comsupp.lib")
  41335. #pragma comment(lib, "version.lib")
  41336. #if JUCE_OPENGL
  41337. #pragma comment(lib, "OpenGL32.Lib")
  41338. #pragma comment(lib, "GlU32.Lib")
  41339. #endif
  41340. #if JUCE_QUICKTIME
  41341. #pragma comment (lib, "QTMLClient.lib")
  41342. #endif
  41343. #if JUCE_USE_CAMERA
  41344. #pragma comment (lib, "Strmiids.lib")
  41345. #endif
  41346. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  41347. #endif
  41348. #endif
  41349. #endif
  41350. /*
  41351. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  41352. AppSubClass is the name of a class derived from JUCEApplication.
  41353. See the JUCEApplication class documentation (juce_Application.h) for more details.
  41354. */
  41355. #if defined (JUCE_GCC) || defined (__MWERKS__)
  41356. #define START_JUCE_APPLICATION(AppClass) \
  41357. int main (int argc, char* argv[]) \
  41358. { \
  41359. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  41360. }
  41361. #elif JUCE_WIN32
  41362. #ifdef _CONSOLE
  41363. #define START_JUCE_APPLICATION(AppClass) \
  41364. int main (int, char* argv[]) \
  41365. { \
  41366. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41367. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41368. }
  41369. #elif ! defined (_AFXDLL)
  41370. #ifdef _WINDOWS_
  41371. #define START_JUCE_APPLICATION(AppClass) \
  41372. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  41373. { \
  41374. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41375. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41376. }
  41377. #else
  41378. #define START_JUCE_APPLICATION(AppClass) \
  41379. int __stdcall WinMain (int, int, const char*, int) \
  41380. { \
  41381. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41382. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41383. }
  41384. #endif
  41385. #endif
  41386. #endif
  41387. #endif // __JUCE_JUCEHEADER__
  41388. /********* End of inlined file: juce.h *********/
  41389. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__