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.

55144 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 units for the timestamp will be application-specific.
  18897. @see setTimeStamp, addToTimeStamp
  18898. */
  18899. double getTimeStamp() const throw() { return timeStamp; }
  18900. /** Changes the message's associated timestamp.
  18901. The units for the timestamp will be application-specific.
  18902. @see addToTimeStamp, getTimeStamp
  18903. */
  18904. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  18905. /** Adds a value to the message's timestamp.
  18906. The units for the timestamp will be application-specific.
  18907. */
  18908. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  18909. /** Returns the midi channel associated with the message.
  18910. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  18911. if it's a sysex)
  18912. @see isForChannel, setChannel
  18913. */
  18914. int getChannel() const throw();
  18915. /** Returns true if the message applies to the given midi channel.
  18916. @param channelNumber the channel number to look for, in the range 1 to 16
  18917. @see getChannel, setChannel
  18918. */
  18919. bool isForChannel (const int channelNumber) const throw();
  18920. /** Changes the message's midi channel.
  18921. This won't do anything for non-channel messages like sysexes.
  18922. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  18923. */
  18924. void setChannel (const int newChannelNumber) throw();
  18925. /** Returns true if this is a system-exclusive message.
  18926. */
  18927. bool isSysEx() const throw();
  18928. /** Returns a pointer to the sysex data inside the message.
  18929. If this event isn't a sysex event, it'll return 0.
  18930. @see getSysExDataSize
  18931. */
  18932. const uint8* getSysExData() const throw();
  18933. /** Returns the size of the sysex data.
  18934. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  18935. @see getSysExData
  18936. */
  18937. int getSysExDataSize() const throw();
  18938. /** Returns true if this message is a 'key-down' event.
  18939. This will return false for a note-on event with a velocity of 0.
  18940. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  18941. */
  18942. bool isNoteOn() const throw();
  18943. /** Creates a key-down message (using a floating-point velocity).
  18944. @param channel the midi channel, in the range 1 to 16
  18945. @param noteNumber the key number, 0 to 127
  18946. @param velocity in the range 0 to 1.0
  18947. @see isNoteOn
  18948. */
  18949. static const MidiMessage noteOn (const int channel,
  18950. const int noteNumber,
  18951. const float velocity) throw();
  18952. /** Creates a key-down message (using an integer velocity).
  18953. @param channel the midi channel, in the range 1 to 16
  18954. @param noteNumber the key number, 0 to 127
  18955. @param velocity in the range 0 to 127
  18956. @see isNoteOn
  18957. */
  18958. static const MidiMessage noteOn (const int channel,
  18959. const int noteNumber,
  18960. const uint8 velocity) throw();
  18961. /** Returns true if this message is a 'key-up' event.
  18962. This will also return true for a note-on event with a velocity of 0.
  18963. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  18964. */
  18965. bool isNoteOff() const throw();
  18966. /** Creates a key-up message.
  18967. @param channel the midi channel, in the range 1 to 16
  18968. @param noteNumber the key number, 0 to 127
  18969. @see isNoteOff
  18970. */
  18971. static const MidiMessage noteOff (const int channel,
  18972. const int noteNumber) throw();
  18973. /** Returns true if this message is a 'key-down' or 'key-up' event.
  18974. @see isNoteOn, isNoteOff
  18975. */
  18976. bool isNoteOnOrOff() const throw();
  18977. /** Returns the midi note number for note-on and note-off messages.
  18978. If the message isn't a note-on or off, the value returned will be
  18979. meaningless.
  18980. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  18981. */
  18982. int getNoteNumber() const throw();
  18983. /** Changes the midi note number of a note-on or note-off message.
  18984. If the message isn't a note on or off, this will do nothing.
  18985. */
  18986. void setNoteNumber (const int newNoteNumber) throw();
  18987. /** Returns the velocity of a note-on or note-off message.
  18988. The value returned will be in the range 0 to 127.
  18989. If the message isn't a note-on or off event, it will return 0.
  18990. @see getFloatVelocity
  18991. */
  18992. uint8 getVelocity() const throw();
  18993. /** Returns the velocity of a note-on or note-off message.
  18994. The value returned will be in the range 0 to 1.0
  18995. If the message isn't a note-on or off event, it will return 0.
  18996. @see getVelocity, setVelocity
  18997. */
  18998. float getFloatVelocity() const throw();
  18999. /** Changes the velocity of a note-on or note-off message.
  19000. If the message isn't a note on or off, this will do nothing.
  19001. @param newVelocity the new velocity, in the range 0 to 1.0
  19002. @see getFloatVelocity, multiplyVelocity
  19003. */
  19004. void setVelocity (const float newVelocity) throw();
  19005. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  19006. If the message isn't a note on or off, this will do nothing.
  19007. @param scaleFactor the value by which to multiply the velocity
  19008. @see setVelocity
  19009. */
  19010. void multiplyVelocity (const float scaleFactor) throw();
  19011. /** Returns true if the message is a program (patch) change message.
  19012. @see getProgramChangeNumber, getGMInstrumentName
  19013. */
  19014. bool isProgramChange() const throw();
  19015. /** Returns the new program number of a program change message.
  19016. If the message isn't a program change, the value returned will be
  19017. nonsense.
  19018. @see isProgramChange, getGMInstrumentName
  19019. */
  19020. int getProgramChangeNumber() const throw();
  19021. /** Creates a program-change message.
  19022. @param channel the midi channel, in the range 1 to 16
  19023. @param programNumber the midi program number, 0 to 127
  19024. @see isProgramChange, getGMInstrumentName
  19025. */
  19026. static const MidiMessage programChange (const int channel,
  19027. const int programNumber) throw();
  19028. /** Returns true if the message is a pitch-wheel move.
  19029. @see getPitchWheelValue, pitchWheel
  19030. */
  19031. bool isPitchWheel() const throw();
  19032. /** Returns the pitch wheel position from a pitch-wheel move message.
  19033. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  19034. If called for messages which aren't pitch wheel events, the number returned will be
  19035. nonsense.
  19036. @see isPitchWheel
  19037. */
  19038. int getPitchWheelValue() const throw();
  19039. /** Creates a pitch-wheel move message.
  19040. @param channel the midi channel, in the range 1 to 16
  19041. @param position the wheel position, in the range 0 to 16383
  19042. @see isPitchWheel
  19043. */
  19044. static const MidiMessage pitchWheel (const int channel,
  19045. const int position) throw();
  19046. /** Returns true if the message is an aftertouch event.
  19047. For aftertouch events, use the getNoteNumber() method to find out the key
  19048. that it applies to, and getAftertouchValue() to find out the amount. Use
  19049. getChannel() to find out the channel.
  19050. @see getAftertouchValue, getNoteNumber
  19051. */
  19052. bool isAftertouch() const throw();
  19053. /** Returns the amount of aftertouch from an aftertouch messages.
  19054. The value returned is in the range 0 to 127, and will be nonsense for messages
  19055. other than aftertouch messages.
  19056. @see isAftertouch
  19057. */
  19058. int getAfterTouchValue() const throw();
  19059. /** Creates an aftertouch message.
  19060. @param channel the midi channel, in the range 1 to 16
  19061. @param noteNumber the key number, 0 to 127
  19062. @param aftertouchAmount the amount of aftertouch, 0 to 127
  19063. @see isAftertouch
  19064. */
  19065. static const MidiMessage aftertouchChange (const int channel,
  19066. const int noteNumber,
  19067. const int aftertouchAmount) throw();
  19068. /** Returns true if the message is a channel-pressure change event.
  19069. This is like aftertouch, but common to the whole channel rather than a specific
  19070. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  19071. to find out the channel.
  19072. @see channelPressureChange
  19073. */
  19074. bool isChannelPressure() const throw();
  19075. /** Returns the pressure from a channel pressure change message.
  19076. @returns the pressure, in the range 0 to 127
  19077. @see isChannelPressure, channelPressureChange
  19078. */
  19079. int getChannelPressureValue() const throw();
  19080. /** Creates a channel-pressure change event.
  19081. @param channel the midi channel: 1 to 16
  19082. @param pressure the pressure, 0 to 127
  19083. @see isChannelPressure
  19084. */
  19085. static const MidiMessage channelPressureChange (const int channel,
  19086. const int pressure) throw();
  19087. /** Returns true if this is a midi controller message.
  19088. @see getControllerNumber, getControllerValue, controllerEvent
  19089. */
  19090. bool isController() const throw();
  19091. /** Returns the controller number of a controller message.
  19092. The name of the controller can be looked up using the getControllerName() method.
  19093. Note that the value returned is invalid for messages that aren't controller changes.
  19094. @see isController, getControllerName, getControllerValue
  19095. */
  19096. int getControllerNumber() const throw();
  19097. /** Returns the controller value from a controller message.
  19098. A value 0 to 127 is returned to indicate the new controller position.
  19099. Note that the value returned is invalid for messages that aren't controller changes.
  19100. @see isController, getControllerNumber
  19101. */
  19102. int getControllerValue() const throw();
  19103. /** Creates a controller message.
  19104. @param channel the midi channel, in the range 1 to 16
  19105. @param controllerType the type of controller
  19106. @param value the controller value
  19107. @see isController
  19108. */
  19109. static const MidiMessage controllerEvent (const int channel,
  19110. const int controllerType,
  19111. const int value) throw();
  19112. /** Checks whether this message is an all-notes-off message.
  19113. @see allNotesOff
  19114. */
  19115. bool isAllNotesOff() const throw();
  19116. /** Checks whether this message is an all-sound-off message.
  19117. @see allSoundOff
  19118. */
  19119. bool isAllSoundOff() const throw();
  19120. /** Creates an all-notes-off message.
  19121. @param channel the midi channel, in the range 1 to 16
  19122. @see isAllNotesOff
  19123. */
  19124. static const MidiMessage allNotesOff (const int channel) throw();
  19125. /** Creates an all-sound-off message.
  19126. @param channel the midi channel, in the range 1 to 16
  19127. @see isAllSoundOff
  19128. */
  19129. static const MidiMessage allSoundOff (const int channel) throw();
  19130. /** Creates an all-controllers-off message.
  19131. @param channel the midi channel, in the range 1 to 16
  19132. */
  19133. static const MidiMessage allControllersOff (const int channel) throw();
  19134. /** Returns true if this event is a meta-event.
  19135. Meta-events are things like tempo changes, track names, etc.
  19136. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  19137. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  19138. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  19139. */
  19140. bool isMetaEvent() const throw();
  19141. /** Returns a meta-event's type number.
  19142. If the message isn't a meta-event, this will return -1.
  19143. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  19144. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  19145. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  19146. */
  19147. int getMetaEventType() const throw();
  19148. /** Returns a pointer to the data in a meta-event.
  19149. @see isMetaEvent, getMetaEventLength
  19150. */
  19151. const uint8* getMetaEventData() const throw();
  19152. /** Returns the length of the data for a meta-event.
  19153. @see isMetaEvent, getMetaEventData
  19154. */
  19155. int getMetaEventLength() const throw();
  19156. /** Returns true if this is a 'track' meta-event. */
  19157. bool isTrackMetaEvent() const throw();
  19158. /** Returns true if this is an 'end-of-track' meta-event. */
  19159. bool isEndOfTrackMetaEvent() const throw();
  19160. /** Creates an end-of-track meta-event.
  19161. @see isEndOfTrackMetaEvent
  19162. */
  19163. static const MidiMessage endOfTrack() throw();
  19164. /** Returns true if this is an 'track name' meta-event.
  19165. You can use the getTextFromTextMetaEvent() method to get the track's name.
  19166. */
  19167. bool isTrackNameEvent() const throw();
  19168. /** Returns true if this is a 'text' meta-event.
  19169. @see getTextFromTextMetaEvent
  19170. */
  19171. bool isTextMetaEvent() const throw();
  19172. /** Returns the text from a text meta-event.
  19173. @see isTextMetaEvent
  19174. */
  19175. const String getTextFromTextMetaEvent() const throw();
  19176. /** Returns true if this is a 'tempo' meta-event.
  19177. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  19178. */
  19179. bool isTempoMetaEvent() const throw();
  19180. /** Returns the tick length from a tempo meta-event.
  19181. @param timeFormat the 16-bit time format value from the midi file's header.
  19182. @returns the tick length (in seconds).
  19183. @see isTempoMetaEvent
  19184. */
  19185. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  19186. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  19187. @see isTempoMetaEvent, getTempoMetaEventTickLength
  19188. */
  19189. double getTempoSecondsPerQuarterNote() const throw();
  19190. /** Creates a tempo meta-event.
  19191. @see isTempoMetaEvent
  19192. */
  19193. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  19194. /** Returns true if this is a 'time-signature' meta-event.
  19195. @see getTimeSignatureInfo
  19196. */
  19197. bool isTimeSignatureMetaEvent() const throw();
  19198. /** Returns the time-signature values from a time-signature meta-event.
  19199. @see isTimeSignatureMetaEvent
  19200. */
  19201. void getTimeSignatureInfo (int& numerator,
  19202. int& denominator) const throw();
  19203. /** Creates a time-signature meta-event.
  19204. @see isTimeSignatureMetaEvent
  19205. */
  19206. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  19207. const int denominator) throw();
  19208. /** Returns true if this is a 'key-signature' meta-event.
  19209. @see getKeySignatureNumberOfSharpsOrFlats
  19210. */
  19211. bool isKeySignatureMetaEvent() const throw();
  19212. /** Returns the key from a key-signature meta-event.
  19213. @see isKeySignatureMetaEvent
  19214. */
  19215. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  19216. /** Returns true if this is a 'channel' meta-event.
  19217. A channel meta-event specifies the midi channel that should be used
  19218. for subsequent meta-events.
  19219. @see getMidiChannelMetaEventChannel
  19220. */
  19221. bool isMidiChannelMetaEvent() const throw();
  19222. /** Returns the channel number from a channel meta-event.
  19223. @returns the channel, in the range 1 to 16.
  19224. @see isMidiChannelMetaEvent
  19225. */
  19226. int getMidiChannelMetaEventChannel() const throw();
  19227. /** Creates a midi channel meta-event.
  19228. @param channel the midi channel, in the range 1 to 16
  19229. @see isMidiChannelMetaEvent
  19230. */
  19231. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  19232. /** Returns true if this is an active-sense message. */
  19233. bool isActiveSense() const throw();
  19234. /** Returns true if this is a midi start event.
  19235. @see midiStart
  19236. */
  19237. bool isMidiStart() const throw();
  19238. /** Creates a midi start event. */
  19239. static const MidiMessage midiStart() throw();
  19240. /** Returns true if this is a midi continue event.
  19241. @see midiContinue
  19242. */
  19243. bool isMidiContinue() const throw();
  19244. /** Creates a midi continue event. */
  19245. static const MidiMessage midiContinue() throw();
  19246. /** Returns true if this is a midi stop event.
  19247. @see midiStop
  19248. */
  19249. bool isMidiStop() const throw();
  19250. /** Creates a midi stop event. */
  19251. static const MidiMessage midiStop() throw();
  19252. /** Returns true if this is a midi clock event.
  19253. @see midiClock, songPositionPointer
  19254. */
  19255. bool isMidiClock() const throw();
  19256. /** Creates a midi clock event. */
  19257. static const MidiMessage midiClock() throw();
  19258. /** Returns true if this is a song-position-pointer message.
  19259. @see getSongPositionPointerMidiBeat, songPositionPointer
  19260. */
  19261. bool isSongPositionPointer() const throw();
  19262. /** Returns the midi beat-number of a song-position-pointer message.
  19263. @see isSongPositionPointer, songPositionPointer
  19264. */
  19265. int getSongPositionPointerMidiBeat() const throw();
  19266. /** Creates a song-position-pointer message.
  19267. The position is a number of midi beats from the start of the song, where 1 midi
  19268. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  19269. are 4 midi beats in a quarter-note.
  19270. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  19271. */
  19272. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  19273. /** Returns true if this is a quarter-frame midi timecode message.
  19274. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  19275. */
  19276. bool isQuarterFrame() const throw();
  19277. /** Returns the sequence number of a quarter-frame midi timecode message.
  19278. This will be a value between 0 and 7.
  19279. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  19280. */
  19281. int getQuarterFrameSequenceNumber() const throw();
  19282. /** Returns the value from a quarter-frame message.
  19283. This will be the lower nybble of the message's data-byte, a value
  19284. between 0 and 15
  19285. */
  19286. int getQuarterFrameValue() const throw();
  19287. /** Creates a quarter-frame MTC message.
  19288. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  19289. @param value a value 0 to 15 for the lower nybble of the message's data byte
  19290. */
  19291. static const MidiMessage quarterFrame (const int sequenceNumber,
  19292. const int value) throw();
  19293. /** SMPTE timecode types.
  19294. Used by the getFullFrameParameters() and fullFrame() methods.
  19295. */
  19296. enum SmpteTimecodeType
  19297. {
  19298. fps24 = 0,
  19299. fps25 = 1,
  19300. fps30drop = 2,
  19301. fps30 = 3
  19302. };
  19303. /** Returns true if this is a full-frame midi timecode message.
  19304. */
  19305. bool isFullFrame() const throw();
  19306. /** Extracts the timecode information from a full-frame midi timecode message.
  19307. You should only call this on messages where you've used isFullFrame() to
  19308. check that they're the right kind.
  19309. */
  19310. void getFullFrameParameters (int& hours,
  19311. int& minutes,
  19312. int& seconds,
  19313. int& frames,
  19314. SmpteTimecodeType& timecodeType) const throw();
  19315. /** Creates a full-frame MTC message.
  19316. */
  19317. static const MidiMessage fullFrame (const int hours,
  19318. const int minutes,
  19319. const int seconds,
  19320. const int frames,
  19321. SmpteTimecodeType timecodeType);
  19322. /** Types of MMC command.
  19323. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  19324. */
  19325. enum MidiMachineControlCommand
  19326. {
  19327. mmc_stop = 1,
  19328. mmc_play = 2,
  19329. mmc_deferredplay = 3,
  19330. mmc_fastforward = 4,
  19331. mmc_rewind = 5,
  19332. mmc_recordStart = 6,
  19333. mmc_recordStop = 7,
  19334. mmc_pause = 9
  19335. };
  19336. /** Checks whether this is an MMC message.
  19337. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  19338. */
  19339. bool isMidiMachineControlMessage() const throw();
  19340. /** For an MMC message, this returns its type.
  19341. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  19342. calling this method.
  19343. */
  19344. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  19345. /** Creates an MMC message.
  19346. */
  19347. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  19348. /** Checks whether this is an MMC "goto" message.
  19349. If it is, the parameters passed-in are set to the time that the message contains.
  19350. @see midiMachineControlGoto
  19351. */
  19352. bool isMidiMachineControlGoto (int& hours,
  19353. int& minutes,
  19354. int& seconds,
  19355. int& frames) const throw();
  19356. /** Creates an MMC "goto" message.
  19357. This messages tells the device to go to a specific frame.
  19358. @see isMidiMachineControlGoto
  19359. */
  19360. static const MidiMessage midiMachineControlGoto (int hours,
  19361. int minutes,
  19362. int seconds,
  19363. int frames);
  19364. /** Creates a master-volume change message.
  19365. @param volume the volume, 0 to 1.0
  19366. */
  19367. static const MidiMessage masterVolume (const float volume) throw();
  19368. /** Creates a system-exclusive message.
  19369. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  19370. */
  19371. static const MidiMessage createSysExMessage (const uint8* sysexData,
  19372. const int dataSize) throw();
  19373. /** Reads a midi variable-length integer.
  19374. @param data the data to read the number from
  19375. @param numBytesUsed on return, this will be set to the number of bytes that were read
  19376. */
  19377. static int readVariableLengthVal (const uint8* data,
  19378. int& numBytesUsed) throw();
  19379. /** Based on the first byte of a short midi message, this uses a lookup table
  19380. to return the message length (either 1, 2, or 3 bytes).
  19381. The value passed in must be 0x80 or higher.
  19382. */
  19383. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  19384. /** Returns the name of a midi note number.
  19385. E.g "C", "D#", etc.
  19386. @param noteNumber the midi note number, 0 to 127
  19387. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  19388. they'll be flattened, e.g. "Db"
  19389. @param includeOctaveNumber if true, the octave number will be appended to the string,
  19390. e.g. "C#4"
  19391. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  19392. number that will be used for middle C's octave
  19393. @see getMidiNoteInHertz
  19394. */
  19395. static const String getMidiNoteName (int noteNumber,
  19396. bool useSharps,
  19397. bool includeOctaveNumber,
  19398. int octaveNumForMiddleC) throw();
  19399. /** Returns the frequency of a midi note number.
  19400. @see getMidiNoteName
  19401. */
  19402. static const double getMidiNoteInHertz (int noteNumber) throw();
  19403. /** Returns the standard name of a GM instrument.
  19404. @param midiInstrumentNumber the program number 0 to 127
  19405. @see getProgramChangeNumber
  19406. */
  19407. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  19408. /** Returns the name of a bank of GM instruments.
  19409. @param midiBankNumber the bank, 0 to 15
  19410. */
  19411. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  19412. /** Returns the standard name of a channel 10 percussion sound.
  19413. @param midiNoteNumber the key number, 35 to 81
  19414. */
  19415. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  19416. /** Returns the name of a controller type number.
  19417. @see getControllerNumber
  19418. */
  19419. static const String getControllerName (int controllerNumber) throw();
  19420. juce_UseDebuggingNewOperator
  19421. private:
  19422. double timeStamp;
  19423. uint8* data;
  19424. int message, size;
  19425. };
  19426. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  19427. /********* End of inlined file: juce_MidiMessage.h *********/
  19428. /**
  19429. Holds a sequence of time-stamped midi events.
  19430. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  19431. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  19432. @see MidiMessage
  19433. */
  19434. class JUCE_API MidiBuffer : private ArrayAllocationBase <uint8>
  19435. {
  19436. public:
  19437. /** Creates an empty MidiBuffer. */
  19438. MidiBuffer() throw();
  19439. /** Creates a MidiBuffer containing a single midi message. */
  19440. MidiBuffer (const MidiMessage& message) throw();
  19441. /** Creates a copy of another MidiBuffer. */
  19442. MidiBuffer (const MidiBuffer& other) throw();
  19443. /** Makes a copy of another MidiBuffer. */
  19444. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  19445. /** Destructor */
  19446. ~MidiBuffer() throw();
  19447. /** Removes all events from the buffer. */
  19448. void clear() throw();
  19449. /** Removes all events between two times from the buffer.
  19450. All events for which (start <= event position < start + numSamples) will
  19451. be removed.
  19452. */
  19453. void clear (const int start,
  19454. const int numSamples) throw();
  19455. /** Returns true if the buffer is empty.
  19456. To actually retrieve the events, use a MidiBuffer::Iterator object
  19457. */
  19458. bool isEmpty() const throw();
  19459. /** Counts the number of events in the buffer.
  19460. This is actually quite a slow operation, as it has to iterate through all
  19461. the events, so you might prefer to call isEmpty() if that's all you need
  19462. to know.
  19463. */
  19464. int getNumEvents() const throw();
  19465. /** Adds an event to the buffer.
  19466. The sample number will be used to determine the position of the event in
  19467. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  19468. ignored.
  19469. If an event is added whose sample position is the same as one or more events
  19470. already in the buffer, the new event will be placed after the existing ones.
  19471. To retrieve events, use a MidiBuffer::Iterator object
  19472. */
  19473. void addEvent (const MidiMessage& midiMessage,
  19474. const int sampleNumber) throw();
  19475. /** Adds an event to the buffer from raw midi data.
  19476. The sample number will be used to determine the position of the event in
  19477. the buffer, which is always kept sorted.
  19478. If an event is added whose sample position is the same as one or more events
  19479. already in the buffer, the new event will be placed after the existing ones.
  19480. The event data will be inspected to calculate the number of bytes in length that
  19481. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  19482. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  19483. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  19484. add an event at all.
  19485. To retrieve events, use a MidiBuffer::Iterator object
  19486. */
  19487. void addEvent (const uint8* const rawMidiData,
  19488. const int maxBytesOfMidiData,
  19489. const int sampleNumber) throw();
  19490. /** Adds some events from another buffer to this one.
  19491. @param otherBuffer the buffer containing the events you want to add
  19492. @param startSample the lowest sample number in the source buffer for which
  19493. events should be added. Any source events whose timestamp is
  19494. less than this will be ignored
  19495. @param numSamples the valid range of samples from the source buffer for which
  19496. events should be added - i.e. events in the source buffer whose
  19497. timestamp is greater than or equal to (startSample + numSamples)
  19498. will be ignored. If this value is less than 0, all events after
  19499. startSample will be taken.
  19500. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  19501. that are added to this buffer
  19502. */
  19503. void addEvents (const MidiBuffer& otherBuffer,
  19504. const int startSample,
  19505. const int numSamples,
  19506. const int sampleDeltaToAdd) throw();
  19507. /** Returns the sample number of the first event in the buffer.
  19508. If the buffer's empty, this will just return 0.
  19509. */
  19510. int getFirstEventTime() const throw();
  19511. /** Returns the sample number of the last event in the buffer.
  19512. If the buffer's empty, this will just return 0.
  19513. */
  19514. int getLastEventTime() const throw();
  19515. /** Exchanges the contents of this buffer with another one.
  19516. This is a quick operation, because no memory allocating or copying is done, it
  19517. just swaps the internal state of the two buffers.
  19518. */
  19519. void swap (MidiBuffer& other);
  19520. /**
  19521. Used to iterate through the events in a MidiBuffer.
  19522. Note that altering the buffer while an iterator is using it isn't a
  19523. safe operation.
  19524. @see MidiBuffer
  19525. */
  19526. class Iterator
  19527. {
  19528. public:
  19529. /** Creates an Iterator for this MidiBuffer. */
  19530. Iterator (const MidiBuffer& buffer) throw();
  19531. /** Destructor. */
  19532. ~Iterator() throw();
  19533. /** Repositions the iterator so that the next event retrieved will be the first
  19534. one whose sample position is at greater than or equal to the given position.
  19535. */
  19536. void setNextSamplePosition (const int samplePosition) throw();
  19537. /** Retrieves a copy of the next event from the buffer.
  19538. @param result on return, this will be the message (the MidiMessage's timestamp
  19539. is not set)
  19540. @param samplePosition on return, this will be the position of the event
  19541. @returns true if an event was found, or false if the iterator has reached
  19542. the end of the buffer
  19543. */
  19544. bool getNextEvent (MidiMessage& result,
  19545. int& samplePosition) throw();
  19546. /** Retrieves the next event from the buffer.
  19547. @param midiData on return, this pointer will be set to a block of data containing
  19548. the midi message. Note that to make it fast, this is a pointer
  19549. directly into the MidiBuffer's internal data, so is only valid
  19550. temporarily until the MidiBuffer is altered.
  19551. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  19552. midi message
  19553. @param samplePosition on return, this will be the position of the event
  19554. @returns true if an event was found, or false if the iterator has reached
  19555. the end of the buffer
  19556. */
  19557. bool getNextEvent (const uint8* &midiData,
  19558. int& numBytesOfMidiData,
  19559. int& samplePosition) throw();
  19560. juce_UseDebuggingNewOperator
  19561. private:
  19562. const MidiBuffer& buffer;
  19563. const uint8* data;
  19564. Iterator (const Iterator&);
  19565. const Iterator& operator= (const Iterator&);
  19566. };
  19567. juce_UseDebuggingNewOperator
  19568. private:
  19569. friend class MidiBuffer::Iterator;
  19570. int bytesUsed;
  19571. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  19572. };
  19573. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  19574. /********* End of inlined file: juce_MidiBuffer.h *********/
  19575. #endif
  19576. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19577. /********* Start of inlined file: juce_MidiFile.h *********/
  19578. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  19579. #define __JUCE_MIDIFILE_JUCEHEADER__
  19580. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  19581. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19582. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19583. /**
  19584. A sequence of timestamped midi messages.
  19585. This allows the sequence to be manipulated, and also to be read from and
  19586. written to a standard midi file.
  19587. @see MidiMessage, MidiFile
  19588. */
  19589. class JUCE_API MidiMessageSequence
  19590. {
  19591. public:
  19592. /** Creates an empty midi sequence object. */
  19593. MidiMessageSequence();
  19594. /** Creates a copy of another sequence. */
  19595. MidiMessageSequence (const MidiMessageSequence& other);
  19596. /** Replaces this sequence with another one. */
  19597. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  19598. /** Destructor. */
  19599. ~MidiMessageSequence();
  19600. /** Structure used to hold midi events in the sequence.
  19601. These structures act as 'handles' on the events as they are moved about in
  19602. the list, and make it quick to find the matching note-offs for note-on events.
  19603. @see MidiMessageSequence::getEventPointer
  19604. */
  19605. class MidiEventHolder
  19606. {
  19607. public:
  19608. /** Destructor. */
  19609. ~MidiEventHolder();
  19610. /** The message itself, whose timestamp is used to specify the event's time.
  19611. */
  19612. MidiMessage message;
  19613. /** The matching note-off event (if this is a note-on event).
  19614. If this isn't a note-on, this pointer will be null.
  19615. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  19616. note-offs up-to-date after events have been moved around in the sequence
  19617. or deleted.
  19618. */
  19619. MidiEventHolder* noteOffObject;
  19620. juce_UseDebuggingNewOperator
  19621. private:
  19622. friend class MidiMessageSequence;
  19623. MidiEventHolder (const MidiMessage& message);
  19624. };
  19625. /** Clears the sequence. */
  19626. void clear();
  19627. /** Returns the number of events in the sequence. */
  19628. int getNumEvents() const;
  19629. /** Returns a pointer to one of the events. */
  19630. MidiEventHolder* getEventPointer (const int index) const;
  19631. /** Returns the time of the note-up that matches the note-on at this index.
  19632. If the event at this index isn't a note-on, it'll just return 0.
  19633. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19634. */
  19635. double getTimeOfMatchingKeyUp (const int index) const;
  19636. /** Returns the index of the note-up that matches the note-on at this index.
  19637. If the event at this index isn't a note-on, it'll just return -1.
  19638. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  19639. */
  19640. int getIndexOfMatchingKeyUp (const int index) const;
  19641. /** Returns the index of an event. */
  19642. int getIndexOf (MidiEventHolder* const event) const;
  19643. /** Returns the index of the first event on or after the given timestamp.
  19644. If the time is beyond the end of the sequence, this will return the
  19645. number of events.
  19646. */
  19647. int getNextIndexAtTime (const double timeStamp) const;
  19648. /** Returns the timestamp of the first event in the sequence.
  19649. @see getEndTime
  19650. */
  19651. double getStartTime() const;
  19652. /** Returns the timestamp of the last event in the sequence.
  19653. @see getStartTime
  19654. */
  19655. double getEndTime() const;
  19656. /** Returns the timestamp of the event at a given index.
  19657. If the index is out-of-range, this will return 0.0
  19658. */
  19659. double getEventTime (const int index) const;
  19660. /** Inserts a midi message into the sequence.
  19661. The index at which the new message gets inserted will depend on its timestamp,
  19662. because the sequence is kept sorted.
  19663. Remember to call updateMatchedPairs() after adding note-on events.
  19664. @param newMessage the new message to add (an internal copy will be made)
  19665. @param timeAdjustment an optional value to add to the timestamp of the message
  19666. that will be inserted
  19667. @see updateMatchedPairs
  19668. */
  19669. void addEvent (const MidiMessage& newMessage,
  19670. double timeAdjustment = 0);
  19671. /** Deletes one of the events in the sequence.
  19672. Remember to call updateMatchedPairs() after removing events.
  19673. @param index the index of the event to delete
  19674. @param deleteMatchingNoteUp whether to also remove the matching note-off
  19675. if the event you're removing is a note-on
  19676. */
  19677. void deleteEvent (const int index,
  19678. const bool deleteMatchingNoteUp);
  19679. /** Merges another sequence into this one.
  19680. Remember to call updateMatchedPairs() after using this method.
  19681. @param other the sequence to add from
  19682. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  19683. as they are read from the other sequence
  19684. @param firstAllowableDestTime events will not be added if their time is earlier
  19685. than this time. (This is after their time has been adjusted
  19686. by the timeAdjustmentDelta)
  19687. @param endOfAllowableDestTimes events will not be added if their time is equal to
  19688. or greater than this time. (This is after their time has
  19689. been adjusted by the timeAdjustmentDelta)
  19690. */
  19691. void addSequence (const MidiMessageSequence& other,
  19692. double timeAdjustmentDelta,
  19693. double firstAllowableDestTime,
  19694. double endOfAllowableDestTimes);
  19695. /** Makes sure all the note-on and note-off pairs are up-to-date.
  19696. Call this after moving messages about or deleting/adding messages, and it
  19697. will scan the list and make sure all the note-offs in the MidiEventHolder
  19698. structures are pointing at the correct ones.
  19699. */
  19700. void updateMatchedPairs();
  19701. /** Copies all the messages for a particular midi channel to another sequence.
  19702. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  19703. @param destSequence the sequence that the chosen events should be copied to
  19704. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  19705. channel) will also be copied across.
  19706. @see extractSysExMessages
  19707. */
  19708. void extractMidiChannelMessages (const int channelNumberToExtract,
  19709. MidiMessageSequence& destSequence,
  19710. const bool alsoIncludeMetaEvents) const;
  19711. /** Copies all midi sys-ex messages to another sequence.
  19712. @param destSequence this is the sequence to which any sys-exes in this sequence
  19713. will be added
  19714. @see extractMidiChannelMessages
  19715. */
  19716. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  19717. /** Removes any messages in this sequence that have a specific midi channel.
  19718. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  19719. */
  19720. void deleteMidiChannelMessages (const int channelNumberToRemove);
  19721. /** Removes any sys-ex messages from this sequence.
  19722. */
  19723. void deleteSysExMessages();
  19724. /** Adds an offset to the timestamps of all events in the sequence.
  19725. @param deltaTime the amount to add to each timestamp.
  19726. */
  19727. void addTimeToMessages (const double deltaTime);
  19728. /** Scans through the sequence to determine the state of any midi controllers at
  19729. a given time.
  19730. This will create a sequence of midi controller changes that can be
  19731. used to set all midi controllers to the state they would be in at the
  19732. specified time within this sequence.
  19733. As well as controllers, it will also recreate the midi program number
  19734. and pitch bend position.
  19735. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  19736. for other channels will be ignored.
  19737. @param time the time at which you want to find out the state - there are
  19738. no explicit units for this time measurement, it's the same units
  19739. as used for the timestamps of the messages
  19740. @param resultMessages an array to which midi controller-change messages will be added. This
  19741. will be the minimum number of controller changes to recreate the
  19742. state at the required time.
  19743. */
  19744. void createControllerUpdatesForTime (const int channelNumber,
  19745. const double time,
  19746. OwnedArray<MidiMessage>& resultMessages);
  19747. juce_UseDebuggingNewOperator
  19748. /** @internal */
  19749. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19750. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19751. private:
  19752. friend class MidiComparator;
  19753. friend class MidiFile;
  19754. OwnedArray <MidiEventHolder> list;
  19755. void sort();
  19756. };
  19757. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  19758. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  19759. /**
  19760. Reads/writes standard midi format files.
  19761. To read a midi file, create a MidiFile object and call its readFrom() method. You
  19762. can then get the individual midi tracks from it using the getTrack() method.
  19763. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  19764. to it using the addTrack() method, and then call its writeTo() method to stream
  19765. it out.
  19766. @see MidiMessageSequence
  19767. */
  19768. class JUCE_API MidiFile
  19769. {
  19770. public:
  19771. /** Creates an empty MidiFile object.
  19772. */
  19773. MidiFile() throw();
  19774. /** Destructor. */
  19775. ~MidiFile() throw();
  19776. /** Returns the number of tracks in the file.
  19777. @see getTrack, addTrack
  19778. */
  19779. int getNumTracks() const throw();
  19780. /** Returns a pointer to one of the tracks in the file.
  19781. @returns a pointer to the track, or 0 if the index is out-of-range
  19782. @see getNumTracks, addTrack
  19783. */
  19784. const MidiMessageSequence* getTrack (const int index) const throw();
  19785. /** Adds a midi track to the file.
  19786. This will make its own internal copy of the sequence that is passed-in.
  19787. @see getNumTracks, getTrack
  19788. */
  19789. void addTrack (const MidiMessageSequence& trackSequence) throw();
  19790. /** Removes all midi tracks from the file.
  19791. @see getNumTracks
  19792. */
  19793. void clear() throw();
  19794. /** Returns the raw time format code that will be written to a stream.
  19795. After reading a midi file, this method will return the time-format that
  19796. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  19797. or setSmpteTimeFormat() methods.
  19798. If the value returned is positive, it indicates the number of midi ticks
  19799. per quarter-note - see setTicksPerQuarterNote().
  19800. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  19801. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  19802. */
  19803. short getTimeFormat() const throw();
  19804. /** Sets the time format to use when this file is written to a stream.
  19805. If this is called, the file will be written as bars/beats using the
  19806. specified resolution, rather than SMPTE absolute times, as would be
  19807. used if setSmpteTimeFormat() had been called instead.
  19808. @param ticksPerQuarterNote e.g. 96, 960
  19809. @see setSmpteTimeFormat
  19810. */
  19811. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  19812. /** Sets the time format to use when this file is written to a stream.
  19813. If this is called, the file will be written using absolute times, rather
  19814. than bars/beats as would be the case if setTicksPerBeat() had been called
  19815. instead.
  19816. @param framesPerSecond must be 24, 25, 29 or 30
  19817. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  19818. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  19819. timing, setSmpteTimeFormat (25, 40)
  19820. @see setTicksPerBeat
  19821. */
  19822. void setSmpteTimeFormat (const int framesPerSecond,
  19823. const int subframeResolution) throw();
  19824. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  19825. Useful for finding the positions of all the tempo changes in a file.
  19826. @param tempoChangeEvents a list to which all the events will be added
  19827. */
  19828. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  19829. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  19830. Useful for finding the positions of all the tempo changes in a file.
  19831. @param timeSigEvents a list to which all the events will be added
  19832. */
  19833. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  19834. /** Returns the latest timestamp in any of the tracks.
  19835. (Useful for finding the length of the file).
  19836. */
  19837. double getLastTimestamp() const;
  19838. /** Reads a midi file format stream.
  19839. After calling this, you can get the tracks that were read from the file by using the
  19840. getNumTracks() and getTrack() methods.
  19841. The timestamps of the midi events in the tracks will represent their positions in
  19842. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  19843. method.
  19844. @returns true if the stream was read successfully
  19845. */
  19846. bool readFrom (InputStream& sourceStream);
  19847. /** Writes the midi tracks as a standard midi file.
  19848. @returns true if the operation succeeded.
  19849. */
  19850. bool writeTo (OutputStream& destStream);
  19851. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  19852. This will use the midi time format and tempo/time signature info in the
  19853. tracks to convert all the timestamps to absolute values in seconds.
  19854. */
  19855. void convertTimestampTicksToSeconds();
  19856. juce_UseDebuggingNewOperator
  19857. /** @internal */
  19858. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19859. const MidiMessageSequence::MidiEventHolder* const second) throw();
  19860. private:
  19861. MidiMessageSequence* tracks [128];
  19862. short numTracks, timeFormat;
  19863. MidiFile (const MidiFile&);
  19864. const MidiFile& operator= (const MidiFile&);
  19865. void readNextTrack (const char* data, int size);
  19866. void writeTrack (OutputStream& mainOut, const int trackNum);
  19867. };
  19868. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  19869. /********* End of inlined file: juce_MidiFile.h *********/
  19870. #endif
  19871. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19872. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  19873. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19874. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19875. class MidiKeyboardState;
  19876. /**
  19877. Receives events from a MidiKeyboardState object.
  19878. @see MidiKeyboardState
  19879. */
  19880. class JUCE_API MidiKeyboardStateListener
  19881. {
  19882. public:
  19883. MidiKeyboardStateListener() throw() {}
  19884. virtual ~MidiKeyboardStateListener() {}
  19885. /** Called when one of the MidiKeyboardState's keys is pressed.
  19886. This will be called synchronously when the state is either processing a
  19887. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19888. when a note is being played with its MidiKeyboardState::noteOn() method.
  19889. Note that this callback could happen from an audio callback thread, so be
  19890. careful not to block, and avoid any UI activity in the callback.
  19891. */
  19892. virtual void handleNoteOn (MidiKeyboardState* source,
  19893. int midiChannel, int midiNoteNumber, float velocity) = 0;
  19894. /** Called when one of the MidiKeyboardState's keys is released.
  19895. This will be called synchronously when the state is either processing a
  19896. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  19897. when a note is being played with its MidiKeyboardState::noteOff() method.
  19898. Note that this callback could happen from an audio callback thread, so be
  19899. careful not to block, and avoid any UI activity in the callback.
  19900. */
  19901. virtual void handleNoteOff (MidiKeyboardState* source,
  19902. int midiChannel, int midiNoteNumber) = 0;
  19903. };
  19904. /**
  19905. Represents a piano keyboard, keeping track of which keys are currently pressed.
  19906. This object can parse a stream of midi events, using them to update its idea
  19907. of which keys are pressed for each individiual midi channel.
  19908. When keys go up or down, it can broadcast these events to listener objects.
  19909. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  19910. methods, and midi messages for these events will be merged into the
  19911. midi stream that gets processed by processNextMidiBuffer().
  19912. */
  19913. class JUCE_API MidiKeyboardState
  19914. {
  19915. public:
  19916. MidiKeyboardState();
  19917. ~MidiKeyboardState();
  19918. /** Resets the state of the object.
  19919. All internal data for all the channels is reset, but no events are sent as a
  19920. result.
  19921. If you want to release any keys that are currently down, and to send out note-up
  19922. midi messages for this, use the allNotesOff() method instead.
  19923. */
  19924. void reset();
  19925. /** Returns true if the given midi key is currently held down for the given midi channel.
  19926. The channel number must be between 1 and 16. If you want to see if any notes are
  19927. on for a range of channels, use the isNoteOnForChannels() method.
  19928. */
  19929. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  19930. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  19931. The channel mask has a bit set for each midi channel you want to test for - bit
  19932. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  19933. If a note is on for at least one of the specified channels, this returns true.
  19934. */
  19935. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  19936. /** Turns a specified note on.
  19937. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  19938. next call to processNextMidiBuffer().
  19939. It will also trigger a synchronous callback to the listeners to tell them that the key has
  19940. gone down.
  19941. */
  19942. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  19943. /** Turns a specified note off.
  19944. This will cause a suitable midi note-off 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 up.
  19948. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  19949. */
  19950. void noteOff (const int midiChannel, const int midiNoteNumber);
  19951. /** This will turn off any currently-down notes for the given midi channel.
  19952. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  19953. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  19954. and events being added to the midi stream.
  19955. */
  19956. void allNotesOff (const int midiChannel);
  19957. /** Looks at a key-up/down event and uses it to update the state of this object.
  19958. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  19959. instead.
  19960. */
  19961. void processNextMidiEvent (const MidiMessage& message);
  19962. /** Scans a midi stream for up/down events and adds its own events to it.
  19963. This will look for any up/down events and use them to update the internal state,
  19964. synchronously making suitable callbacks to the listeners.
  19965. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  19966. and noteOff() calls will be added into the buffer.
  19967. Only the section of the buffer whose timestamps are between startSample and
  19968. (startSample + numSamples) will be affected, and any events added will be placed
  19969. between these times.
  19970. If you're going to use this method, you'll need to keep calling it regularly for
  19971. it to work satisfactorily.
  19972. To process a single midi event at a time, use the processNextMidiEvent() method
  19973. instead.
  19974. */
  19975. void processNextMidiBuffer (MidiBuffer& buffer,
  19976. const int startSample,
  19977. const int numSamples,
  19978. const bool injectIndirectEvents);
  19979. /** Registers a listener for callbacks when keys go up or down.
  19980. @see removeListener
  19981. */
  19982. void addListener (MidiKeyboardStateListener* const listener) throw();
  19983. /** Deregisters a listener.
  19984. @see addListener
  19985. */
  19986. void removeListener (MidiKeyboardStateListener* const listener) throw();
  19987. juce_UseDebuggingNewOperator
  19988. private:
  19989. CriticalSection lock;
  19990. uint16 noteStates [128];
  19991. MidiBuffer eventsToAdd;
  19992. VoidArray listeners;
  19993. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  19994. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  19995. MidiKeyboardState (const MidiKeyboardState&);
  19996. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  19997. };
  19998. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  19999. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  20000. #endif
  20001. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  20002. #endif
  20003. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20004. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  20005. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20006. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20007. /********* Start of inlined file: juce_MidiInput.h *********/
  20008. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  20009. #define __JUCE_MIDIINPUT_JUCEHEADER__
  20010. class MidiInput;
  20011. /**
  20012. Receives midi messages from a midi input device.
  20013. This class is overridden to handle incoming midi messages. See the MidiInput
  20014. class for more details.
  20015. @see MidiInput
  20016. */
  20017. class JUCE_API MidiInputCallback
  20018. {
  20019. public:
  20020. /** Destructor. */
  20021. virtual ~MidiInputCallback() {}
  20022. /** Receives an incoming message.
  20023. A MidiInput object will call this method when a midi event arrives. It'll be
  20024. called on a high-priority system thread, so avoid doing anything time-consuming
  20025. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  20026. for queueing incoming messages for use later.
  20027. @param source the MidiInput object that generated the message
  20028. @param message the incoming message. The message's timestamp is set to a value
  20029. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  20030. time when the message arrived.
  20031. */
  20032. virtual void handleIncomingMidiMessage (MidiInput* source,
  20033. const MidiMessage& message) = 0;
  20034. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  20035. If a long sysex message is broken up into multiple packets, this callback is made
  20036. for each packet that arrives until the message is finished, at which point
  20037. the normal handleIncomingMidiMessage() callback will be made with the entire
  20038. message.
  20039. The message passed in will contain the start of a sysex, but won't be finished
  20040. with the terminating 0xf7 byte.
  20041. */
  20042. virtual void handlePartialSysexMessage (MidiInput* source,
  20043. const uint8* messageData,
  20044. const int numBytesSoFar,
  20045. const double timestamp)
  20046. {
  20047. // (this bit is just to avoid compiler warnings about unused variables)
  20048. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  20049. }
  20050. };
  20051. /**
  20052. Represents a midi input device.
  20053. To create one of these, use the static getDevices() method to find out what inputs are
  20054. available, and then use the openDevice() method to try to open one.
  20055. @see MidiOutput
  20056. */
  20057. class JUCE_API MidiInput
  20058. {
  20059. public:
  20060. /** Returns a list of the available midi input devices.
  20061. You can open one of the devices by passing its index into the
  20062. openDevice() method.
  20063. @see getDefaultDeviceIndex, openDevice
  20064. */
  20065. static const StringArray getDevices();
  20066. /** Returns the index of the default midi input device to use.
  20067. This refers to the index in the list returned by getDevices().
  20068. */
  20069. static int getDefaultDeviceIndex();
  20070. /** Tries to open one of the midi input devices.
  20071. This will return a MidiInput object if it manages to open it. You can then
  20072. call start() and stop() on this device, and delete it when no longer needed.
  20073. If the device can't be opened, this will return a null pointer.
  20074. @param deviceIndex the index of a device from the list returned by getDevices()
  20075. @param callback the object that will receive the midi messages from this device.
  20076. @see MidiInputCallback, getDevices
  20077. */
  20078. static MidiInput* openDevice (int deviceIndex,
  20079. MidiInputCallback* callback);
  20080. #if JUCE_LINUX || DOXYGEN
  20081. /** LINUX ONLY - This will try to create a new midi input device.
  20082. This will attempt to create a new midi input device with the specified name,
  20083. for other apps to connect to.
  20084. Returns 0 if a device can't be created.
  20085. @param deviceName the name to use for the new device
  20086. @param callback the object that will receive the midi messages from this device.
  20087. */
  20088. static MidiInput* createNewDevice (const String& deviceName,
  20089. MidiInputCallback* callback);
  20090. #endif
  20091. /** Destructor. */
  20092. virtual ~MidiInput();
  20093. /** Returns the name of this device.
  20094. */
  20095. virtual const String getName() const throw() { return name; }
  20096. /** Allows you to set a custom name for the device, in case you don't like the name
  20097. it was given when created.
  20098. */
  20099. virtual void setName (const String& newName) throw() { name = newName; }
  20100. /** Starts the device running.
  20101. After calling this, the device will start sending midi messages to the
  20102. MidiInputCallback object that was specified when the openDevice() method
  20103. was called.
  20104. @see stop
  20105. */
  20106. virtual void start();
  20107. /** Stops the device running.
  20108. @see start
  20109. */
  20110. virtual void stop();
  20111. juce_UseDebuggingNewOperator
  20112. protected:
  20113. String name;
  20114. void* internal;
  20115. MidiInput (const String& name);
  20116. MidiInput (const MidiInput&);
  20117. };
  20118. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  20119. /********* End of inlined file: juce_MidiInput.h *********/
  20120. /**
  20121. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  20122. processing by a block-based audio callback.
  20123. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  20124. so it can easily use a midi input or keyboard component as its source.
  20125. @see MidiMessage, MidiInput
  20126. */
  20127. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  20128. public MidiInputCallback
  20129. {
  20130. public:
  20131. /** Creates a MidiMessageCollector. */
  20132. MidiMessageCollector();
  20133. /** Destructor. */
  20134. ~MidiMessageCollector();
  20135. /** Clears any messages from the queue.
  20136. You need to call this method before starting to use the collector, so that
  20137. it knows the correct sample rate to use.
  20138. */
  20139. void reset (const double sampleRate);
  20140. /** Takes an incoming real-time message and adds it to the queue.
  20141. The message's timestamp is taken, and it will be ready for retrieval as part
  20142. of the block returned by the next call to removeNextBlockOfMessages().
  20143. This method is fully thread-safe when overlapping calls are made with
  20144. removeNextBlockOfMessages().
  20145. */
  20146. void addMessageToQueue (const MidiMessage& message);
  20147. /** Removes all the pending messages from the queue as a buffer.
  20148. This will also correct the messages' timestamps to make sure they're in
  20149. the range 0 to numSamples - 1.
  20150. This call should be made regularly by something like an audio processing
  20151. callback, because the time that it happens is used in calculating the
  20152. midi event positions.
  20153. This method is fully thread-safe when overlapping calls are made with
  20154. addMessageToQueue().
  20155. */
  20156. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20157. const int numSamples);
  20158. /** @internal */
  20159. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  20160. /** @internal */
  20161. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  20162. /** @internal */
  20163. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  20164. juce_UseDebuggingNewOperator
  20165. private:
  20166. double lastCallbackTime;
  20167. CriticalSection midiCallbackLock;
  20168. MidiBuffer incomingMessages;
  20169. double sampleRate;
  20170. MidiMessageCollector (const MidiMessageCollector&);
  20171. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  20172. };
  20173. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  20174. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  20175. #endif
  20176. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  20177. #endif
  20178. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20179. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  20180. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20181. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20182. /**
  20183. A set of routines to convert buffers of 32-bit floating point data to and from
  20184. various integer formats.
  20185. */
  20186. class JUCE_API AudioDataConverters
  20187. {
  20188. public:
  20189. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  20190. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  20191. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  20192. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  20193. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20194. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20195. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20196. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  20197. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  20198. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  20199. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  20200. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  20201. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20202. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20203. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20204. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  20205. enum DataFormat
  20206. {
  20207. int16LE,
  20208. int16BE,
  20209. int24LE,
  20210. int24BE,
  20211. int32LE,
  20212. int32BE,
  20213. float32LE,
  20214. float32BE,
  20215. };
  20216. static void convertFloatToFormat (const DataFormat destFormat,
  20217. const float* source, void* dest, int numSamples);
  20218. static void convertFormatToFloat (const DataFormat sourceFormat,
  20219. const void* source, float* dest, int numSamples);
  20220. static void interleaveSamples (const float** source, float* dest,
  20221. const int numSamples, const int numChannels);
  20222. static void deinterleaveSamples (const float* source, float** dest,
  20223. const int numSamples, const int numChannels);
  20224. };
  20225. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  20226. /********* End of inlined file: juce_AudioDataConverters.h *********/
  20227. #endif
  20228. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20229. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  20230. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20231. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20232. class AudioFormatReader;
  20233. class AudioFormatWriter;
  20234. /**
  20235. A multi-channel buffer of 32-bit floating point audio samples.
  20236. */
  20237. class JUCE_API AudioSampleBuffer
  20238. {
  20239. public:
  20240. /** Creates a buffer with a specified number of channels and samples.
  20241. The contents of the buffer will initially be undefined, so use clear() to
  20242. set all the samples to zero.
  20243. The buffer will allocate its memory internally, and this will be released
  20244. when the buffer is deleted.
  20245. */
  20246. AudioSampleBuffer (const int numChannels,
  20247. const int numSamples) throw();
  20248. /** Creates a buffer using a pre-allocated block of memory.
  20249. Note that if the buffer is resized or its number of channels is changed, it
  20250. will re-allocate memory internally and copy the existing data to this new area,
  20251. so it will then stop directly addressing this memory.
  20252. @param dataToReferTo a pre-allocated array containing pointers to the data
  20253. for each channel that should be used by this buffer. The
  20254. buffer will only refer to this memory, it won't try to delete
  20255. it when the buffer is deleted or resized.
  20256. @param numChannels the number of channels to use - this must correspond to the
  20257. number of elements in the array passed in
  20258. @param numSamples the number of samples to use - this must correspond to the
  20259. size of the arrays passed in
  20260. */
  20261. AudioSampleBuffer (float** dataToReferTo,
  20262. const int numChannels,
  20263. const int numSamples) throw();
  20264. /** Copies another buffer.
  20265. This buffer will make its own copy of the other's data, unless the buffer was created
  20266. using an external data buffer, in which case boths buffers will just point to the same
  20267. shared block of data.
  20268. */
  20269. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  20270. /** Copies another buffer onto this one.
  20271. This buffer's size will be changed to that of the other buffer.
  20272. */
  20273. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  20274. /** Destructor.
  20275. This will free any memory allocated by the buffer.
  20276. */
  20277. virtual ~AudioSampleBuffer() throw();
  20278. /** Returns the number of channels of audio data that this buffer contains.
  20279. @see getSampleData
  20280. */
  20281. int getNumChannels() const throw() { return numChannels; }
  20282. /** Returns the number of samples allocated in each of the buffer's channels.
  20283. @see getSampleData
  20284. */
  20285. int getNumSamples() const throw() { return size; }
  20286. /** Returns a pointer one of the buffer's channels.
  20287. For speed, this doesn't check whether the channel number is out of range,
  20288. so be careful when using it!
  20289. */
  20290. float* getSampleData (const int channelNumber) const throw()
  20291. {
  20292. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20293. return channels [channelNumber];
  20294. }
  20295. /** Returns a pointer to a sample in one of the buffer's channels.
  20296. For speed, this doesn't check whether the channel and sample number
  20297. are out-of-range, so be careful when using it!
  20298. */
  20299. float* getSampleData (const int channelNumber,
  20300. const int sampleOffset) const throw()
  20301. {
  20302. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20303. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  20304. return channels [channelNumber] + sampleOffset;
  20305. }
  20306. /** Returns an array of pointers to the channels in the buffer.
  20307. Don't modify any of the pointers that are returned, and bear in mind that
  20308. these will become invalid if the buffer is resized.
  20309. */
  20310. float** getArrayOfChannels() const throw() { return channels; }
  20311. /** Chages the buffer's size or number of channels.
  20312. This can expand or contract the buffer's length, and add or remove channels.
  20313. If keepExistingContent is true, it will try to preserve as much of the
  20314. old data as it can in the new buffer.
  20315. If clearExtraSpace is true, then any extra channels or space that is
  20316. allocated will be also be cleared. If false, then this space is left
  20317. uninitialised.
  20318. If avoidReallocating is true, then changing the buffer's size won't reduce the
  20319. amount of memory that is currently allocated (but it will still increase it if
  20320. the new size is bigger than the amount it currently has). If this is false, then
  20321. a new allocation will be done so that the buffer uses takes up the minimum amount
  20322. of memory that it needs.
  20323. */
  20324. void setSize (const int newNumChannels,
  20325. const int newNumSamples,
  20326. const bool keepExistingContent = false,
  20327. const bool clearExtraSpace = false,
  20328. const bool avoidReallocating = false) throw();
  20329. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  20330. There's also a constructor that lets you specify arrays like this, but this
  20331. lets you change the channels dynamically.
  20332. Note that if the buffer is resized or its number of channels is changed, it
  20333. will re-allocate memory internally and copy the existing data to this new area,
  20334. so it will then stop directly addressing this memory.
  20335. @param dataToReferTo a pre-allocated array containing pointers to the data
  20336. for each channel that should be used by this buffer. The
  20337. buffer will only refer to this memory, it won't try to delete
  20338. it when the buffer is deleted or resized.
  20339. @param numChannels the number of channels to use - this must correspond to the
  20340. number of elements in the array passed in
  20341. @param numSamples the number of samples to use - this must correspond to the
  20342. size of the arrays passed in
  20343. */
  20344. void setDataToReferTo (float** dataToReferTo,
  20345. const int numChannels,
  20346. const int numSamples) throw();
  20347. /** Clears all the samples in all channels. */
  20348. void clear() throw();
  20349. /** Clears a specified region of all the channels.
  20350. For speed, this doesn't check whether the channel and sample number
  20351. are in-range, so be careful!
  20352. */
  20353. void clear (const int startSample,
  20354. const int numSamples) throw();
  20355. /** Clears a specified region of just one channel.
  20356. For speed, this doesn't check whether the channel and sample number
  20357. are in-range, so be careful!
  20358. */
  20359. void clear (const int channel,
  20360. const int startSample,
  20361. const int numSamples) throw();
  20362. /** Applies a gain multiple to a region of 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 applyGain (const int channel,
  20367. const int startSample,
  20368. int numSamples,
  20369. const float gain) throw();
  20370. /** Applies a gain multiple to a region of all the channels.
  20371. For speed, this doesn't check whether the sample numbers
  20372. are in-range, so be careful!
  20373. */
  20374. void applyGain (const int startSample,
  20375. const int numSamples,
  20376. const float gain) throw();
  20377. /** Applies a range of gains to a region of a channel.
  20378. The gain that is applied to each sample will vary from
  20379. startGain on the first sample to endGain on the last Sample,
  20380. so it can be used to do basic fades.
  20381. For speed, this doesn't check whether the sample numbers
  20382. are in-range, so be careful!
  20383. */
  20384. void applyGainRamp (const int channel,
  20385. const int startSample,
  20386. int numSamples,
  20387. float startGain,
  20388. float endGain) throw();
  20389. /** Adds samples from another buffer to this one.
  20390. @param destChannel the channel within this buffer to add the samples to
  20391. @param destStartSample the start sample within this buffer's channel
  20392. @param source the source buffer to add from
  20393. @param sourceChannel the channel within the source buffer to read from
  20394. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20395. @param numSamples the number of samples to process
  20396. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20397. added to this buffer's samples
  20398. @see copyFrom
  20399. */
  20400. void addFrom (const int destChannel,
  20401. const int destStartSample,
  20402. const AudioSampleBuffer& source,
  20403. const int sourceChannel,
  20404. const int sourceStartSample,
  20405. int numSamples,
  20406. const float gainToApplyToSource = 1.0f) throw();
  20407. /** Adds samples from an array of floats to one of the channels.
  20408. @param destChannel the channel within this buffer to add the samples to
  20409. @param destStartSample the start sample within this buffer's channel
  20410. @param source the source data to use
  20411. @param numSamples the number of samples to process
  20412. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20413. added to this buffer's samples
  20414. @see copyFrom
  20415. */
  20416. void addFrom (const int destChannel,
  20417. const int destStartSample,
  20418. const float* source,
  20419. int numSamples,
  20420. const float gainToApplyToSource = 1.0f) throw();
  20421. /** Adds samples from an array of floats, applying a gain ramp to them.
  20422. @param destChannel the channel within this buffer to add the samples to
  20423. @param destStartSample the start sample within this buffer's channel
  20424. @param source the source data to use
  20425. @param numSamples the number of samples to process
  20426. @param startGain the gain to apply to the first sample (this is multiplied with
  20427. the source samples before they are added to this buffer)
  20428. @param endGain the gain to apply to the final sample. The gain is linearly
  20429. interpolated between the first and last samples.
  20430. */
  20431. void addFromWithRamp (const int destChannel,
  20432. const int destStartSample,
  20433. const float* source,
  20434. int numSamples,
  20435. float startGain,
  20436. float endGain) throw();
  20437. /** Copies samples from another buffer to this one.
  20438. @param destChannel the channel within this buffer to copy the samples to
  20439. @param destStartSample the start sample within this buffer's channel
  20440. @param source the source buffer to read from
  20441. @param sourceChannel the channel within the source buffer to read from
  20442. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20443. @param numSamples the number of samples to process
  20444. @see addFrom
  20445. */
  20446. void copyFrom (const int destChannel,
  20447. const int destStartSample,
  20448. const AudioSampleBuffer& source,
  20449. const int sourceChannel,
  20450. const int sourceStartSample,
  20451. int numSamples) throw();
  20452. /** Copies samples from an array of floats into one of the channels.
  20453. @param destChannel the channel within this buffer to copy the samples to
  20454. @param destStartSample the start sample within this buffer's channel
  20455. @param source the source buffer to read from
  20456. @param numSamples the number of samples to process
  20457. @see addFrom
  20458. */
  20459. void copyFrom (const int destChannel,
  20460. const int destStartSample,
  20461. const float* source,
  20462. int numSamples) throw();
  20463. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  20464. @param destChannel the channel within this buffer to copy the samples to
  20465. @param destStartSample the start sample within this buffer's channel
  20466. @param source the source buffer to read from
  20467. @param numSamples the number of samples to process
  20468. @param gain the gain to apply
  20469. @see addFrom
  20470. */
  20471. void copyFrom (const int destChannel,
  20472. const int destStartSample,
  20473. const float* source,
  20474. int numSamples,
  20475. const float gain) throw();
  20476. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  20477. @param destChannel the channel within this buffer to copy the samples to
  20478. @param destStartSample the start sample within this buffer's channel
  20479. @param source the source buffer to read from
  20480. @param numSamples the number of samples to process
  20481. @param startGain the gain to apply to the first sample (this is multiplied with
  20482. the source samples before they are copied to this buffer)
  20483. @param endGain the gain to apply to the final sample. The gain is linearly
  20484. interpolated between the first and last samples.
  20485. @see addFrom
  20486. */
  20487. void copyFromWithRamp (const int destChannel,
  20488. const int destStartSample,
  20489. const float* source,
  20490. int numSamples,
  20491. float startGain,
  20492. float endGain) throw();
  20493. /** Finds the highest and lowest sample values in a given range.
  20494. @param channel the channel to read from
  20495. @param startSample the start sample within the channel
  20496. @param numSamples the number of samples to check
  20497. @param minVal on return, the lowest value that was found
  20498. @param maxVal on return, the highest value that was found
  20499. */
  20500. void findMinMax (const int channel,
  20501. const int startSample,
  20502. int numSamples,
  20503. float& minVal,
  20504. float& maxVal) const throw();
  20505. /** Finds the highest absolute sample value within a region of a channel.
  20506. */
  20507. float getMagnitude (const int channel,
  20508. const int startSample,
  20509. const int numSamples) const throw();
  20510. /** Finds the highest absolute sample value within a region on all channels.
  20511. */
  20512. float getMagnitude (const int startSample,
  20513. const int numSamples) const throw();
  20514. /** Returns the root mean squared level for a region of a channel.
  20515. */
  20516. float getRMSLevel (const int channel,
  20517. const int startSample,
  20518. const int numSamples) const throw();
  20519. /** Fills a section of the buffer using an AudioReader as its source.
  20520. This will convert the reader's fixed- or floating-point data to
  20521. the buffer's floating-point format, and will try to intelligently
  20522. cope with mismatches between the number of channels in the reader
  20523. and the buffer.
  20524. @see writeToAudioWriter
  20525. */
  20526. void readFromAudioReader (AudioFormatReader* reader,
  20527. const int startSample,
  20528. const int numSamples,
  20529. const int readerStartSample,
  20530. const bool useReaderLeftChan,
  20531. const bool useReaderRightChan) throw();
  20532. /** Writes a section of this buffer to an audio writer.
  20533. This saves you having to mess about with channels or floating/fixed
  20534. point conversion.
  20535. @see readFromAudioReader
  20536. */
  20537. void writeToAudioWriter (AudioFormatWriter* writer,
  20538. const int startSample,
  20539. const int numSamples) const throw();
  20540. juce_UseDebuggingNewOperator
  20541. private:
  20542. int numChannels, size, allocatedBytes;
  20543. float** channels;
  20544. float* allocatedData;
  20545. float* preallocatedChannelSpace [32];
  20546. };
  20547. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20548. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20549. #endif
  20550. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20551. /********* Start of inlined file: juce_IIRFilter.h *********/
  20552. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  20553. #define __JUCE_IIRFILTER_JUCEHEADER__
  20554. /**
  20555. An IIR filter that can perform low, high, or band-pass filtering on an
  20556. audio signal.
  20557. @see IIRFilterAudioSource
  20558. */
  20559. class JUCE_API IIRFilter
  20560. {
  20561. public:
  20562. /** Creates a filter.
  20563. Initially the filter is inactive, so will have no effect on samples that
  20564. you process with it. Use the appropriate method to turn it into the type
  20565. of filter needed.
  20566. */
  20567. IIRFilter() throw();
  20568. /** Creates a copy of another filter. */
  20569. IIRFilter (const IIRFilter& other) throw();
  20570. /** Destructor. */
  20571. ~IIRFilter() throw();
  20572. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  20573. Note that this clears the processing state, but the type of filter and
  20574. its coefficients aren't changed. To put a filter into an inactive state, use
  20575. the makeInactive() method.
  20576. */
  20577. void reset() throw();
  20578. /** Performs the filter operation on the given set of samples.
  20579. */
  20580. void processSamples (float* const samples,
  20581. const int numSamples) throw();
  20582. /** Processes a single sample, without any locking or checking.
  20583. Use this if you need fast processing of a single value, but be aware that
  20584. this isn't thread-safe in the way that processSamples() is.
  20585. */
  20586. float processSingleSampleRaw (const float sample) throw();
  20587. /** Sets the filter up to act as a low-pass filter.
  20588. */
  20589. void makeLowPass (const double sampleRate,
  20590. const double frequency) throw();
  20591. /** Sets the filter up to act as a high-pass filter.
  20592. */
  20593. void makeHighPass (const double sampleRate,
  20594. const double frequency) throw();
  20595. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  20596. The gain is a scale factor that the low frequencies are multiplied by, so values
  20597. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  20598. attenuate them.
  20599. */
  20600. void makeLowShelf (const double sampleRate,
  20601. const double cutOffFrequency,
  20602. const double Q,
  20603. const float gainFactor) throw();
  20604. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  20605. The gain is a scale factor that the high frequencies are multiplied by, so values
  20606. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  20607. attenuate them.
  20608. */
  20609. void makeHighShelf (const double sampleRate,
  20610. const double cutOffFrequency,
  20611. const double Q,
  20612. const float gainFactor) throw();
  20613. /** Sets the filter up to act as a band pass filter centred around a
  20614. frequency, with a variable Q and gain.
  20615. The gain is a scale factor that the centre frequencies are multiplied by, so
  20616. values greater than 1.0 will boost the centre frequencies, values less than
  20617. 1.0 will attenuate them.
  20618. */
  20619. void makeBandPass (const double sampleRate,
  20620. const double centreFrequency,
  20621. const double Q,
  20622. const float gainFactor) throw();
  20623. /** Clears the filter's coefficients so that it becomes inactive.
  20624. */
  20625. void makeInactive() throw();
  20626. /** Makes this filter duplicate the set-up of another one.
  20627. */
  20628. void copyCoefficientsFrom (const IIRFilter& other) throw();
  20629. juce_UseDebuggingNewOperator
  20630. protected:
  20631. CriticalSection processLock;
  20632. void setCoefficients (double c1, double c2, double c3,
  20633. double c4, double c5, double c6) throw();
  20634. bool active;
  20635. float coefficients[6];
  20636. float x1, x2, y1, y2;
  20637. // (use the copyCoefficientsFrom() method instead of this operator)
  20638. const IIRFilter& operator= (const IIRFilter&);
  20639. };
  20640. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  20641. /********* End of inlined file: juce_IIRFilter.h *********/
  20642. #endif
  20643. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20644. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  20645. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20646. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20647. /**
  20648. A subclass of AudioPlayHead can supply information about the position and
  20649. status of a moving play head during audio playback.
  20650. One of these can be supplied to an AudioProcessor object so that it can find
  20651. out about the position of the audio that it is rendering.
  20652. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  20653. */
  20654. class JUCE_API AudioPlayHead
  20655. {
  20656. protected:
  20657. AudioPlayHead() {}
  20658. public:
  20659. virtual ~AudioPlayHead() {}
  20660. /** Frame rate types. */
  20661. enum FrameRateType
  20662. {
  20663. fps24 = 0,
  20664. fps25 = 1,
  20665. fps2997 = 2,
  20666. fps30 = 3,
  20667. fps2997drop = 4,
  20668. fps30drop = 5,
  20669. fpsUnknown = 99
  20670. };
  20671. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  20672. */
  20673. struct CurrentPositionInfo
  20674. {
  20675. /** The tempo in BPM */
  20676. double bpm;
  20677. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  20678. int timeSigNumerator;
  20679. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  20680. int timeSigDenominator;
  20681. /** The current play position, in seconds from the start of the edit. */
  20682. double timeInSeconds;
  20683. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  20684. double editOriginTime;
  20685. /** The current play position in pulses-per-quarter-note.
  20686. This is the number of quarter notes since the edit start.
  20687. */
  20688. double ppqPosition;
  20689. /** The position of the start of the last bar, in pulses-per-quarter-note.
  20690. This is the number of quarter notes from the start of the edit to the
  20691. start of the current bar.
  20692. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  20693. it's not available, the value will be 0.
  20694. */
  20695. double ppqPositionOfLastBarStart;
  20696. /** The video frame rate, if applicable. */
  20697. FrameRateType frameRate;
  20698. /** True if the transport is currently playing. */
  20699. bool isPlaying;
  20700. /** True if the transport is currently recording.
  20701. (When isRecording is true, then isPlaying will also be true).
  20702. */
  20703. bool isRecording;
  20704. };
  20705. /** Fills-in the given structure with details about the transport's
  20706. position at the start of the current processing block.
  20707. */
  20708. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  20709. };
  20710. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  20711. /********* End of inlined file: juce_AudioPlayHead.h *********/
  20712. #endif
  20713. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20714. /********* Start of inlined file: juce_AudioProcessor.h *********/
  20715. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20716. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  20717. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  20718. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20719. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20720. class AudioProcessor;
  20721. /**
  20722. Base class for the component that acts as the GUI for an AudioProcessor.
  20723. Derive your editor component from this class, and create an instance of it
  20724. by overriding the AudioProcessor::createEditor() method.
  20725. @see AudioProcessor, GenericAudioProcessorEditor
  20726. */
  20727. class JUCE_API AudioProcessorEditor : public Component
  20728. {
  20729. protected:
  20730. /** Creates an editor for the specified processor.
  20731. */
  20732. AudioProcessorEditor (AudioProcessor* const owner);
  20733. public:
  20734. /** Destructor. */
  20735. ~AudioProcessorEditor();
  20736. /** Returns a pointer to the processor that this editor represents. */
  20737. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  20738. private:
  20739. AudioProcessor* const owner;
  20740. };
  20741. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  20742. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  20743. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  20744. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20745. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20746. class AudioProcessor;
  20747. /**
  20748. Base class for listeners that want to know about changes to an AudioProcessor.
  20749. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  20750. @see AudioProcessor
  20751. */
  20752. class JUCE_API AudioProcessorListener
  20753. {
  20754. public:
  20755. /** Destructor. */
  20756. virtual ~AudioProcessorListener() {}
  20757. /** Receives a callback when a parameter is changed.
  20758. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  20759. many audio processors will change their parameter during their audio callback.
  20760. This means that not only has your handler code got to be completely thread-safe,
  20761. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  20762. this event on your message thread, use this callback to trigger an AsyncUpdater
  20763. or ChangeBroadcaster which you can respond to on the message thread.
  20764. */
  20765. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  20766. int parameterIndex,
  20767. float newValue) = 0;
  20768. /** Called to indicate that something else in the plugin has changed, like its
  20769. program, number of parameters, etc.
  20770. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20771. call it during their audio callback. This means that not only has your handler code
  20772. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20773. blocking. If you need to handle this event on your message thread, use this callback
  20774. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20775. message thread.
  20776. */
  20777. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  20778. /** Indicates that a parameter change gesture has started.
  20779. E.g. if the user is dragging a slider, this would be called when they first
  20780. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  20781. called when they release it.
  20782. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20783. call it during their audio callback. This means that not only has your handler code
  20784. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20785. blocking. If you need to handle this event on your message thread, use this callback
  20786. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20787. message thread.
  20788. @see audioProcessorParameterChangeGestureEnd
  20789. */
  20790. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  20791. int parameterIndex);
  20792. /** Indicates that a parameter change gesture has finished.
  20793. E.g. if the user is dragging a slider, this would be called when they release
  20794. the mouse button.
  20795. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  20796. call it during their audio callback. This means that not only has your handler code
  20797. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  20798. blocking. If you need to handle this event on your message thread, use this callback
  20799. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  20800. message thread.
  20801. @see audioPluginParameterChangeGestureStart
  20802. */
  20803. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  20804. int parameterIndex);
  20805. };
  20806. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  20807. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  20808. /**
  20809. Base class for audio processing filters or plugins.
  20810. This is intended to act as a base class of audio filter that is general enough to
  20811. be wrapped as a VST, AU, RTAS, etc, or used internally.
  20812. It is also used by the plugin hosting code as the wrapper around an instance
  20813. of a loaded plugin.
  20814. Derive your filter class from this base class, and if you're building a plugin,
  20815. you should implement a global function called createPluginFilter() which creates
  20816. and returns a new instance of your subclass.
  20817. */
  20818. class JUCE_API AudioProcessor
  20819. {
  20820. protected:
  20821. /** Constructor.
  20822. You can also do your initialisation tasks in the initialiseFilterInfo()
  20823. call, which will be made after this object has been created.
  20824. */
  20825. AudioProcessor();
  20826. public:
  20827. /** Destructor. */
  20828. virtual ~AudioProcessor();
  20829. /** Returns the name of this processor.
  20830. */
  20831. virtual const String getName() const = 0;
  20832. /** Called before playback starts, to let the filter prepare itself.
  20833. The sample rate is the target sample rate, and will remain constant until
  20834. playback stops.
  20835. The estimatedSamplesPerBlock value is a HINT about the typical number of
  20836. samples that will be processed for each callback, but isn't any kind
  20837. of guarantee. The actual block sizes that the host uses may be different
  20838. each time the callback happens, and may be more or less than this value.
  20839. */
  20840. virtual void prepareToPlay (double sampleRate,
  20841. int estimatedSamplesPerBlock) = 0;
  20842. /** Called after playback has stopped, to let the filter free up any resources it
  20843. no longer needs.
  20844. */
  20845. virtual void releaseResources() = 0;
  20846. /** Renders the next block.
  20847. When this method is called, the buffer contains a number of channels which is
  20848. at least as great as the maximum number of input and output channels that
  20849. this filter is using. It will be filled with the filter's input data and
  20850. should be replaced with the filter's output.
  20851. So for example if your filter has 2 input channels and 4 output channels, then
  20852. the buffer will contain 4 channels, the first two being filled with the
  20853. input data. Your filter should read these, do its processing, and replace
  20854. the contents of all 4 channels with its output.
  20855. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  20856. all filled with data, and your filter should overwrite the first 2 of these
  20857. with its output. But be VERY careful not to write anything to the last 3
  20858. channels, as these might be mapped to memory that the host assumes is read-only!
  20859. Note that if you have more outputs than inputs, then only those channels that
  20860. correspond to an input channel are guaranteed to contain sensible data - e.g.
  20861. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  20862. but the last two channels may contain garbage, so you should be careful not to
  20863. let this pass through without being overwritten or cleared.
  20864. Also note that the buffer may have more channels than are strictly necessary,
  20865. but your should only read/write from the ones that your filter is supposed to
  20866. be using.
  20867. The number of samples in these buffers is NOT guaranteed to be the same for every
  20868. callback, and may be more or less than the estimated value given to prepareToPlay().
  20869. Your code must be able to cope with variable-sized blocks, or you're going to get
  20870. clicks and crashes!
  20871. If the filter is receiving a midi input, then the midiMessages array will be filled
  20872. with the midi messages for this block. Each message's timestamp will indicate the
  20873. message's time, as a number of samples from the start of the block.
  20874. Any messages left in the midi buffer when this method has finished are assumed to
  20875. be the filter's midi output. This means that your filter should be careful to
  20876. clear any incoming messages from the array if it doesn't want them to be passed-on.
  20877. Be very careful about what you do in this callback - it's going to be called by
  20878. the audio thread, so any kind of interaction with the UI is absolutely
  20879. out of the question. If you change a parameter in here and need to tell your UI to
  20880. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  20881. the UI components register as listeners, and then call sendChangeMessage() inside the
  20882. processBlock() method to send out an asynchronous message. You could also use
  20883. the AsyncUpdater class in a similar way.
  20884. */
  20885. virtual void processBlock (AudioSampleBuffer& buffer,
  20886. MidiBuffer& midiMessages) = 0;
  20887. /** Returns the current AudioPlayHead object that should be used to find
  20888. out the state and position of the playhead.
  20889. You can call this from your processBlock() method, and use the AudioPlayHead
  20890. object to get the details about the time of the start of the block currently
  20891. being processed.
  20892. If the host hasn't supplied a playhead object, this will return 0.
  20893. */
  20894. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  20895. /** Returns the current sample rate.
  20896. This can be called from your processBlock() method - it's not guaranteed
  20897. to be valid at any other time, and may return 0 if it's unknown.
  20898. */
  20899. double getSampleRate() const throw() { return sampleRate; }
  20900. /** Returns the current typical block size that is being used.
  20901. This can be called from your processBlock() method - it's not guaranteed
  20902. to be valid at any other time.
  20903. Remember it's not the ONLY block size that may be used when calling
  20904. processBlock, it's just the normal one. The actual block sizes used may be
  20905. larger or smaller than this, and will vary between successive calls.
  20906. */
  20907. int getBlockSize() const throw() { return blockSize; }
  20908. /** Returns the number of input channels that the host will be sending the filter.
  20909. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20910. number of channels that your filter would prefer to have, and this method lets
  20911. you know how many the host is actually using.
  20912. Note that this method is only valid during or after the prepareToPlay()
  20913. method call. Until that point, the number of channels will be unknown.
  20914. */
  20915. int getNumInputChannels() const throw() { return numInputChannels; }
  20916. /** Returns the number of output channels that the host will be sending the filter.
  20917. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  20918. number of channels that your filter would prefer to have, and this method lets
  20919. you know how many the host is actually using.
  20920. Note that this method is only valid during or after the prepareToPlay()
  20921. method call. Until that point, the number of channels will be unknown.
  20922. */
  20923. int getNumOutputChannels() const throw() { return numOutputChannels; }
  20924. /** Returns the name of one of the input channels, as returned by the host.
  20925. The host might not supply very useful names for channels, and this might be
  20926. something like "1", "2", "left", "right", etc.
  20927. */
  20928. virtual const String getInputChannelName (const int channelIndex) const = 0;
  20929. /** Returns the name of one of the output channels, as returned by the host.
  20930. The host might not supply very useful names for channels, and this might be
  20931. something like "1", "2", "left", "right", etc.
  20932. */
  20933. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  20934. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20935. virtual bool isInputChannelStereoPair (int index) const = 0;
  20936. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  20937. virtual bool isOutputChannelStereoPair (int index) const = 0;
  20938. /** This returns the number of samples delay that the filter imposes on the audio
  20939. passing through it.
  20940. The host will call this to find the latency - the filter itself should set this value
  20941. by calling setLatencySamples() as soon as it can during its initialisation.
  20942. */
  20943. int getLatencySamples() const throw() { return latencySamples; }
  20944. /** The filter should call this to set the number of samples delay that it introduces.
  20945. The filter should call this as soon as it can during initialisation, and can call it
  20946. later if the value changes.
  20947. */
  20948. void setLatencySamples (const int newLatency);
  20949. /** Returns true if the processor wants midi messages. */
  20950. virtual bool acceptsMidi() const = 0;
  20951. /** Returns true if the processor produces midi messages. */
  20952. virtual bool producesMidi() const = 0;
  20953. /** This returns a critical section that will automatically be locked while the host
  20954. is calling the processBlock() method.
  20955. Use it from your UI or other threads to lock access to variables that are used
  20956. by the process callback, but obviously be careful not to keep it locked for
  20957. too long, because that could cause stuttering playback. If you need to do something
  20958. that'll take a long time and need the processing to stop while it happens, use the
  20959. suspendProcessing() method instead.
  20960. @see suspendProcessing
  20961. */
  20962. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  20963. /** Enables and disables the processing callback.
  20964. If you need to do something time-consuming on a thread and would like to make sure
  20965. the audio processing callback doesn't happen until you've finished, use this
  20966. to disable the callback and re-enable it again afterwards.
  20967. E.g.
  20968. @code
  20969. void loadNewPatch()
  20970. {
  20971. suspendProcessing (true);
  20972. ..do something that takes ages..
  20973. suspendProcessing (false);
  20974. }
  20975. @endcode
  20976. If the host tries to make an audio callback while processing is suspended, the
  20977. filter will return an empty buffer, but won't block the audio thread like it would
  20978. do if you use the getCallbackLock() critical section to synchronise access.
  20979. If you're going to use this, your processBlock() method must call isSuspended() and
  20980. check whether it's suspended or not. If it is, then it should skip doing any real
  20981. processing, either emitting silence or passing the input through unchanged.
  20982. @see getCallbackLock
  20983. */
  20984. void suspendProcessing (const bool shouldBeSuspended);
  20985. /** Returns true if processing is currently suspended.
  20986. @see suspendProcessing
  20987. */
  20988. bool isSuspended() const throw() { return suspended; }
  20989. /** A plugin can override this to be told when it should reset any playing voices.
  20990. The default implementation does nothing, but a host may call this to tell the
  20991. plugin that it should stop any tails or sounds that have been left running.
  20992. */
  20993. virtual void reset();
  20994. /** Returns true if the processor is being run in an offline mode for rendering.
  20995. If the processor is being run live on realtime signals, this returns false.
  20996. If the mode is unknown, this will assume it's realtime and return false.
  20997. This value may be unreliable until the prepareToPlay() method has been called,
  20998. and could change each time prepareToPlay() is called.
  20999. @see setNonRealtime()
  21000. */
  21001. bool isNonRealtime() const throw() { return nonRealtime; }
  21002. /** Called by the host to tell this processor whether it's being used in a non-realime
  21003. capacity for offline rendering or bouncing.
  21004. Whatever value is passed-in will be
  21005. */
  21006. void setNonRealtime (const bool isNonRealtime) throw();
  21007. /** Creates the filter's UI.
  21008. This can return 0 if you want a UI-less filter, in which case the host may create
  21009. a generic UI that lets the user twiddle the parameters directly.
  21010. If you do want to pass back a component, the component should be created and set to
  21011. the correct size before returning it.
  21012. Remember not to do anything silly like allowing your filter to keep a pointer to
  21013. the component that gets created - it could be deleted later without any warning, which
  21014. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  21015. The correct way to handle the connection between an editor component and its
  21016. filter is to use something like a ChangeBroadcaster so that the editor can
  21017. register itself as a listener, and be told when a change occurs. This lets them
  21018. safely unregister themselves when they are deleted.
  21019. Here are a few things to bear in mind when writing an editor:
  21020. - Initially there won't be an editor, until the user opens one, or they might
  21021. not open one at all. Your filter mustn't rely on it being there.
  21022. - An editor object may be deleted and a replacement one created again at any time.
  21023. - It's safe to assume that an editor will be deleted before its filter.
  21024. */
  21025. virtual AudioProcessorEditor* createEditor() = 0;
  21026. /** Returns the active editor, if there is one.
  21027. Bear in mind this can return 0, even if an editor has previously been
  21028. opened.
  21029. */
  21030. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  21031. /** Returns the active editor, or if there isn't one, it will create one.
  21032. This may call createEditor() internally to create the component.
  21033. */
  21034. AudioProcessorEditor* createEditorIfNeeded();
  21035. /** This must return the correct value immediately after the object has been
  21036. created, and mustn't change the number of parameters later.
  21037. */
  21038. virtual int getNumParameters() = 0;
  21039. /** Returns the name of a particular parameter. */
  21040. virtual const String getParameterName (int parameterIndex) = 0;
  21041. /** Called by the host to find out the value of one of the filter's parameters.
  21042. The host will expect the value returned to be between 0 and 1.0.
  21043. This could be called quite frequently, so try to make your code efficient.
  21044. It's also likely to be called by non-UI threads, so the code in here should
  21045. be thread-aware.
  21046. */
  21047. virtual float getParameter (int parameterIndex) = 0;
  21048. /** Returns the value of a parameter as a text string. */
  21049. virtual const String getParameterText (int parameterIndex) = 0;
  21050. /** The host will call this method to change the value of one of the filter's parameters.
  21051. The host may call this at any time, including during the audio processing
  21052. callback, so the filter has to process this very fast and avoid blocking.
  21053. If you want to set the value of a parameter internally, e.g. from your
  21054. editor component, then don't call this directly - instead, use the
  21055. setParameterNotifyingHost() method, which will also send a message to
  21056. the host telling it about the change. If the message isn't sent, the host
  21057. won't be able to automate your parameters properly.
  21058. The value passed will be between 0 and 1.0.
  21059. */
  21060. virtual void setParameter (int parameterIndex,
  21061. float newValue) = 0;
  21062. /** Your filter can call this when it needs to change one of its parameters.
  21063. This could happen when the editor or some other internal operation changes
  21064. a parameter. This method will call the setParameter() method to change the
  21065. value, and will then send a message to the host telling it about the change.
  21066. Note that to make sure the host correctly handles automation, you should call
  21067. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  21068. tell the host when the user has started and stopped changing the parameter.
  21069. */
  21070. void setParameterNotifyingHost (int parameterIndex,
  21071. float newValue);
  21072. /** Returns true if the host can automate this parameter.
  21073. By default, this returns true for all parameters.
  21074. */
  21075. virtual bool isParameterAutomatable (int parameterIndex) const;
  21076. /** Should return true if this parameter is a "meta" parameter.
  21077. A meta-parameter is a parameter that changes other params. It is used
  21078. by some hosts (e.g. AudioUnit hosts).
  21079. By default this returns false.
  21080. */
  21081. virtual bool isMetaParameter (int parameterIndex) const;
  21082. /** Sends a signal to the host to tell it that the user is about to start changing this
  21083. parameter.
  21084. This allows the host to know when a parameter is actively being held by the user, and
  21085. it may use this information to help it record automation.
  21086. If you call this, it must be matched by a later call to endParameterChangeGesture().
  21087. */
  21088. void beginParameterChangeGesture (int parameterIndex);
  21089. /** Tells the host that the user has finished changing this parameter.
  21090. This allows the host to know when a parameter is actively being held by the user, and
  21091. it may use this information to help it record automation.
  21092. A call to this method must follow a call to beginParameterChangeGesture().
  21093. */
  21094. void endParameterChangeGesture (int parameterIndex);
  21095. /** The filter can call this when something (apart from a parameter value) has changed.
  21096. It sends a hint to the host that something like the program, number of parameters,
  21097. etc, has changed, and that it should update itself.
  21098. */
  21099. void updateHostDisplay();
  21100. /** Returns the number of preset programs the filter supports.
  21101. The value returned must be valid as soon as this object is created, and
  21102. must not change over its lifetime.
  21103. This value shouldn't be less than 1.
  21104. */
  21105. virtual int getNumPrograms() = 0;
  21106. /** Returns the number of the currently active program.
  21107. */
  21108. virtual int getCurrentProgram() = 0;
  21109. /** Called by the host to change the current program.
  21110. */
  21111. virtual void setCurrentProgram (int index) = 0;
  21112. /** Must return the name of a given program. */
  21113. virtual const String getProgramName (int index) = 0;
  21114. /** Called by the host to rename a program.
  21115. */
  21116. virtual void changeProgramName (int index, const String& newName) = 0;
  21117. /** The host will call this method when it wants to save the filter's internal state.
  21118. This must copy any info about the filter's state into the block of memory provided,
  21119. so that the host can store this and later restore it using setStateInformation().
  21120. Note that there's also a getCurrentProgramStateInformation() method, which only
  21121. stores the current program, not the state of the entire filter.
  21122. See also the helper function copyXmlToBinary() for storing settings as XML.
  21123. @see getCurrentProgramStateInformation
  21124. */
  21125. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  21126. /** The host will call this method if it wants to save the state of just the filter's
  21127. current program.
  21128. Unlike getStateInformation, this should only return the current program's state.
  21129. Not all hosts support this, and if you don't implement it, the base class
  21130. method just calls getStateInformation() instead. If you do implement it, be
  21131. sure to also implement getCurrentProgramStateInformation.
  21132. @see getStateInformation, setCurrentProgramStateInformation
  21133. */
  21134. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  21135. /** This must restore the filter's state from a block of data previously created
  21136. using getStateInformation().
  21137. Note that there's also a setCurrentProgramStateInformation() method, which tries
  21138. to restore just the current program, not the state of the entire filter.
  21139. See also the helper function getXmlFromBinary() for loading settings as XML.
  21140. @see setCurrentProgramStateInformation
  21141. */
  21142. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  21143. /** The host will call this method if it wants to restore the state of just the filter's
  21144. current program.
  21145. Not all hosts support this, and if you don't implement it, the base class
  21146. method just calls setStateInformation() instead. If you do implement it, be
  21147. sure to also implement getCurrentProgramStateInformation.
  21148. @see setStateInformation, getCurrentProgramStateInformation
  21149. */
  21150. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  21151. /** Adds a listener that will be called when an aspect of this processor changes. */
  21152. void addListener (AudioProcessorListener* const newListener) throw();
  21153. /** Removes a previously added listener. */
  21154. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  21155. /** Not for public use - this is called before deleting an editor component. */
  21156. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  21157. /** Not for public use - this is called to initialise the processor. */
  21158. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  21159. /** Not for public use - this is called to initialise the processor before playing. */
  21160. void setPlayConfigDetails (const int numIns, const int numOuts,
  21161. const double sampleRate,
  21162. const int blockSize) throw();
  21163. juce_UseDebuggingNewOperator
  21164. protected:
  21165. /** Helper function that just converts an xml element into a binary blob.
  21166. Use this in your filter's getStateInformation() method if you want to
  21167. store its state as xml.
  21168. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  21169. from a binary blob.
  21170. */
  21171. static void copyXmlToBinary (const XmlElement& xml,
  21172. JUCE_NAMESPACE::MemoryBlock& destData);
  21173. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  21174. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  21175. an XmlElement object that the caller must delete when no longer needed.
  21176. */
  21177. static XmlElement* getXmlFromBinary (const void* data,
  21178. const int sizeInBytes);
  21179. /** @internal */
  21180. AudioPlayHead* playHead;
  21181. /** @internal */
  21182. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  21183. private:
  21184. VoidArray listeners;
  21185. AudioProcessorEditor* activeEditor;
  21186. double sampleRate;
  21187. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  21188. bool suspended, nonRealtime;
  21189. CriticalSection callbackLock, listenerLock;
  21190. #ifdef JUCE_DEBUG
  21191. BitArray changingParams;
  21192. #endif
  21193. AudioProcessor (const AudioProcessor&);
  21194. const AudioProcessor& operator= (const AudioProcessor&);
  21195. };
  21196. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  21197. /********* End of inlined file: juce_AudioProcessor.h *********/
  21198. #endif
  21199. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  21200. #endif
  21201. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21202. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  21203. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21204. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  21205. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  21206. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21207. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21208. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  21209. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21210. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21211. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  21212. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21213. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21214. /********* Start of inlined file: juce_PluginDescription.h *********/
  21215. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21216. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21217. /**
  21218. A small class to represent some facts about a particular type of plugin.
  21219. This class is for storing and managing the details about a plugin without
  21220. actually having to load an instance of it.
  21221. A KnownPluginList contains a list of PluginDescription objects.
  21222. @see KnownPluginList
  21223. */
  21224. class JUCE_API PluginDescription
  21225. {
  21226. public:
  21227. PluginDescription() throw();
  21228. PluginDescription (const PluginDescription& other) throw();
  21229. const PluginDescription& operator= (const PluginDescription& other) throw();
  21230. ~PluginDescription() throw();
  21231. /** The name of the plugin. */
  21232. String name;
  21233. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  21234. */
  21235. String pluginFormatName;
  21236. /** A category, such as "Dynamics", "Reverbs", etc.
  21237. */
  21238. String category;
  21239. /** The manufacturer. */
  21240. String manufacturerName;
  21241. /** The version. This string doesn't have any particular format. */
  21242. String version;
  21243. /** Either the file containing the plugin module, or some other unique way
  21244. of identifying it.
  21245. E.g. for an AU, this would be an ID string that the component manager
  21246. could use to retrieve the plugin. For a VST, it's the file path.
  21247. */
  21248. String fileOrIdentifier;
  21249. /** The last time the plugin file was changed.
  21250. This is handy when scanning for new or changed plugins.
  21251. */
  21252. Time lastFileModTime;
  21253. /** A unique ID for the plugin.
  21254. Note that this might not be unique between formats, e.g. a VST and some
  21255. other format might actually have the same id.
  21256. @see createIdentifierString
  21257. */
  21258. int uid;
  21259. /** True if the plugin identifies itself as a synthesiser. */
  21260. bool isInstrument;
  21261. /** The number of inputs. */
  21262. int numInputChannels;
  21263. /** The number of outputs. */
  21264. int numOutputChannels;
  21265. /** Returns true if the two descriptions refer the the same plugin.
  21266. This isn't quite as simple as them just having the same file (because of
  21267. shell plugins).
  21268. */
  21269. bool isDuplicateOf (const PluginDescription& other) const;
  21270. /** Returns a string that can be saved and used to uniquely identify the
  21271. plugin again.
  21272. This contains less info than the XML encoding, and is independent of the
  21273. plugin's file location, so can be used to store a plugin ID for use
  21274. across different machines.
  21275. */
  21276. const String createIdentifierString() const throw();
  21277. /** Creates an XML object containing these details.
  21278. @see loadFromXml
  21279. */
  21280. XmlElement* createXml() const;
  21281. /** Reloads the info in this structure from an XML record that was previously
  21282. saved with createXML().
  21283. Returns true if the XML was a valid plugin description.
  21284. */
  21285. bool loadFromXml (const XmlElement& xml);
  21286. juce_UseDebuggingNewOperator
  21287. };
  21288. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  21289. /********* End of inlined file: juce_PluginDescription.h *********/
  21290. /**
  21291. Base class for an active instance of a plugin.
  21292. This derives from the AudioProcessor class, and adds some extra functionality
  21293. that helps when wrapping dynamically loaded plugins.
  21294. @see AudioProcessor, AudioPluginFormat
  21295. */
  21296. class JUCE_API AudioPluginInstance : public AudioProcessor
  21297. {
  21298. public:
  21299. /** Destructor.
  21300. Make sure that you delete any UI components that belong to this plugin before
  21301. deleting the plugin.
  21302. */
  21303. virtual ~AudioPluginInstance();
  21304. /** Fills-in the appropriate parts of this plugin description object.
  21305. */
  21306. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  21307. juce_UseDebuggingNewOperator
  21308. protected:
  21309. AudioPluginInstance();
  21310. AudioPluginInstance (const AudioPluginInstance&);
  21311. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  21312. };
  21313. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  21314. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  21315. class PluginDescription;
  21316. /**
  21317. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  21318. Use the static getNumFormats() and getFormat() calls to find the types
  21319. of format that are available.
  21320. */
  21321. class JUCE_API AudioPluginFormat
  21322. {
  21323. public:
  21324. /** Destructor. */
  21325. virtual ~AudioPluginFormat();
  21326. /** Returns the format name.
  21327. E.g. "VST", "AudioUnit", etc.
  21328. */
  21329. virtual const String getName() const = 0;
  21330. /** This tries to create descriptions for all the plugin types available in
  21331. a binary module file.
  21332. The file will be some kind of DLL or bundle.
  21333. Normally there will only be one type returned, but some plugins
  21334. (e.g. VST shells) can use a single DLL to create a set of different plugin
  21335. subtypes, so in that case, each subtype is returned as a separate object.
  21336. */
  21337. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  21338. const String& fileOrIdentifier) = 0;
  21339. /** Tries to recreate a type from a previously generated PluginDescription.
  21340. @see PluginDescription::createInstance
  21341. */
  21342. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  21343. /** Should do a quick check to see if this file or directory might be a plugin of
  21344. this format.
  21345. This is for searching for potential files, so it shouldn't actually try to
  21346. load the plugin or do anything time-consuming.
  21347. */
  21348. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  21349. /** Returns a readable version of the name of the plugin that this identifier refers to.
  21350. */
  21351. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  21352. /** Checks whether this plugin could possibly be loaded.
  21353. It doesn't actually need to load it, just to check whether the file or component
  21354. still exists.
  21355. */
  21356. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  21357. /** Searches a suggested set of directories for any plugins in this format.
  21358. The path might be ignored, e.g. by AUs, which are found by the OS rather
  21359. than manually.
  21360. */
  21361. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  21362. const bool recursive) = 0;
  21363. /** Returns the typical places to look for this kind of plugin.
  21364. Note that if this returns no paths, it means that the format can't be scanned-for
  21365. (i.e. it's an internal format that doesn't live in files)
  21366. */
  21367. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  21368. juce_UseDebuggingNewOperator
  21369. protected:
  21370. AudioPluginFormat() throw();
  21371. AudioPluginFormat (const AudioPluginFormat&);
  21372. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  21373. };
  21374. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  21375. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  21376. /**
  21377. This maintains a list of known AudioPluginFormats.
  21378. @see AudioPluginFormat
  21379. */
  21380. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  21381. {
  21382. public:
  21383. AudioPluginFormatManager() throw();
  21384. /** Destructor. */
  21385. ~AudioPluginFormatManager() throw();
  21386. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  21387. /** Adds any formats that it knows about, e.g. VST.
  21388. */
  21389. void addDefaultFormats();
  21390. /** Returns the number of types of format that are available.
  21391. Use getFormat() to get one of them.
  21392. */
  21393. int getNumFormats() throw();
  21394. /** Returns one of the available formats.
  21395. @see getNumFormats
  21396. */
  21397. AudioPluginFormat* getFormat (const int index) throw();
  21398. /** Adds a format to the list.
  21399. The object passed in will be owned and deleted by the manager.
  21400. */
  21401. void addFormat (AudioPluginFormat* const format) throw();
  21402. /** Tries to load the type for this description, by trying all the formats
  21403. that this manager knows about.
  21404. The caller is responsible for deleting the object that is returned.
  21405. If it can't load the plugin, it returns 0 and leaves a message in the
  21406. errorMessage string.
  21407. */
  21408. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  21409. String& errorMessage) const;
  21410. /** Checks that the file or component for this plugin actually still exists.
  21411. (This won't try to load the plugin)
  21412. */
  21413. bool doesPluginStillExist (const PluginDescription& description) const;
  21414. juce_UseDebuggingNewOperator
  21415. private:
  21416. OwnedArray <AudioPluginFormat> formats;
  21417. AudioPluginFormatManager (const AudioPluginFormatManager&);
  21418. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  21419. };
  21420. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  21421. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  21422. /********* Start of inlined file: juce_KnownPluginList.h *********/
  21423. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21424. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21425. /********* Start of inlined file: juce_PopupMenu.h *********/
  21426. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  21427. #define __JUCE_POPUPMENU_JUCEHEADER__
  21428. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  21429. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21430. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21431. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  21432. @see PopupMenu::addCustomItem
  21433. */
  21434. class JUCE_API PopupMenuCustomComponent : public Component
  21435. {
  21436. public:
  21437. /** Destructor. */
  21438. ~PopupMenuCustomComponent();
  21439. /** Chooses the size that this component would like to have.
  21440. Note that the size which this method returns isn't necessarily the one that
  21441. the menu will give it, as it will be stretched to fit the other items in
  21442. the menu.
  21443. */
  21444. virtual void getIdealSize (int& idealWidth,
  21445. int& idealHeight) = 0;
  21446. /** Dismisses the menu indicating that this item has been chosen.
  21447. This will cause the menu to exit from its modal state, returning
  21448. this item's id as the result.
  21449. */
  21450. void triggerMenuItem();
  21451. /** Returns true if this item should be highlighted because the mouse is
  21452. over it.
  21453. You can call this method in your paint() method to find out whether
  21454. to draw a highlight.
  21455. */
  21456. bool isItemHighlighted() const throw() { return isHighlighted; }
  21457. protected:
  21458. /** Constructor.
  21459. If isTriggeredAutomatically is true, then the menu will automatically detect
  21460. a click on this component and use that to trigger it. If it's false, then it's
  21461. up to your class to manually trigger the item if it wants to.
  21462. */
  21463. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  21464. private:
  21465. friend class MenuItemInfo;
  21466. friend class MenuItemComponent;
  21467. friend class PopupMenuWindow;
  21468. int refCount_;
  21469. bool isHighlighted, isTriggeredAutomatically;
  21470. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  21471. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  21472. };
  21473. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  21474. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  21475. /** Creates and displays a popup-menu.
  21476. To show a popup-menu, you create one of these, add some items to it, then
  21477. call its show() method, which returns the id of the item the user selects.
  21478. E.g. @code
  21479. void MyWidget::mouseDown (const MouseEvent& e)
  21480. {
  21481. PopupMenu m;
  21482. m.addItem (1, "item 1");
  21483. m.addItem (2, "item 2");
  21484. const int result = m.show();
  21485. if (result == 0)
  21486. {
  21487. // user dismissed the menu without picking anything
  21488. }
  21489. else if (result == 1)
  21490. {
  21491. // user picked item 1
  21492. }
  21493. else if (result == 2)
  21494. {
  21495. // user picked item 2
  21496. }
  21497. }
  21498. @endcode
  21499. Submenus are easy too: @code
  21500. void MyWidget::mouseDown (const MouseEvent& e)
  21501. {
  21502. PopupMenu subMenu;
  21503. subMenu.addItem (1, "item 1");
  21504. subMenu.addItem (2, "item 2");
  21505. PopupMenu mainMenu;
  21506. mainMenu.addItem (3, "item 3");
  21507. mainMenu.addSubMenu ("other choices", subMenu);
  21508. const int result = m.show();
  21509. ...etc
  21510. }
  21511. @endcode
  21512. */
  21513. class JUCE_API PopupMenu
  21514. {
  21515. public:
  21516. /** Creates an empty popup menu. */
  21517. PopupMenu() throw();
  21518. /** Creates a copy of another menu. */
  21519. PopupMenu (const PopupMenu& other) throw();
  21520. /** Destructor. */
  21521. ~PopupMenu() throw();
  21522. /** Copies this menu from another one. */
  21523. const PopupMenu& operator= (const PopupMenu& other) throw();
  21524. /** Resets the menu, removing all its items. */
  21525. void clear() throw();
  21526. /** Appends a new text item for this menu to show.
  21527. @param itemResultId the number that will be returned from the show() method
  21528. if the user picks this item. The value should never be
  21529. zero, because that's used to indicate that the user didn't
  21530. select anything.
  21531. @param itemText the text to show.
  21532. @param isActive if false, the item will be shown 'greyed-out' and can't be
  21533. picked
  21534. @param isTicked if true, the item will be shown with a tick next to it
  21535. @param iconToUse if this is non-zero, it should be an image that will be
  21536. displayed to the left of the item. This method will take its
  21537. own copy of the image passed-in, so there's no need to keep
  21538. it hanging around.
  21539. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  21540. */
  21541. void addItem (const int itemResultId,
  21542. const String& itemText,
  21543. const bool isActive = true,
  21544. const bool isTicked = false,
  21545. const Image* const iconToUse = 0) throw();
  21546. /** Adds an item that represents one of the commands in a command manager object.
  21547. @param commandManager the manager to use to trigger the command and get information
  21548. about it
  21549. @param commandID the ID of the command
  21550. @param displayName if this is non-empty, then this string will be used instead of
  21551. the command's registered name
  21552. */
  21553. void addCommandItem (ApplicationCommandManager* commandManager,
  21554. const int commandID,
  21555. const String& displayName = String::empty) throw();
  21556. /** Appends a text item with a special colour.
  21557. This is the same as addItem(), but specifies a colour to use for the
  21558. text, which will override the default colours that are used by the
  21559. current look-and-feel. See addItem() for a description of the parameters.
  21560. */
  21561. void addColouredItem (const int itemResultId,
  21562. const String& itemText,
  21563. const Colour& itemTextColour,
  21564. const bool isActive = true,
  21565. const bool isTicked = false,
  21566. const Image* const iconToUse = 0) throw();
  21567. /** Appends a custom menu item.
  21568. This will add a user-defined component to use as a menu item. The component
  21569. passed in will be deleted by this menu when it's no longer needed.
  21570. @see PopupMenuCustomComponent
  21571. */
  21572. void addCustomItem (const int itemResultId,
  21573. PopupMenuCustomComponent* const customComponent) throw();
  21574. /** Appends a custom menu item that can't be used to trigger a result.
  21575. This will add a user-defined component to use as a menu item. Unlike the
  21576. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  21577. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  21578. delete the component when it's finished, so it's the caller's responsibility
  21579. to manage the component that is passed-in.
  21580. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  21581. detection of a mouse-click on your component, and use that to trigger the
  21582. menu ID specified in itemResultId. If this is false, the menu item can't
  21583. be triggered, so itemResultId is not used.
  21584. @see PopupMenuCustomComponent
  21585. */
  21586. void addCustomItem (const int itemResultId,
  21587. Component* customComponent,
  21588. int idealWidth, int idealHeight,
  21589. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  21590. /** Appends a sub-menu.
  21591. If the menu that's passed in is empty, it will appear as an inactive item.
  21592. */
  21593. void addSubMenu (const String& subMenuName,
  21594. const PopupMenu& subMenu,
  21595. const bool isActive = true,
  21596. Image* const iconToUse = 0,
  21597. const bool isTicked = false) throw();
  21598. /** Appends a separator to the menu, to help break it up into sections.
  21599. The menu class is smart enough not to display separators at the top or bottom
  21600. of the menu, and it will replace mutliple adjacent separators with a single
  21601. one, so your code can be quite free and easy about adding these, and it'll
  21602. always look ok.
  21603. */
  21604. void addSeparator() throw();
  21605. /** Adds a non-clickable text item to the menu.
  21606. This is a bold-font items which can be used as a header to separate the items
  21607. into named groups.
  21608. */
  21609. void addSectionHeader (const String& title) throw();
  21610. /** Returns the number of items that the menu currently contains.
  21611. (This doesn't count separators).
  21612. */
  21613. int getNumItems() const throw();
  21614. /** Returns true if the menu contains a command item that triggers the given command. */
  21615. bool containsCommandItem (const int commandID) const throw();
  21616. /** Returns true if the menu contains any items that can be used. */
  21617. bool containsAnyActiveItems() const throw();
  21618. /** Displays the menu and waits for the user to pick something.
  21619. This will display the menu modally, and return the ID of the item that the
  21620. user picks. If they click somewhere off the menu to get rid of it without
  21621. choosing anything, this will return 0.
  21622. The current location of the mouse will be used as the position to show the
  21623. menu - to explicitly set the menu's position, use showAt() instead. Depending
  21624. on where this point is on the screen, the menu will appear above, below or
  21625. to the side of the point.
  21626. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  21627. then when the menu first appears, it will make sure
  21628. that this item is visible. So if the menu has too many
  21629. items to fit on the screen, it will be scrolled to a
  21630. position where this item is visible.
  21631. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  21632. than this if some items are too long to fit.
  21633. @param maximumNumColumns if there are too many items to fit on-screen in a single
  21634. vertical column, the menu may be laid out as a series of
  21635. columns - this is the maximum number allowed. To use the
  21636. default value for this (probably about 7), you can pass
  21637. in zero.
  21638. @param standardItemHeight if this is non-zero, it will be used as the standard
  21639. height for menu items (apart from custom items)
  21640. @see showAt
  21641. */
  21642. int show (const int itemIdThatMustBeVisible = 0,
  21643. const int minimumWidth = 0,
  21644. const int maximumNumColumns = 0,
  21645. const int standardItemHeight = 0);
  21646. /** Displays the menu at a specific location.
  21647. This is the same as show(), but uses a specific location (in global screen
  21648. co-ordinates) rather than the current mouse position.
  21649. Note that the co-ordinates don't specify the top-left of the menu - they
  21650. indicate a point of interest, and the menu will position itself nearby to
  21651. this point, trying to keep it fully on-screen.
  21652. @see show()
  21653. */
  21654. int showAt (const int screenX,
  21655. const int screenY,
  21656. const int itemIdThatMustBeVisible = 0,
  21657. const int minimumWidth = 0,
  21658. const int maximumNumColumns = 0,
  21659. const int standardItemHeight = 0);
  21660. /** Displays the menu as if it's attached to a component such as a button.
  21661. This is similar to showAt(), but will position it next to the given component, e.g.
  21662. so that the menu's edge is aligned with that of the component. This is intended for
  21663. things like buttons that trigger a pop-up menu.
  21664. */
  21665. int showAt (Component* componentToAttachTo,
  21666. const int itemIdThatMustBeVisible = 0,
  21667. const int minimumWidth = 0,
  21668. const int maximumNumColumns = 0,
  21669. const int standardItemHeight = 0);
  21670. /** Closes any menus that are currently open.
  21671. This might be useful if you have a situation where your window is being closed
  21672. by some means other than a user action, and you'd like to make sure that menus
  21673. aren't left hanging around.
  21674. */
  21675. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  21676. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  21677. This can be called before show() if you need a customised menu. Be careful
  21678. not to delete the LookAndFeel object before the menu has been deleted.
  21679. */
  21680. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  21681. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  21682. These constants can be used either via the LookAndFeel::setColour()
  21683. method for the look and feel that is set for this menu with setLookAndFeel()
  21684. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  21685. */
  21686. enum ColourIds
  21687. {
  21688. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  21689. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  21690. colour is specified when the item is added). */
  21691. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  21692. addSectionHeader() method). */
  21693. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  21694. highlighted menu item. */
  21695. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  21696. highlighted item. */
  21697. };
  21698. /**
  21699. Allows you to iterate through the items in a pop-up menu, and examine
  21700. their properties.
  21701. To use this, just create one and repeatedly call its next() method. When this
  21702. returns true, all the member variables of the iterator are filled-out with
  21703. information describing the menu item. When it returns false, the end of the
  21704. list has been reached.
  21705. */
  21706. class JUCE_API MenuItemIterator
  21707. {
  21708. public:
  21709. /** Creates an iterator that will scan through the items in the specified
  21710. menu.
  21711. Be careful not to add any items to a menu while it is being iterated,
  21712. or things could get out of step.
  21713. */
  21714. MenuItemIterator (const PopupMenu& menu) throw();
  21715. /** Destructor. */
  21716. ~MenuItemIterator() throw();
  21717. /** Returns true if there is another item, and sets up all this object's
  21718. member variables to reflect that item's properties.
  21719. */
  21720. bool next() throw();
  21721. String itemName;
  21722. const PopupMenu* subMenu;
  21723. int itemId;
  21724. bool isSeparator;
  21725. bool isTicked;
  21726. bool isEnabled;
  21727. bool isCustomComponent;
  21728. bool isSectionHeader;
  21729. const Colour* customColour;
  21730. const Image* customImage;
  21731. ApplicationCommandManager* commandManager;
  21732. juce_UseDebuggingNewOperator
  21733. private:
  21734. const PopupMenu& menu;
  21735. int index;
  21736. MenuItemIterator (const MenuItemIterator&);
  21737. const MenuItemIterator& operator= (const MenuItemIterator&);
  21738. };
  21739. juce_UseDebuggingNewOperator
  21740. private:
  21741. friend class PopupMenuWindow;
  21742. friend class MenuItemIterator;
  21743. VoidArray items;
  21744. LookAndFeel* lookAndFeel;
  21745. bool separatorPending;
  21746. void addSeparatorIfPending();
  21747. int showMenu (const int x, const int y, const int w, const int h,
  21748. const int itemIdThatMustBeVisible,
  21749. const int minimumWidth,
  21750. const int maximumNumColumns,
  21751. const int standardItemHeight,
  21752. const bool alignToRectangle,
  21753. Component* const componentAttachedTo) throw();
  21754. friend class MenuBarComponent;
  21755. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  21756. const int itemIdThatMustBeVisible,
  21757. const int minimumWidth,
  21758. const int maximumNumColumns,
  21759. const int standardItemHeight,
  21760. const bool alignToRectangle,
  21761. Component* menuBarComponent,
  21762. ApplicationCommandManager** managerOfChosenCommand,
  21763. Component* const componentAttachedTo) throw();
  21764. };
  21765. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  21766. /********* End of inlined file: juce_PopupMenu.h *********/
  21767. /**
  21768. Manages a list of plugin types.
  21769. This can be easily edited, saved and loaded, and used to create instances of
  21770. the plugin types in it.
  21771. @see PluginListComponent
  21772. */
  21773. class JUCE_API KnownPluginList : public ChangeBroadcaster
  21774. {
  21775. public:
  21776. /** Creates an empty list.
  21777. */
  21778. KnownPluginList();
  21779. /** Destructor. */
  21780. ~KnownPluginList();
  21781. /** Clears the list. */
  21782. void clear();
  21783. /** Returns the number of types currently in the list.
  21784. @see getType
  21785. */
  21786. int getNumTypes() const throw() { return types.size(); }
  21787. /** Returns one of the types.
  21788. @see getNumTypes
  21789. */
  21790. PluginDescription* getType (const int index) const throw() { return types [index]; }
  21791. /** Looks for a type in the list which comes from this file.
  21792. */
  21793. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  21794. /** Looks for a type in the list which matches a plugin type ID.
  21795. The identifierString parameter must have been created by
  21796. PluginDescription::createIdentifierString().
  21797. */
  21798. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  21799. /** Adds a type manually from its description. */
  21800. bool addType (const PluginDescription& type);
  21801. /** Removes a type. */
  21802. void removeType (const int index) throw();
  21803. /** Looks for all types that can be loaded from a given file, and adds them
  21804. to the list.
  21805. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  21806. re-tested if it's not already in the list, or if the file's modification
  21807. time has changed since the list was created. If dontRescanIfAlreadyInList is
  21808. false, the file will always be reloaded and tested.
  21809. Returns true if any new types were added, and all the types found in this
  21810. file (even if it was already known and hasn't been re-scanned) get returned
  21811. in the array.
  21812. */
  21813. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  21814. const bool dontRescanIfAlreadyInList,
  21815. OwnedArray <PluginDescription>& typesFound,
  21816. AudioPluginFormat& formatToUse);
  21817. /** Returns true if the specified file is already known about and if it
  21818. hasn't been modified since our entry was created.
  21819. */
  21820. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  21821. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  21822. If any types are found in the files, their descriptions are returned in the array.
  21823. */
  21824. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  21825. OwnedArray <PluginDescription>& typesFound);
  21826. /** Sort methods used to change the order of the plugins in the list.
  21827. */
  21828. enum SortMethod
  21829. {
  21830. defaultOrder = 0,
  21831. sortAlphabetically,
  21832. sortByCategory,
  21833. sortByManufacturer,
  21834. sortByFileSystemLocation
  21835. };
  21836. /** Adds all the plugin types to a popup menu so that the user can select one.
  21837. Depending on the sort method, it may add sub-menus for categories,
  21838. manufacturers, etc.
  21839. Use getIndexChosenByMenu() to find out the type that was chosen.
  21840. */
  21841. void addToMenu (PopupMenu& menu,
  21842. const SortMethod sortMethod) const;
  21843. /** Converts a menu item index that has been chosen into its index in this list.
  21844. Returns -1 if it's not an ID that was used.
  21845. @see addToMenu
  21846. */
  21847. int getIndexChosenByMenu (const int menuResultCode) const;
  21848. /** Sorts the list. */
  21849. void sort (const SortMethod method);
  21850. /** Creates some XML that can be used to store the state of this list.
  21851. */
  21852. XmlElement* createXml() const;
  21853. /** Recreates the state of this list from its stored XML format.
  21854. */
  21855. void recreateFromXml (const XmlElement& xml);
  21856. juce_UseDebuggingNewOperator
  21857. private:
  21858. OwnedArray <PluginDescription> types;
  21859. KnownPluginList (const KnownPluginList&);
  21860. const KnownPluginList& operator= (const KnownPluginList&);
  21861. };
  21862. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  21863. /********* End of inlined file: juce_KnownPluginList.h *********/
  21864. /**
  21865. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  21866. Use one of these objects if you want to wire-up a set of AudioProcessors
  21867. and play back the result.
  21868. Processors can be added to the graph as "nodes" using addNode(), and once
  21869. added, you can connect any of their input or output channels to other
  21870. nodes using addConnection().
  21871. To play back a graph through an audio device, you might want to use an
  21872. AudioProcessorPlayer object.
  21873. */
  21874. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  21875. public AsyncUpdater
  21876. {
  21877. public:
  21878. /** Creates an empty graph.
  21879. */
  21880. AudioProcessorGraph();
  21881. /** Destructor.
  21882. Any processor objects that have been added to the graph will also be deleted.
  21883. */
  21884. ~AudioProcessorGraph();
  21885. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  21886. To create a node, call AudioProcessorGraph::addNode().
  21887. */
  21888. class JUCE_API Node : public ReferenceCountedObject
  21889. {
  21890. public:
  21891. /** Destructor.
  21892. */
  21893. ~Node();
  21894. /** The ID number assigned to this node.
  21895. This is assigned by the graph that owns it, and can't be changed.
  21896. */
  21897. const uint32 id;
  21898. /** The actual processor object that this node represents.
  21899. */
  21900. AudioProcessor* const processor;
  21901. /** A set of user-definable properties that are associated with this node.
  21902. This can be used to attach values to the node for whatever purpose seems
  21903. useful. For example, you might store an x and y position if your application
  21904. is displaying the nodes on-screen.
  21905. */
  21906. PropertySet properties;
  21907. /** A convenient typedef for referring to a pointer to a node object.
  21908. */
  21909. typedef ReferenceCountedObjectPtr <Node> Ptr;
  21910. juce_UseDebuggingNewOperator
  21911. private:
  21912. friend class AudioProcessorGraph;
  21913. bool isPrepared;
  21914. Node (const uint32 id, AudioProcessor* const processor) throw();
  21915. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  21916. void unprepare();
  21917. Node (const Node&);
  21918. const Node& operator= (const Node&);
  21919. };
  21920. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  21921. To create a connection, use AudioProcessorGraph::addConnection().
  21922. */
  21923. struct JUCE_API Connection
  21924. {
  21925. public:
  21926. /** The ID number of the node which is the input source for this connection.
  21927. @see AudioProcessorGraph::getNodeForId
  21928. */
  21929. uint32 sourceNodeId;
  21930. /** The index of the output channel of the source node from which this
  21931. connection takes its data.
  21932. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21933. it is referring to the source node's midi output. Otherwise, it is the zero-based
  21934. index of an audio output channel in the source node.
  21935. */
  21936. int sourceChannelIndex;
  21937. /** The ID number of the node which is the destination for this connection.
  21938. @see AudioProcessorGraph::getNodeForId
  21939. */
  21940. uint32 destNodeId;
  21941. /** The index of the input channel of the destination node to which this
  21942. connection delivers its data.
  21943. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  21944. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  21945. index of an audio input channel in the destination node.
  21946. */
  21947. int destChannelIndex;
  21948. juce_UseDebuggingNewOperator
  21949. private:
  21950. };
  21951. /** Deletes all nodes and connections from this graph.
  21952. Any processor objects in the graph will be deleted.
  21953. */
  21954. void clear();
  21955. /** Returns the number of nodes in the graph. */
  21956. int getNumNodes() const throw() { return nodes.size(); }
  21957. /** Returns a pointer to one of the nodes in the graph.
  21958. This will return 0 if the index is out of range.
  21959. @see getNodeForId
  21960. */
  21961. Node* getNode (const int index) const throw() { return nodes [index]; }
  21962. /** Searches the graph for a node with the given ID number and returns it.
  21963. If no such node was found, this returns 0.
  21964. @see getNode
  21965. */
  21966. Node* getNodeForId (const uint32 nodeId) const throw();
  21967. /** Adds a node to the graph.
  21968. This creates a new node in the graph, for the specified processor. Once you have
  21969. added a processor to the graph, the graph owns it and will delete it later when
  21970. it is no longer needed.
  21971. The optional nodeId parameter lets you specify an ID to use for the node, but
  21972. if the value is already in use, this new node will overwrite the old one.
  21973. If this succeeds, it returns a pointer to the newly-created node.
  21974. */
  21975. Node* addNode (AudioProcessor* const newProcessor,
  21976. uint32 nodeId = 0);
  21977. /** Deletes a node within the graph which has the specified ID.
  21978. This will also delete any connections that are attached to this node.
  21979. */
  21980. bool removeNode (const uint32 nodeId);
  21981. /** Returns the number of connections in the graph. */
  21982. int getNumConnections() const throw() { return connections.size(); }
  21983. /** Returns a pointer to one of the connections in the graph. */
  21984. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  21985. /** Searches for a connection between some specified channels.
  21986. If no such connection is found, this returns 0.
  21987. */
  21988. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  21989. const int sourceChannelIndex,
  21990. const uint32 destNodeId,
  21991. const int destChannelIndex) const throw();
  21992. /** Returns true if there is a connection between any of the channels of
  21993. two specified nodes.
  21994. */
  21995. bool isConnected (const uint32 possibleSourceNodeId,
  21996. const uint32 possibleDestNodeId) const throw();
  21997. /** Returns true if it would be legal to connect the specified points.
  21998. */
  21999. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  22000. const uint32 destNodeId, const int destChannelIndex) const throw();
  22001. /** Attempts to connect two specified channels of two nodes.
  22002. If this isn't allowed (e.g. because you're trying to connect a midi channel
  22003. to an audio one or other such nonsense), then it'll return false.
  22004. */
  22005. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  22006. const uint32 destNodeId, const int destChannelIndex);
  22007. /** Deletes the connection with the specified index.
  22008. Returns true if a connection was actually deleted.
  22009. */
  22010. void removeConnection (const int index);
  22011. /** Deletes any connection between two specified points.
  22012. Returns true if a connection was actually deleted.
  22013. */
  22014. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  22015. const uint32 destNodeId, const int destChannelIndex);
  22016. /** Removes all connections from the specified node.
  22017. */
  22018. bool disconnectNode (const uint32 nodeId);
  22019. /** Performs a sanity checks of all the connections.
  22020. This might be useful if some of the processors are doing things like changing
  22021. their channel counts, which could render some connections obsolete.
  22022. */
  22023. bool removeIllegalConnections();
  22024. /** A special number that represents the midi channel of a node.
  22025. This is used as a channel index value if you want to refer to the midi input
  22026. or output instead of an audio channel.
  22027. */
  22028. static const int midiChannelIndex;
  22029. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  22030. in order to use the audio that comes into and out of the graph itself.
  22031. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  22032. node in the graph which delivers the audio that is coming into the parent
  22033. graph. This allows you to stream the data to other nodes and process the
  22034. incoming audio.
  22035. Likewise, one of these in "output" mode can be sent data which it will add to
  22036. the sum of data being sent to the graph's output.
  22037. @see AudioProcessorGraph
  22038. */
  22039. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  22040. {
  22041. public:
  22042. /** Specifies the mode in which this processor will operate.
  22043. */
  22044. enum IODeviceType
  22045. {
  22046. audioInputNode, /**< In this mode, the processor has output channels
  22047. representing all the audio input channels that are
  22048. coming into its parent audio graph. */
  22049. audioOutputNode, /**< In this mode, the processor has input channels
  22050. representing all the audio output channels that are
  22051. going out of its parent audio graph. */
  22052. midiInputNode, /**< In this mode, the processor has a midi output which
  22053. delivers the same midi data that is arriving at its
  22054. parent graph. */
  22055. midiOutputNode /**< In this mode, the processor has a midi input and
  22056. any data sent to it will be passed out of the parent
  22057. graph. */
  22058. };
  22059. /** Returns the mode of this processor. */
  22060. IODeviceType getType() const throw() { return type; }
  22061. /** Returns the parent graph to which this processor belongs, or 0 if it
  22062. hasn't yet been added to one. */
  22063. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  22064. /** True if this is an audio or midi input. */
  22065. bool isInput() const throw();
  22066. /** True if this is an audio or midi output. */
  22067. bool isOutput() const throw();
  22068. AudioGraphIOProcessor (const IODeviceType type);
  22069. ~AudioGraphIOProcessor();
  22070. const String getName() const;
  22071. void fillInPluginDescription (PluginDescription& d) const;
  22072. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22073. void releaseResources();
  22074. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  22075. const String getInputChannelName (const int channelIndex) const;
  22076. const String getOutputChannelName (const int channelIndex) const;
  22077. bool isInputChannelStereoPair (int index) const;
  22078. bool isOutputChannelStereoPair (int index) const;
  22079. bool acceptsMidi() const;
  22080. bool producesMidi() const;
  22081. AudioProcessorEditor* createEditor();
  22082. int getNumParameters();
  22083. const String getParameterName (int);
  22084. float getParameter (int);
  22085. const String getParameterText (int);
  22086. void setParameter (int, float);
  22087. int getNumPrograms();
  22088. int getCurrentProgram();
  22089. void setCurrentProgram (int);
  22090. const String getProgramName (int);
  22091. void changeProgramName (int, const String&);
  22092. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  22093. void setStateInformation (const void* data, int sizeInBytes);
  22094. /** @internal */
  22095. void setParentGraph (AudioProcessorGraph* const graph) throw();
  22096. juce_UseDebuggingNewOperator
  22097. private:
  22098. const IODeviceType type;
  22099. AudioProcessorGraph* graph;
  22100. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  22101. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  22102. };
  22103. // AudioProcessor methods:
  22104. const String getName() const;
  22105. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22106. void releaseResources();
  22107. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  22108. const String getInputChannelName (const int channelIndex) const;
  22109. const String getOutputChannelName (const int channelIndex) const;
  22110. bool isInputChannelStereoPair (int index) const;
  22111. bool isOutputChannelStereoPair (int index) const;
  22112. bool acceptsMidi() const;
  22113. bool producesMidi() const;
  22114. AudioProcessorEditor* createEditor() { return 0; }
  22115. int getNumParameters() { return 0; }
  22116. const String getParameterName (int) { return String::empty; }
  22117. float getParameter (int) { return 0; }
  22118. const String getParameterText (int) { return String::empty; }
  22119. void setParameter (int, float) { }
  22120. int getNumPrograms() { return 0; }
  22121. int getCurrentProgram() { return 0; }
  22122. void setCurrentProgram (int) { }
  22123. const String getProgramName (int) { return String::empty; }
  22124. void changeProgramName (int, const String&) { }
  22125. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  22126. void setStateInformation (const void* data, int sizeInBytes);
  22127. /** @internal */
  22128. void handleAsyncUpdate();
  22129. juce_UseDebuggingNewOperator
  22130. private:
  22131. ReferenceCountedArray <Node> nodes;
  22132. OwnedArray <Connection> connections;
  22133. int lastNodeId;
  22134. AudioSampleBuffer renderingBuffers;
  22135. OwnedArray <MidiBuffer> midiBuffers;
  22136. CriticalSection renderLock;
  22137. VoidArray renderingOps;
  22138. friend class AudioGraphIOProcessor;
  22139. AudioSampleBuffer* currentAudioInputBuffer;
  22140. AudioSampleBuffer currentAudioOutputBuffer;
  22141. MidiBuffer* currentMidiInputBuffer;
  22142. MidiBuffer currentMidiOutputBuffer;
  22143. void clearRenderingSequence();
  22144. void buildRenderingSequence();
  22145. bool isAnInputTo (const uint32 possibleInputId,
  22146. const uint32 possibleDestinationId,
  22147. const int recursionCheck) const throw();
  22148. AudioProcessorGraph (const AudioProcessorGraph&);
  22149. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  22150. };
  22151. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  22152. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  22153. #endif
  22154. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  22155. #endif
  22156. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22157. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  22158. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22159. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22160. /********* Start of inlined file: juce_AudioIODevice.h *********/
  22161. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22162. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22163. class AudioIODevice;
  22164. /**
  22165. One of these is passed to an AudioIODevice object to stream the audio data
  22166. in and out.
  22167. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  22168. method on its own high-priority audio thread, when it needs to send or receive
  22169. the next block of data.
  22170. @see AudioIODevice, AudioDeviceManager
  22171. */
  22172. class JUCE_API AudioIODeviceCallback
  22173. {
  22174. public:
  22175. /** Destructor. */
  22176. virtual ~AudioIODeviceCallback() {}
  22177. /** Processes a block of incoming and outgoing audio data.
  22178. The subclass's implementation should use the incoming audio for whatever
  22179. purposes it needs to, and must fill all the output channels with the next
  22180. block of output data before returning.
  22181. The channel data is arranged with the same array indices as the channel name
  22182. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  22183. that aren't specified in AudioIODevice::open() will have a null pointer for their
  22184. associated channel, so remember to check for this.
  22185. @param inputChannelData a set of arrays containing the audio data for each
  22186. incoming channel - this data is valid until the function
  22187. returns. There will be one channel of data for each input
  22188. channel that was enabled when the audio device was opened
  22189. (see AudioIODevice::open())
  22190. @param numInputChannels the number of pointers to channel data in the
  22191. inputChannelData array.
  22192. @param outputChannelData a set of arrays which need to be filled with the data
  22193. that should be sent to each outgoing channel of the device.
  22194. There will be one channel of data for each output channel
  22195. that was enabled when the audio device was opened (see
  22196. AudioIODevice::open())
  22197. The initial contents of the array is undefined, so the
  22198. callback function must fill all the channels with zeros if
  22199. its output is silence. Failing to do this could cause quite
  22200. an unpleasant noise!
  22201. @param numOutputChannels the number of pointers to channel data in the
  22202. outputChannelData array.
  22203. @param numSamples the number of samples in each channel of the input and
  22204. output arrays. The number of samples will depend on the
  22205. audio device's buffer size and will usually remain constant,
  22206. although this isn't guaranteed, so make sure your code can
  22207. cope with reasonable changes in the buffer size from one
  22208. callback to the next.
  22209. */
  22210. virtual void audioDeviceIOCallback (const float** inputChannelData,
  22211. int numInputChannels,
  22212. float** outputChannelData,
  22213. int numOutputChannels,
  22214. int numSamples) = 0;
  22215. /** Called to indicate that the device is about to start calling back.
  22216. This will be called just before the audio callbacks begin, either when this
  22217. callback has just been added to an audio device, or after the device has been
  22218. restarted because of a sample-rate or block-size change.
  22219. You can use this opportunity to find out the sample rate and block size
  22220. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  22221. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  22222. @param device the audio IO device that will be used to drive the callback.
  22223. Note that if you're going to store this this pointer, it is
  22224. only valid until the next time that audioDeviceStopped is called.
  22225. */
  22226. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  22227. /** Called to indicate that the device has stopped.
  22228. */
  22229. virtual void audioDeviceStopped() = 0;
  22230. };
  22231. /**
  22232. Base class for an audio device with synchronised input and output channels.
  22233. Subclasses of this are used to implement different protocols such as DirectSound,
  22234. ASIO, CoreAudio, etc.
  22235. To create one of these, you'll need to use the AudioIODeviceType class - see the
  22236. documentation for that class for more info.
  22237. For an easier way of managing audio devices and their settings, have a look at the
  22238. AudioDeviceManager class.
  22239. @see AudioIODeviceType, AudioDeviceManager
  22240. */
  22241. class JUCE_API AudioIODevice
  22242. {
  22243. public:
  22244. /** Destructor. */
  22245. virtual ~AudioIODevice();
  22246. /** Returns the device's name, (as set in the constructor). */
  22247. const String& getName() const throw() { return name; }
  22248. /** Returns the type of the device.
  22249. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  22250. */
  22251. const String& getTypeName() const throw() { return typeName; }
  22252. /** Returns the names of all the available output channels on this device.
  22253. To find out which of these are currently in use, call getActiveOutputChannels().
  22254. */
  22255. virtual const StringArray getOutputChannelNames() = 0;
  22256. /** Returns the names of all the available input channels on this device.
  22257. To find out which of these are currently in use, call getActiveInputChannels().
  22258. */
  22259. virtual const StringArray getInputChannelNames() = 0;
  22260. /** Returns the number of sample-rates this device supports.
  22261. To find out which rates are available on this device, use this method to
  22262. find out how many there are, and getSampleRate() to get the rates.
  22263. @see getSampleRate
  22264. */
  22265. virtual int getNumSampleRates() = 0;
  22266. /** Returns one of the sample-rates this device supports.
  22267. To find out which rates are available on this device, use getNumSampleRates() to
  22268. find out how many there are, and getSampleRate() to get the individual rates.
  22269. The sample rate is set by the open() method.
  22270. (Note that for DirectSound some rates might not work, depending on combinations
  22271. of i/o channels that are being opened).
  22272. @see getNumSampleRates
  22273. */
  22274. virtual double getSampleRate (int index) = 0;
  22275. /** Returns the number of sizes of buffer that are available.
  22276. @see getBufferSizeSamples, getDefaultBufferSize
  22277. */
  22278. virtual int getNumBufferSizesAvailable() = 0;
  22279. /** Returns one of the possible buffer-sizes.
  22280. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  22281. @returns a number of samples
  22282. @see getNumBufferSizesAvailable, getDefaultBufferSize
  22283. */
  22284. virtual int getBufferSizeSamples (int index) = 0;
  22285. /** Returns the default buffer-size to use.
  22286. @returns a number of samples
  22287. @see getNumBufferSizesAvailable, getBufferSizeSamples
  22288. */
  22289. virtual int getDefaultBufferSize() = 0;
  22290. /** Tries to open the device ready to play.
  22291. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  22292. input channel should be enabled
  22293. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  22294. output channel should be enabled
  22295. @param sampleRate the sample rate to try to use - to find out which rates are
  22296. available, see getNumSampleRates() and getSampleRate()
  22297. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  22298. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  22299. @returns an error description if there's a problem, or an empty string if it succeeds in
  22300. opening the device
  22301. @see close
  22302. */
  22303. virtual const String open (const BitArray& inputChannels,
  22304. const BitArray& outputChannels,
  22305. double sampleRate,
  22306. int bufferSizeSamples) = 0;
  22307. /** Closes and releases the device if it's open. */
  22308. virtual void close() = 0;
  22309. /** Returns true if the device is still open.
  22310. A device might spontaneously close itself if something goes wrong, so this checks if
  22311. it's still open.
  22312. */
  22313. virtual bool isOpen() = 0;
  22314. /** Starts the device actually playing.
  22315. This must be called after the device has been opened.
  22316. @param callback the callback to use for streaming the data.
  22317. @see AudioIODeviceCallback, open
  22318. */
  22319. virtual void start (AudioIODeviceCallback* callback) = 0;
  22320. /** Stops the device playing.
  22321. Once a device has been started, this will stop it. Any pending calls to the
  22322. callback class will be flushed before this method returns.
  22323. */
  22324. virtual void stop() = 0;
  22325. /** Returns true if the device is still calling back.
  22326. The device might mysteriously stop, so this checks whether it's
  22327. still playing.
  22328. */
  22329. virtual bool isPlaying() = 0;
  22330. /** Returns the last error that happened if anything went wrong. */
  22331. virtual const String getLastError() = 0;
  22332. /** Returns the buffer size that the device is currently using.
  22333. If the device isn't actually open, this value doesn't really mean much.
  22334. */
  22335. virtual int getCurrentBufferSizeSamples() = 0;
  22336. /** Returns the sample rate that the device is currently using.
  22337. If the device isn't actually open, this value doesn't really mean much.
  22338. */
  22339. virtual double getCurrentSampleRate() = 0;
  22340. /** Returns the device's current physical bit-depth.
  22341. If the device isn't actually open, this value doesn't really mean much.
  22342. */
  22343. virtual int getCurrentBitDepth() = 0;
  22344. /** Returns a mask showing which of the available output channels are currently
  22345. enabled.
  22346. @see getOutputChannelNames
  22347. */
  22348. virtual const BitArray getActiveOutputChannels() const = 0;
  22349. /** Returns a mask showing which of the available input channels are currently
  22350. enabled.
  22351. @see getInputChannelNames
  22352. */
  22353. virtual const BitArray getActiveInputChannels() const = 0;
  22354. /** Returns the device's output latency.
  22355. This is the delay in samples between a callback getting a block of data, and
  22356. that data actually getting played.
  22357. */
  22358. virtual int getOutputLatencyInSamples() = 0;
  22359. /** Returns the device's input latency.
  22360. This is the delay in samples between some audio actually arriving at the soundcard,
  22361. and the callback getting passed this block of data.
  22362. */
  22363. virtual int getInputLatencyInSamples() = 0;
  22364. /** True if this device can show a pop-up control panel for editing its settings.
  22365. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  22366. to display it.
  22367. */
  22368. virtual bool hasControlPanel() const;
  22369. /** Shows a device-specific control panel if there is one.
  22370. This should only be called for devices which return true from hasControlPanel().
  22371. */
  22372. virtual bool showControlPanel();
  22373. protected:
  22374. /** Creates a device, setting its name and type member variables. */
  22375. AudioIODevice (const String& deviceName,
  22376. const String& typeName);
  22377. /** @internal */
  22378. String name, typeName;
  22379. };
  22380. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22381. /********* End of inlined file: juce_AudioIODevice.h *********/
  22382. /**
  22383. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  22384. To use one of these, just make it the callback used by your AudioIODevice, and
  22385. give it a processor to use by calling setProcessor().
  22386. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  22387. input to send both streams through the processor.
  22388. @see AudioProcessor, AudioProcessorGraph
  22389. */
  22390. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  22391. public MidiInputCallback
  22392. {
  22393. public:
  22394. /**
  22395. */
  22396. AudioProcessorPlayer();
  22397. /** Destructor. */
  22398. virtual ~AudioProcessorPlayer();
  22399. /** Sets the processor that should be played.
  22400. The processor that is passed in will not be deleted or owned by this object.
  22401. To stop anything playing, pass in 0 to this method.
  22402. */
  22403. void setProcessor (AudioProcessor* const processorToPlay);
  22404. /** Returns the current audio processor that is being played.
  22405. */
  22406. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  22407. /** Returns a midi message collector that you can pass midi messages to if you
  22408. want them to be injected into the midi stream that is being sent to the
  22409. processor.
  22410. */
  22411. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  22412. /** @internal */
  22413. void audioDeviceIOCallback (const float** inputChannelData,
  22414. int totalNumInputChannels,
  22415. float** outputChannelData,
  22416. int totalNumOutputChannels,
  22417. int numSamples);
  22418. /** @internal */
  22419. void audioDeviceAboutToStart (AudioIODevice* device);
  22420. /** @internal */
  22421. void audioDeviceStopped();
  22422. /** @internal */
  22423. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  22424. juce_UseDebuggingNewOperator
  22425. private:
  22426. AudioProcessor* processor;
  22427. CriticalSection lock;
  22428. double sampleRate;
  22429. int blockSize;
  22430. bool isPrepared;
  22431. int numInputChans, numOutputChans;
  22432. float* channels [128];
  22433. AudioSampleBuffer tempBuffer;
  22434. MidiBuffer incomingMidi;
  22435. MidiMessageCollector messageCollector;
  22436. AudioProcessorPlayer (const AudioProcessorPlayer&);
  22437. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  22438. };
  22439. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  22440. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  22441. #endif
  22442. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22443. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  22444. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22445. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  22446. /********* Start of inlined file: juce_PropertyPanel.h *********/
  22447. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  22448. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  22449. /********* Start of inlined file: juce_PropertyComponent.h *********/
  22450. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22451. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22452. class EditableProperty;
  22453. /**
  22454. A base class for a component that goes in a PropertyPanel and displays one of
  22455. an item's properties.
  22456. Subclasses of this are used to display a property in various forms, e.g. a
  22457. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  22458. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  22459. A subclass must implement the refresh() method which will be called to tell the
  22460. component to update itself, and is also responsible for calling this it when the
  22461. item that it refers to is changed.
  22462. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  22463. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  22464. */
  22465. class JUCE_API PropertyComponent : public Component
  22466. {
  22467. public:
  22468. /** Creates a PropertyComponent.
  22469. @param propertyName the name is stored as this component's name, and is
  22470. used as the name displayed next to this component in
  22471. a property panel
  22472. @param preferredHeight the height that the component should be given - some
  22473. items may need to be larger than a normal row height.
  22474. This value can also be set if a subclass changes the
  22475. preferredHeight member variable.
  22476. */
  22477. PropertyComponent (const String& propertyName,
  22478. const int preferredHeight = 25);
  22479. /** Destructor. */
  22480. ~PropertyComponent();
  22481. /** Returns this item's preferred height.
  22482. This value is specified either in the constructor or by a subclass changing the
  22483. preferredHeight member variable.
  22484. */
  22485. int getPreferredHeight() const throw() { return preferredHeight; }
  22486. /** Updates the property component if the item it refers to has changed.
  22487. A subclass must implement this method, and other objects may call it to
  22488. force it to refresh itself.
  22489. The subclass should be economical in the amount of work is done, so for
  22490. example it should check whether it really needs to do a repaint rather than
  22491. just doing one every time this method is called, as it may be called when
  22492. the value being displayed hasn't actually changed.
  22493. */
  22494. virtual void refresh() = 0;
  22495. /** The default paint method fills the background and draws a label for the
  22496. item's name.
  22497. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  22498. */
  22499. void paint (Graphics& g);
  22500. /** The default resize method positions any child component to the right of this
  22501. one, based on the look and feel's default label size.
  22502. */
  22503. void resized();
  22504. /** By default, this just repaints the component. */
  22505. void enablementChanged();
  22506. juce_UseDebuggingNewOperator
  22507. protected:
  22508. /** Used by the PropertyPanel to determine how high this component needs to be.
  22509. A subclass can update this value in its constructor but shouldn't alter it later
  22510. as changes won't necessarily be picked up.
  22511. */
  22512. int preferredHeight;
  22513. };
  22514. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  22515. /********* End of inlined file: juce_PropertyComponent.h *********/
  22516. /********* Start of inlined file: juce_Viewport.h *********/
  22517. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  22518. #define __JUCE_VIEWPORT_JUCEHEADER__
  22519. /********* Start of inlined file: juce_ScrollBar.h *********/
  22520. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  22521. #define __JUCE_SCROLLBAR_JUCEHEADER__
  22522. /********* Start of inlined file: juce_Button.h *********/
  22523. #ifndef __JUCE_BUTTON_JUCEHEADER__
  22524. #define __JUCE_BUTTON_JUCEHEADER__
  22525. /********* Start of inlined file: juce_TooltipWindow.h *********/
  22526. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22527. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22528. /********* Start of inlined file: juce_TooltipClient.h *********/
  22529. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22530. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22531. /**
  22532. Components that want to use pop-up tooltips should implement this interface.
  22533. A TooltipWindow will wait for the mouse to hover over a component that
  22534. implements the TooltipClient interface, and when it finds one, it will display
  22535. the tooltip returned by its getTooltip() method.
  22536. @see TooltipWindow, SettableTooltipClient
  22537. */
  22538. class JUCE_API TooltipClient
  22539. {
  22540. public:
  22541. /** Destructor. */
  22542. virtual ~TooltipClient() {}
  22543. /** Returns the string that this object wants to show as its tooltip. */
  22544. virtual const String getTooltip() = 0;
  22545. };
  22546. /**
  22547. An implementation of TooltipClient that stores the tooltip string and a method
  22548. for changing it.
  22549. This makes it easy to add a tooltip to a custom component, by simply adding this
  22550. as a base class and calling setTooltip().
  22551. Many of the Juce widgets already use this as a base class to implement their
  22552. tooltips.
  22553. @see TooltipClient, TooltipWindow
  22554. */
  22555. class JUCE_API SettableTooltipClient : public TooltipClient
  22556. {
  22557. public:
  22558. /** Destructor. */
  22559. virtual ~SettableTooltipClient() {}
  22560. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  22561. virtual const String getTooltip() { return tooltipString; }
  22562. juce_UseDebuggingNewOperator
  22563. protected:
  22564. String tooltipString;
  22565. };
  22566. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  22567. /********* End of inlined file: juce_TooltipClient.h *********/
  22568. /**
  22569. A window that displays a pop-up tooltip when the mouse hovers over another component.
  22570. To enable tooltips in your app, just create a single instance of a TooltipWindow
  22571. object.
  22572. The TooltipWindow object will then stay invisible, waiting until the mouse
  22573. hovers for the specified length of time - it will then see if it's currently
  22574. over a component which implements the TooltipClient interface, and if so,
  22575. it will make itself visible to show the tooltip in the appropriate place.
  22576. @see TooltipClient, SettableTooltipClient
  22577. */
  22578. class JUCE_API TooltipWindow : public Component,
  22579. private Timer
  22580. {
  22581. public:
  22582. /** Creates a tooltip window.
  22583. Make sure your app only creates one instance of this class, otherwise you'll
  22584. get multiple overlaid tooltips appearing. The window will initially be invisible
  22585. and will make itself visible when it needs to display a tip.
  22586. To change the style of tooltips, see the LookAndFeel class for its tooltip
  22587. methods.
  22588. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  22589. otherwise the tooltip will be added to the given parent
  22590. component.
  22591. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  22592. before a tooltip will be shown
  22593. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  22594. */
  22595. TooltipWindow (Component* parentComponent = 0,
  22596. const int millisecondsBeforeTipAppears = 700);
  22597. /** Destructor. */
  22598. ~TooltipWindow();
  22599. /** Changes the time before the tip appears.
  22600. This lets you change the value that was set in the constructor.
  22601. */
  22602. void setMillisecondsBeforeTipAppears (const int newTimeMs = 700) throw();
  22603. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  22604. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  22605. methods.
  22606. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  22607. */
  22608. enum ColourIds
  22609. {
  22610. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  22611. textColourId = 0x1001c00, /**< The colour to use for the text. */
  22612. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  22613. };
  22614. juce_UseDebuggingNewOperator
  22615. private:
  22616. int millisecondsBeforeTipAppears;
  22617. int mouseX, mouseY, mouseClicks;
  22618. unsigned int lastCompChangeTime, lastHideTime;
  22619. Component* lastComponentUnderMouse;
  22620. bool changedCompsSinceShown;
  22621. String tipShowing, lastTipUnderMouse;
  22622. void paint (Graphics& g);
  22623. void mouseEnter (const MouseEvent& e);
  22624. void timerCallback();
  22625. static const String getTipFor (Component* const c);
  22626. void showFor (Component* const c, const String& tip);
  22627. void hide();
  22628. TooltipWindow (const TooltipWindow&);
  22629. const TooltipWindow& operator= (const TooltipWindow&);
  22630. };
  22631. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  22632. /********* End of inlined file: juce_TooltipWindow.h *********/
  22633. class Button;
  22634. /**
  22635. Used to receive callbacks when a button is clicked.
  22636. @see Button::addButtonListener, Button::removeButtonListener
  22637. */
  22638. class JUCE_API ButtonListener
  22639. {
  22640. public:
  22641. /** Destructor. */
  22642. virtual ~ButtonListener() {}
  22643. /** Called when the button is clicked. */
  22644. virtual void buttonClicked (Button* button) = 0;
  22645. /** Called when the button's state changes. */
  22646. virtual void buttonStateChanged (Button*) {}
  22647. };
  22648. /**
  22649. A base class for buttons.
  22650. This contains all the logic for button behaviours such as enabling/disabling,
  22651. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  22652. and radio groups, etc.
  22653. @see TextButton, DrawableButton, ToggleButton
  22654. */
  22655. class JUCE_API Button : public Component,
  22656. public SettableTooltipClient,
  22657. public ApplicationCommandManagerListener,
  22658. private KeyListener
  22659. {
  22660. protected:
  22661. /** Creates a button.
  22662. @param buttonName the text to put in the button (the component's name is also
  22663. initially set to this string, but these can be changed later
  22664. using the setName() and setButtonText() methods)
  22665. */
  22666. Button (const String& buttonName);
  22667. public:
  22668. /** Destructor. */
  22669. virtual ~Button();
  22670. /** Changes the button's text.
  22671. @see getButtonText
  22672. */
  22673. void setButtonText (const String& newText) throw();
  22674. /** Returns the text displayed in the button.
  22675. @see setButtonText
  22676. */
  22677. const String getButtonText() const throw() { return text; }
  22678. /** Returns true if the button is currently being held down by the mouse.
  22679. @see isOver
  22680. */
  22681. bool isDown() const throw();
  22682. /** Returns true if the mouse is currently over the button.
  22683. This will be also be true if the mouse is being held down.
  22684. @see isDown
  22685. */
  22686. bool isOver() const throw();
  22687. /** A button has an on/off state associated with it, and this changes that.
  22688. By default buttons are 'off' and for simple buttons that you click to perform
  22689. an action you won't change this. Toggle buttons, however will want to
  22690. change their state when turned on or off.
  22691. @param shouldBeOn whether to set the button's toggle state to be on or
  22692. off. If it's a member of a button group, this will
  22693. always try to turn it on, and to turn off any other
  22694. buttons in the group
  22695. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  22696. the button will be repainted but no notification will
  22697. be sent
  22698. @see getToggleState, setRadioGroupId
  22699. */
  22700. void setToggleState (const bool shouldBeOn,
  22701. const bool sendChangeNotification);
  22702. /** Returns true if the button in 'on'.
  22703. By default buttons are 'off' and for simple buttons that you click to perform
  22704. an action you won't change this. Toggle buttons, however will want to
  22705. change their state when turned on or off.
  22706. @see setToggleState
  22707. */
  22708. bool getToggleState() const throw() { return isOn; }
  22709. /** This tells the button to automatically flip the toggle state when
  22710. the button is clicked.
  22711. If set to true, then before the clicked() callback occurs, the toggle-state
  22712. of the button is flipped.
  22713. */
  22714. void setClickingTogglesState (const bool shouldToggle) throw();
  22715. /** Returns true if this button is set to be an automatic toggle-button.
  22716. This returns the last value that was passed to setClickingTogglesState().
  22717. */
  22718. bool getClickingTogglesState() const throw();
  22719. /** Enables the button to act as a member of a mutually-exclusive group
  22720. of 'radio buttons'.
  22721. If the group ID is set to a non-zero number, then this button will
  22722. act as part of a group of buttons with the same ID, only one of
  22723. which can be 'on' at the same time. Note that when it's part of
  22724. a group, clicking a toggle-button that's 'on' won't turn it off.
  22725. To find other buttons with the same ID, this button will search through
  22726. its sibling components for ToggleButtons, so all the buttons for a
  22727. particular group must be placed inside the same parent component.
  22728. Set the group ID back to zero if you want it to act as a normal toggle
  22729. button again.
  22730. @see getRadioGroupId
  22731. */
  22732. void setRadioGroupId (const int newGroupId);
  22733. /** Returns the ID of the group to which this button belongs.
  22734. (See setRadioGroupId() for an explanation of this).
  22735. */
  22736. int getRadioGroupId() const throw() { return radioGroupId; }
  22737. /** Registers a listener to receive events when this button's state changes.
  22738. If the listener is already registered, this will not register it again.
  22739. @see removeButtonListener
  22740. */
  22741. void addButtonListener (ButtonListener* const newListener) throw();
  22742. /** Removes a previously-registered button listener
  22743. @see addButtonListener
  22744. */
  22745. void removeButtonListener (ButtonListener* const listener) throw();
  22746. /** Causes the button to act as if it's been clicked.
  22747. This will asynchronously make the button draw itself going down and up, and
  22748. will then call back the clicked() method as if mouse was clicked on it.
  22749. @see clicked
  22750. */
  22751. virtual void triggerClick();
  22752. /** Sets a command ID for this button to automatically invoke when it's clicked.
  22753. When the button is pressed, it will use the given manager to trigger the
  22754. command ID.
  22755. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  22756. before this button is. To disable the command triggering, call this method and
  22757. pass 0 for the parameters.
  22758. If generateTooltip is true, then the button's tooltip will be automatically
  22759. generated based on the name of this command and its current shortcut key.
  22760. @see addShortcut, getCommandID
  22761. */
  22762. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  22763. const int commandID,
  22764. const bool generateTooltip);
  22765. /** Returns the command ID that was set by setCommandToTrigger().
  22766. */
  22767. int getCommandID() const throw() { return commandID; }
  22768. /** Assigns a shortcut key to trigger the button.
  22769. The button registers itself with its top-level parent component for keypresses.
  22770. Note that a different way of linking buttons to keypresses is by using the
  22771. setKeyPressToTrigger() method to invoke a command - the difference being that
  22772. setting a shortcut allows the button to be temporarily linked to a keypress
  22773. only while it's on-screen.
  22774. @see clearShortcuts
  22775. */
  22776. void addShortcut (const KeyPress& key);
  22777. /** Removes all key shortcuts that had been set for this button.
  22778. @see addShortcut
  22779. */
  22780. void clearShortcuts();
  22781. /** Returns true if the given keypress is a shortcut for this button.
  22782. @see addShortcut
  22783. */
  22784. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  22785. /** Sets an auto-repeat speed for the button when it is held down.
  22786. (Auto-repeat is disabled by default).
  22787. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  22788. triggering the next click. If this is zero, auto-repeat
  22789. is disabled
  22790. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  22791. triggered
  22792. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  22793. get faster, the longer the button is held down, up to the
  22794. minimum interval specified here
  22795. */
  22796. void setRepeatSpeed (const int initialDelayInMillisecs,
  22797. const int repeatDelayInMillisecs,
  22798. const int minimumDelayInMillisecs = -1) throw();
  22799. /** Sets whether the button click should happen when the mouse is pressed or released.
  22800. By default the button is only considered to have been clicked when the mouse is
  22801. released, but setting this to true will make it call the clicked() method as soon
  22802. as the button is pressed.
  22803. This is useful if the button is being used to show a pop-up menu, as it allows
  22804. the click to be used as a drag onto the menu.
  22805. */
  22806. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  22807. /** Returns the number of milliseconds since the last time the button
  22808. went into the 'down' state.
  22809. */
  22810. uint32 getMillisecondsSinceButtonDown() const throw();
  22811. /** (overridden from Component to do special stuff). */
  22812. void setVisible (bool shouldBeVisible);
  22813. /** Sets the tooltip for this button.
  22814. @see TooltipClient, TooltipWindow
  22815. */
  22816. void setTooltip (const String& newTooltip);
  22817. // (implementation of the TooltipClient method)
  22818. const String getTooltip();
  22819. /** A combination of these flags are used by setConnectedEdges().
  22820. */
  22821. enum ConnectedEdgeFlags
  22822. {
  22823. ConnectedOnLeft = 1,
  22824. ConnectedOnRight = 2,
  22825. ConnectedOnTop = 4,
  22826. ConnectedOnBottom = 8
  22827. };
  22828. /** Hints about which edges of the button might be connected to adjoining buttons.
  22829. The value passed in is a bitwise combination of any of the values in the
  22830. ConnectedEdgeFlags enum.
  22831. E.g. if you are placing two buttons adjacent to each other, you could use this to
  22832. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  22833. without rounded corners on the edges that connect. It's only a hint, so the
  22834. LookAndFeel can choose to ignore it if it's not relevent for this type of
  22835. button.
  22836. */
  22837. void setConnectedEdges (const int connectedEdgeFlags) throw();
  22838. /** Returns the set of flags passed into setConnectedEdges(). */
  22839. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  22840. /** Indicates whether the button adjoins another one on its left edge.
  22841. @see setConnectedEdges
  22842. */
  22843. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  22844. /** Indicates whether the button adjoins another one on its right edge.
  22845. @see setConnectedEdges
  22846. */
  22847. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  22848. /** Indicates whether the button adjoins another one on its top edge.
  22849. @see setConnectedEdges
  22850. */
  22851. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  22852. /** Indicates whether the button adjoins another one on its bottom edge.
  22853. @see setConnectedEdges
  22854. */
  22855. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  22856. /** Used by setState(). */
  22857. enum ButtonState
  22858. {
  22859. buttonNormal,
  22860. buttonOver,
  22861. buttonDown
  22862. };
  22863. /** Can be used to force the button into a particular state.
  22864. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  22865. from happening.
  22866. The state that you set here will only last until it is automatically changed when the mouse
  22867. enters or exits the button, or the mouse-button is pressed or released.
  22868. */
  22869. void setState (const ButtonState newState);
  22870. juce_UseDebuggingNewOperator
  22871. protected:
  22872. /** This method is called when the button has been clicked.
  22873. Subclasses can override this to perform whatever they actions they need
  22874. to do.
  22875. Alternatively, a ButtonListener can be added to the button, and these listeners
  22876. will be called when the click occurs.
  22877. @see triggerClick
  22878. */
  22879. virtual void clicked();
  22880. /** This method is called when the button has been clicked.
  22881. By default it just calls clicked(), but you might want to override it to handle
  22882. things like clicking when a modifier key is pressed, etc.
  22883. @see ModifierKeys
  22884. */
  22885. virtual void clicked (const ModifierKeys& modifiers);
  22886. /** Subclasses should override this to actually paint the button's contents.
  22887. It's better to use this than the paint method, because it gives you information
  22888. about the over/down state of the button.
  22889. @param g the graphics context to use
  22890. @param isMouseOverButton true if the button is either in the 'over' or
  22891. 'down' state
  22892. @param isButtonDown true if the button should be drawn in the 'down' position
  22893. */
  22894. virtual void paintButton (Graphics& g,
  22895. bool isMouseOverButton,
  22896. bool isButtonDown) = 0;
  22897. /** Called when the button's up/down/over state changes.
  22898. Subclasses can override this if they need to do something special when the button
  22899. goes up or down.
  22900. @see isDown, isOver
  22901. */
  22902. virtual void buttonStateChanged();
  22903. /** @internal */
  22904. virtual void internalClickCallback (const ModifierKeys& modifiers);
  22905. /** @internal */
  22906. void handleCommandMessage (int commandId);
  22907. /** @internal */
  22908. void mouseEnter (const MouseEvent& e);
  22909. /** @internal */
  22910. void mouseExit (const MouseEvent& e);
  22911. /** @internal */
  22912. void mouseDown (const MouseEvent& e);
  22913. /** @internal */
  22914. void mouseDrag (const MouseEvent& e);
  22915. /** @internal */
  22916. void mouseUp (const MouseEvent& e);
  22917. /** @internal */
  22918. bool keyPressed (const KeyPress& key);
  22919. /** @internal */
  22920. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  22921. /** @internal */
  22922. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  22923. /** @internal */
  22924. void paint (Graphics& g);
  22925. /** @internal */
  22926. void parentHierarchyChanged();
  22927. /** @internal */
  22928. void focusGained (FocusChangeType cause);
  22929. /** @internal */
  22930. void focusLost (FocusChangeType cause);
  22931. /** @internal */
  22932. void enablementChanged();
  22933. /** @internal */
  22934. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  22935. /** @internal */
  22936. void applicationCommandListChanged();
  22937. private:
  22938. Array <KeyPress> shortcuts;
  22939. Component* keySource;
  22940. String text;
  22941. SortedSet <void*> buttonListeners;
  22942. friend class InternalButtonRepeatTimer;
  22943. Timer* repeatTimer;
  22944. uint32 buttonPressTime, lastTimeCallbackTime;
  22945. ApplicationCommandManager* commandManagerToUse;
  22946. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  22947. int radioGroupId, commandID, connectedEdgeFlags;
  22948. ButtonState buttonState;
  22949. bool isOn : 1;
  22950. bool clickTogglesState : 1;
  22951. bool needsToRelease : 1;
  22952. bool needsRepainting : 1;
  22953. bool isKeyDown : 1;
  22954. bool triggerOnMouseDown : 1;
  22955. bool generateTooltip : 1;
  22956. void repeatTimerCallback() throw();
  22957. Timer& getRepeatTimer() throw();
  22958. ButtonState updateState (const MouseEvent* const e) throw();
  22959. bool isShortcutPressed() const throw();
  22960. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  22961. void flashButtonState() throw();
  22962. void sendClickMessage (const ModifierKeys& modifiers);
  22963. void sendStateMessage();
  22964. Button (const Button&);
  22965. const Button& operator= (const Button&);
  22966. };
  22967. #endif // __JUCE_BUTTON_JUCEHEADER__
  22968. /********* End of inlined file: juce_Button.h *********/
  22969. class ScrollBar;
  22970. /**
  22971. A class for receiving events from a ScrollBar.
  22972. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  22973. method, and it will be called when the bar's position changes.
  22974. @see ScrollBar::addListener, ScrollBar::removeListener
  22975. */
  22976. class JUCE_API ScrollBarListener
  22977. {
  22978. public:
  22979. /** Destructor. */
  22980. virtual ~ScrollBarListener() {}
  22981. /** Called when a ScrollBar is moved.
  22982. @param scrollBarThatHasMoved the bar that has moved
  22983. @param newRangeStart the new range start of this bar
  22984. */
  22985. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  22986. const double newRangeStart) = 0;
  22987. };
  22988. /**
  22989. A scrollbar component.
  22990. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  22991. sets the range of values it can represent. Then you can use setCurrentRange() to
  22992. change the position and size of the scrollbar's 'thumb'.
  22993. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  22994. the user moves it, and you can use the getCurrentRangeStart() to find out where
  22995. they moved it to.
  22996. The scrollbar will adjust its own visibility according to whether its thumb size
  22997. allows it to actually be scrolled.
  22998. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  22999. instead of handling a scrollbar directly.
  23000. @see ScrollBarListener
  23001. */
  23002. class JUCE_API ScrollBar : public Component,
  23003. public AsyncUpdater,
  23004. private Timer
  23005. {
  23006. public:
  23007. /** Creates a Scrollbar.
  23008. @param isVertical whether it should be a vertical or horizontal bar
  23009. @param buttonsAreVisible whether to show the up/down or left/right buttons
  23010. */
  23011. ScrollBar (const bool isVertical,
  23012. const bool buttonsAreVisible = true);
  23013. /** Destructor. */
  23014. ~ScrollBar();
  23015. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  23016. bool isVertical() const throw() { return vertical; }
  23017. /** Changes the scrollbar's direction.
  23018. You'll also need to resize the bar appropriately - this just changes its internal
  23019. layout.
  23020. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  23021. */
  23022. void setOrientation (const bool shouldBeVertical) throw();
  23023. /** Shows or hides the scrollbar's buttons. */
  23024. void setButtonVisibility (const bool buttonsAreVisible);
  23025. /** Tells the scrollbar whether to make itself invisible when not needed.
  23026. The default behaviour is for a scrollbar to become invisible when the thumb
  23027. fills the whole of its range (i.e. when it can't be moved). Setting this
  23028. value to false forces the bar to always be visible.
  23029. */
  23030. void setAutoHide (const bool shouldHideWhenFullRange);
  23031. /** Sets the minimum and maximum values that the bar will move between.
  23032. The bar's thumb will always be constrained so that the top of the thumb
  23033. will be >= minimum, and the bottom of the thumb <= maximum.
  23034. @see setCurrentRange
  23035. */
  23036. void setRangeLimits (const double minimum,
  23037. const double maximum) throw();
  23038. /** Returns the lower value that the thumb can be set to.
  23039. This is the value set by setRangeLimits().
  23040. */
  23041. double getMinimumRangeLimit() const throw() { return minimum; }
  23042. /** Returns the upper value that the thumb can be set to.
  23043. This is the value set by setRangeLimits().
  23044. */
  23045. double getMaximumRangeLimit() const throw() { return maximum; }
  23046. /** Changes the position of the scrollbar's 'thumb'.
  23047. This sets both the position and size of the thumb - to just set the position without
  23048. changing the size, you can use setCurrentRangeStart().
  23049. If this method call actually changes the scrollbar's position, it will trigger an
  23050. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  23051. are registered.
  23052. @param newStart the top (or left) of the thumb, in the range
  23053. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  23054. value is beyond these limits, it will be clipped.
  23055. @param newSize the size of the thumb, such that
  23056. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  23057. size is beyond these limits, it will be clipped.
  23058. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  23059. */
  23060. void setCurrentRange (double newStart,
  23061. double newSize) throw();
  23062. /** Moves the bar's thumb position.
  23063. This will move the thumb position without changing the thumb size. Note
  23064. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  23065. If this method call actually changes the scrollbar's position, it will trigger an
  23066. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  23067. are registered.
  23068. @see setCurrentRange
  23069. */
  23070. void setCurrentRangeStart (double newStart) throw();
  23071. /** Returns the position of the top of the thumb.
  23072. @see setCurrentRangeStart
  23073. */
  23074. double getCurrentRangeStart() const throw() { return rangeStart; }
  23075. /** Returns the current size of the thumb.
  23076. @see setCurrentRange
  23077. */
  23078. double getCurrentRangeSize() const throw() { return rangeSize; }
  23079. /** Sets the amount by which the up and down buttons will move the bar.
  23080. The value here is in terms of the total range, and is added or subtracted
  23081. from the thumb position when the user clicks an up/down (or left/right) button.
  23082. */
  23083. void setSingleStepSize (const double newSingleStepSize) throw();
  23084. /** Moves the scrollbar by a number of single-steps.
  23085. This will move the bar by a multiple of its single-step interval (as
  23086. specified using the setSingleStepSize() method).
  23087. A positive value here will move the bar down or to the right, a negative
  23088. value moves it up or to the left.
  23089. */
  23090. void moveScrollbarInSteps (const int howManySteps) throw();
  23091. /** Moves the scroll bar up or down in pages.
  23092. This will move the bar by a multiple of its current thumb size, effectively
  23093. doing a page-up or down.
  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 moveScrollbarInPages (const int howManyPages) throw();
  23098. /** Scrolls to the top (or left).
  23099. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  23100. */
  23101. void scrollToTop() throw();
  23102. /** Scrolls to the bottom (or right).
  23103. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  23104. */
  23105. void scrollToBottom() throw();
  23106. /** Changes the delay before the up and down buttons autorepeat when they are held
  23107. down.
  23108. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  23109. @see Button::setRepeatSpeed
  23110. */
  23111. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  23112. const int repeatDelayInMillisecs,
  23113. const int minimumDelayInMillisecs = -1) throw();
  23114. /** A set of colour IDs to use to change the colour of various aspects of the component.
  23115. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  23116. methods.
  23117. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  23118. */
  23119. enum ColourIds
  23120. {
  23121. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  23122. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  23123. 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. */
  23124. };
  23125. /** Registers a listener that will be called when the scrollbar is moved. */
  23126. void addListener (ScrollBarListener* const listener) throw();
  23127. /** Deregisters a previously-registered listener. */
  23128. void removeListener (ScrollBarListener* const listener) throw();
  23129. /** @internal */
  23130. bool keyPressed (const KeyPress& key);
  23131. /** @internal */
  23132. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23133. /** @internal */
  23134. void lookAndFeelChanged();
  23135. /** @internal */
  23136. void handleAsyncUpdate();
  23137. /** @internal */
  23138. void mouseDown (const MouseEvent& e);
  23139. /** @internal */
  23140. void mouseDrag (const MouseEvent& e);
  23141. /** @internal */
  23142. void mouseUp (const MouseEvent& e);
  23143. /** @internal */
  23144. void paint (Graphics& g);
  23145. /** @internal */
  23146. void resized();
  23147. juce_UseDebuggingNewOperator
  23148. private:
  23149. double minimum, maximum;
  23150. double rangeStart, rangeSize;
  23151. double singleStepSize, dragStartRange;
  23152. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  23153. int dragStartMousePos, lastMousePos;
  23154. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  23155. bool vertical, isDraggingThumb, alwaysVisible;
  23156. Button* upButton;
  23157. Button* downButton;
  23158. SortedSet <void*> listeners;
  23159. void updateThumbPosition() throw();
  23160. void timerCallback();
  23161. ScrollBar (const ScrollBar&);
  23162. const ScrollBar& operator= (const ScrollBar&);
  23163. };
  23164. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  23165. /********* End of inlined file: juce_ScrollBar.h *********/
  23166. /**
  23167. A Viewport is used to contain a larger child component, and allows the child
  23168. to be automatically scrolled around.
  23169. To use a Viewport, just create one and set the component that goes inside it
  23170. using the setViewedComponent() method. When the child component changes size,
  23171. the Viewport will adjust its scrollbars accordingly.
  23172. A subclass of the viewport can be created which will receive calls to its
  23173. visibleAreaChanged() method when the subcomponent changes position or size.
  23174. */
  23175. class JUCE_API Viewport : public Component,
  23176. private ComponentListener,
  23177. private ScrollBarListener
  23178. {
  23179. public:
  23180. /** Creates a Viewport.
  23181. The viewport is initially empty - use the setViewedComponent() method to
  23182. add a child component for it to manage.
  23183. */
  23184. Viewport (const String& componentName = String::empty);
  23185. /** Destructor. */
  23186. ~Viewport();
  23187. /** Sets the component that this viewport will contain and scroll around.
  23188. This will add the given component to this Viewport and position it at
  23189. (0, 0).
  23190. (Don't add or remove any child components directly using the normal
  23191. Component::addChildComponent() methods).
  23192. @param newViewedComponent the component to add to this viewport (this pointer
  23193. may be null). The component passed in will be deleted
  23194. by the Viewport when it's no longer needed
  23195. @see getViewedComponent
  23196. */
  23197. void setViewedComponent (Component* const newViewedComponent);
  23198. /** Returns the component that's currently being used inside the Viewport.
  23199. @see setViewedComponent
  23200. */
  23201. Component* getViewedComponent() const throw() { return contentComp; }
  23202. /** Changes the position of the viewed component.
  23203. The inner component will be moved so that the pixel at the top left of
  23204. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  23205. within the inner component.
  23206. This will update the scrollbars and might cause a call to visibleAreaChanged().
  23207. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  23208. */
  23209. void setViewPosition (const int xPixelsOffset,
  23210. const int yPixelsOffset);
  23211. /** Changes the view position as a proportion of the distance it can move.
  23212. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  23213. visible area in the top-left, and (1, 1) would put it as far down and
  23214. to the right as it's possible to go whilst keeping the child component
  23215. on-screen.
  23216. */
  23217. void setViewPositionProportionately (const double proportionX,
  23218. const double proportionY);
  23219. /** Returns the position within the child component of the top-left of its visible area.
  23220. @see getViewWidth, setViewPosition
  23221. */
  23222. int getViewPositionX() const throw() { return lastVX; }
  23223. /** Returns the position within the child component of the top-left of its visible area.
  23224. @see getViewHeight, setViewPosition
  23225. */
  23226. int getViewPositionY() const throw() { return lastVY; }
  23227. /** Returns the width of the visible area of the child component.
  23228. This may be less than the width of this Viewport if there's a vertical scrollbar
  23229. or if the child component is itself smaller.
  23230. */
  23231. int getViewWidth() const throw() { return lastVW; }
  23232. /** Returns the height of the visible area of the child component.
  23233. This may be less than the height of this Viewport if there's a horizontal scrollbar
  23234. or if the child component is itself smaller.
  23235. */
  23236. int getViewHeight() const throw() { return lastVH; }
  23237. /** Returns the width available within this component for the contents.
  23238. This will be the width of the viewport component minus the width of a
  23239. vertical scrollbar (if visible).
  23240. */
  23241. int getMaximumVisibleWidth() const throw();
  23242. /** Returns the height available within this component for the contents.
  23243. This will be the height of the viewport component minus the space taken up
  23244. by a horizontal scrollbar (if visible).
  23245. */
  23246. int getMaximumVisibleHeight() const throw();
  23247. /** Callback method that is called when the visible area changes.
  23248. This will be called when the visible area is moved either be scrolling or
  23249. by calls to setViewPosition(), etc.
  23250. */
  23251. virtual void visibleAreaChanged (int visibleX, int visibleY,
  23252. int visibleW, int visibleH);
  23253. /** Turns scrollbars on or off.
  23254. If set to false, the scrollbars won't ever appear. When true (the default)
  23255. they will appear only when needed.
  23256. */
  23257. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  23258. const bool showHorizontalScrollbarIfNeeded);
  23259. /** True if the vertical scrollbar is enabled.
  23260. @see setScrollBarsShown
  23261. */
  23262. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  23263. /** True if the horizontal scrollbar is enabled.
  23264. @see setScrollBarsShown
  23265. */
  23266. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  23267. /** Changes the width of the scrollbars.
  23268. If this isn't specified, the default width from the LookAndFeel class will be used.
  23269. @see LookAndFeel::getDefaultScrollbarWidth
  23270. */
  23271. void setScrollBarThickness (const int thickness);
  23272. /** Returns the thickness of the scrollbars.
  23273. @see setScrollBarThickness
  23274. */
  23275. int getScrollBarThickness() const throw();
  23276. /** Changes the distance that a single-step click on a scrollbar button
  23277. will move the viewport.
  23278. */
  23279. void setSingleStepSizes (const int stepX, const int stepY);
  23280. /** Shows or hides the buttons on any scrollbars that are used.
  23281. @see ScrollBar::setButtonVisibility
  23282. */
  23283. void setScrollBarButtonVisibility (const bool buttonsVisible);
  23284. /** Returns a pointer to the scrollbar component being used.
  23285. Handy if you need to customise the bar somehow.
  23286. */
  23287. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  23288. /** Returns a pointer to the scrollbar component being used.
  23289. Handy if you need to customise the bar somehow.
  23290. */
  23291. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  23292. juce_UseDebuggingNewOperator
  23293. /** @internal */
  23294. void resized();
  23295. /** @internal */
  23296. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  23297. /** @internal */
  23298. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23299. /** @internal */
  23300. bool keyPressed (const KeyPress& key);
  23301. /** @internal */
  23302. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  23303. /** @internal */
  23304. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  23305. private:
  23306. Component* contentComp;
  23307. int lastVX, lastVY, lastVW, lastVH;
  23308. int scrollBarThickness;
  23309. int singleStepX, singleStepY;
  23310. bool showHScrollbar, showVScrollbar;
  23311. Component* contentHolder;
  23312. ScrollBar* verticalScrollBar;
  23313. ScrollBar* horizontalScrollBar;
  23314. void updateVisibleRegion();
  23315. Viewport (const Viewport&);
  23316. const Viewport& operator= (const Viewport&);
  23317. };
  23318. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  23319. /********* End of inlined file: juce_Viewport.h *********/
  23320. /**
  23321. A panel that holds a list of PropertyComponent objects.
  23322. This panel displays a list of PropertyComponents, and allows them to be organised
  23323. into collapsible sections.
  23324. To use, simply create one of these and add your properties to it with addProperties()
  23325. or addSection().
  23326. @see PropertyComponent
  23327. */
  23328. class JUCE_API PropertyPanel : public Component
  23329. {
  23330. public:
  23331. /** Creates an empty property panel. */
  23332. PropertyPanel();
  23333. /** Destructor. */
  23334. ~PropertyPanel();
  23335. /** Deletes all property components from the panel.
  23336. */
  23337. void clear();
  23338. /** Adds a set of properties to the panel.
  23339. The components in the list will be owned by this object and will be automatically
  23340. deleted later on when no longer needed.
  23341. These properties are added without them being inside a named section. If you
  23342. want them to be kept together in a collapsible section, use addSection() instead.
  23343. */
  23344. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  23345. /** Adds a set of properties to the panel.
  23346. These properties are added at the bottom of the list, under a section heading with
  23347. a plus/minus button that allows it to be opened and closed.
  23348. The components in the list will be owned by this object and will be automatically
  23349. deleted later on when no longer needed.
  23350. To add properies without them being in a section, use addProperties().
  23351. */
  23352. void addSection (const String& sectionTitle,
  23353. const Array <PropertyComponent*>& newPropertyComponents,
  23354. const bool shouldSectionInitiallyBeOpen = true);
  23355. /** Calls the refresh() method of all PropertyComponents in the panel */
  23356. void refreshAll() const;
  23357. /** Returns a list of all the names of sections in the panel.
  23358. These are the sections that have been added with addSection().
  23359. */
  23360. const StringArray getSectionNames() const;
  23361. /** Returns true if the section at this index is currently open.
  23362. The index is from 0 up to the number of items returned by getSectionNames().
  23363. */
  23364. bool isSectionOpen (const int sectionIndex) const;
  23365. /** Opens or closes one of the sections.
  23366. The index is from 0 up to the number of items returned by getSectionNames().
  23367. */
  23368. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  23369. /** Enables or disables one of the sections.
  23370. The index is from 0 up to the number of items returned by getSectionNames().
  23371. */
  23372. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  23373. /** Saves the current state of open/closed sections so it can be restored later.
  23374. The caller is responsible for deleting the object that is returned.
  23375. To restore this state, use restoreOpennessState().
  23376. @see restoreOpennessState
  23377. */
  23378. XmlElement* getOpennessState() const;
  23379. /** Restores a previously saved arrangement of open/closed sections.
  23380. This will try to restore a snapshot of the panel's state that was created by
  23381. the getOpennessState() method. If any of the sections named in the original
  23382. XML aren't present, they will be ignored.
  23383. @see getOpennessState
  23384. */
  23385. void restoreOpennessState (const XmlElement& newState);
  23386. /** Sets a message to be displayed when there are no properties in the panel.
  23387. The default message is "nothing selected".
  23388. */
  23389. void setMessageWhenEmpty (const String& newMessage);
  23390. /** Returns the message that is displayed when there are no properties.
  23391. @see setMessageWhenEmpty
  23392. */
  23393. const String& getMessageWhenEmpty() const throw();
  23394. /** @internal */
  23395. void paint (Graphics& g);
  23396. /** @internal */
  23397. void resized();
  23398. juce_UseDebuggingNewOperator
  23399. private:
  23400. Viewport* viewport;
  23401. Component* propertyHolderComponent;
  23402. String messageWhenEmpty;
  23403. void updatePropHolderLayout() const;
  23404. void updatePropHolderLayout (const int width) const;
  23405. };
  23406. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  23407. /********* End of inlined file: juce_PropertyPanel.h *********/
  23408. /**
  23409. A type of UI component that displays the parameters of an AudioProcessor as
  23410. a simple list of sliders.
  23411. This can be used for showing an editor for a processor that doesn't supply
  23412. its own custom editor.
  23413. @see AudioProcessor
  23414. */
  23415. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  23416. {
  23417. public:
  23418. GenericAudioProcessorEditor (AudioProcessor* const owner);
  23419. ~GenericAudioProcessorEditor();
  23420. void paint (Graphics& g);
  23421. void resized();
  23422. juce_UseDebuggingNewOperator
  23423. private:
  23424. PropertyPanel* panel;
  23425. };
  23426. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  23427. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  23428. #endif
  23429. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23430. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  23431. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23432. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23433. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  23434. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23435. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23436. /********* Start of inlined file: juce_AudioSource.h *********/
  23437. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23438. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  23439. /**
  23440. Used by AudioSource::getNextAudioBlock().
  23441. */
  23442. struct JUCE_API AudioSourceChannelInfo
  23443. {
  23444. /** The destination buffer to fill with audio data.
  23445. When the AudioSource::getNextAudioBlock() method is called, the active section
  23446. of this buffer should be filled with whatever output the source produces.
  23447. Only the samples specified by the startSample and numSamples members of this structure
  23448. should be affected by the call.
  23449. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  23450. method can be treated as the input if the source is performing some kind of filter operation,
  23451. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  23452. a handy way of doing this.
  23453. The number of channels in the buffer could be anything, so the AudioSource
  23454. must cope with this in whatever way is appropriate for its function.
  23455. */
  23456. AudioSampleBuffer* buffer;
  23457. /** The first sample in the buffer from which the callback is expected
  23458. to write data. */
  23459. int startSample;
  23460. /** The number of samples in the buffer which the callback is expected to
  23461. fill with data. */
  23462. int numSamples;
  23463. /** Convenient method to clear the buffer if the source is not producing any data. */
  23464. void clearActiveBufferRegion() const
  23465. {
  23466. if (buffer != 0)
  23467. buffer->clear (startSample, numSamples);
  23468. }
  23469. };
  23470. /**
  23471. Base class for objects that can produce a continuous stream of audio.
  23472. @see AudioFormatReaderSource, ResamplingAudioSource
  23473. */
  23474. class JUCE_API AudioSource
  23475. {
  23476. protected:
  23477. /** Creates an AudioSource. */
  23478. AudioSource() throw() {}
  23479. public:
  23480. /** Destructor. */
  23481. virtual ~AudioSource() {}
  23482. /** Tells the source to prepare for playing.
  23483. The source can use this opportunity to initialise anything it needs to.
  23484. Note that this method could be called more than once in succession without
  23485. a matching call to releaseResources(), so make sure your code is robust and
  23486. can handle that kind of situation.
  23487. @param samplesPerBlockExpected the number of samples that the source
  23488. will be expected to supply each time its
  23489. getNextAudioBlock() method is called. This
  23490. number may vary slightly, because it will be dependent
  23491. on audio hardware callbacks, and these aren't
  23492. guaranteed to always use a constant block size, so
  23493. the source should be able to cope with small variations.
  23494. @param sampleRate the sample rate that the output will be used at - this
  23495. is needed by sources such as tone generators.
  23496. @see releaseResources, getNextAudioBlock
  23497. */
  23498. virtual void prepareToPlay (int samplesPerBlockExpected,
  23499. double sampleRate) = 0;
  23500. /** Allows the source to release anything it no longer needs after playback has stopped.
  23501. This will be called when the source is no longer going to have its getNextAudioBlock()
  23502. method called, so it should release any spare memory, etc. that it might have
  23503. allocated during the prepareToPlay() call.
  23504. Note that there's no guarantee that prepareToPlay() will actually have been called before
  23505. releaseResources(), and it may be called more than once in succession, so make sure your
  23506. code is robust and doesn't make any assumptions about when it will be called.
  23507. @see prepareToPlay, getNextAudioBlock
  23508. */
  23509. virtual void releaseResources() = 0;
  23510. /** Called repeatedly to fetch subsequent blocks of audio data.
  23511. After calling the prepareToPlay() method, this callback will be made each
  23512. time the audio playback hardware (or whatever other destination the audio
  23513. data is going to) needs another block of data.
  23514. It will generally be called on a high-priority system thread, or possibly even
  23515. an interrupt, so be careful not to do too much work here, as that will cause
  23516. audio glitches!
  23517. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  23518. */
  23519. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  23520. };
  23521. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  23522. /********* End of inlined file: juce_AudioSource.h *********/
  23523. /**
  23524. A type of AudioSource which can be repositioned.
  23525. The basic AudioSource just streams continuously with no idea of a current
  23526. time or length, so the PositionableAudioSource is used for a finite stream
  23527. that has a current read position.
  23528. @see AudioSource, AudioTransportSource
  23529. */
  23530. class JUCE_API PositionableAudioSource : public AudioSource
  23531. {
  23532. protected:
  23533. /** Creates the PositionableAudioSource. */
  23534. PositionableAudioSource() throw() {}
  23535. public:
  23536. /** Destructor */
  23537. ~PositionableAudioSource() {}
  23538. /** Tells the stream to move to a new position.
  23539. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23540. should return samples from this position.
  23541. Note that this may be called on a different thread to getNextAudioBlock(),
  23542. so the subclass should make sure it's synchronised.
  23543. */
  23544. virtual void setNextReadPosition (int newPosition) = 0;
  23545. /** Returns the position from which the next block will be returned.
  23546. @see setNextReadPosition
  23547. */
  23548. virtual int getNextReadPosition() const = 0;
  23549. /** Returns the total length of the stream (in samples). */
  23550. virtual int getTotalLength() const = 0;
  23551. /** Returns true if this source is actually playing in a loop. */
  23552. virtual bool isLooping() const = 0;
  23553. };
  23554. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23555. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  23556. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  23557. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23558. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23559. class AudioFormat;
  23560. /**
  23561. Reads samples from an audio file stream.
  23562. A subclass that reads a specific type of audio format will be created by
  23563. an AudioFormat object.
  23564. @see AudioFormat, AudioFormatWriter
  23565. */
  23566. class JUCE_API AudioFormatReader
  23567. {
  23568. protected:
  23569. /** Creates an AudioFormatReader object.
  23570. @param sourceStream the stream to read from - this will be deleted
  23571. by this object when it is no longer needed. (Some
  23572. specialised readers might not use this parameter and
  23573. can leave it as 0).
  23574. @param formatName the description that will be returned by the getFormatName()
  23575. method
  23576. */
  23577. AudioFormatReader (InputStream* const sourceStream,
  23578. const String& formatName);
  23579. public:
  23580. /** Destructor. */
  23581. virtual ~AudioFormatReader();
  23582. /** Returns a description of what type of format this is.
  23583. E.g. "AIFF"
  23584. */
  23585. const String getFormatName() const throw() { return formatName; }
  23586. /** Reads samples from the stream.
  23587. @param destSamples an array of buffers into which the sample data for each
  23588. channel will be written.
  23589. If the format is fixed-point, each channel will be written
  23590. as an array of 32-bit signed integers using the full
  23591. range -0x80000000 to 0x7fffffff, regardless of the source's
  23592. bit-depth. If it is a floating-point format, you should cast
  23593. the resulting array to a (float**) to get the values (in the
  23594. range -1.0 to 1.0 or beyond)
  23595. If the format is stereo, then destSamples[0] is the left channel
  23596. data, and destSamples[1] is the right channel.
  23597. The numDestChannels parameter indicates how many pointers this array
  23598. contains, but some of these pointers can be null if you don't want to
  23599. read data for some of the channels
  23600. @param numDestChannels the number of array elements in the destChannels array
  23601. @param startSampleInSource the position in the audio file or stream at which the samples
  23602. should be read, as a number of samples from the start of the
  23603. stream. It's ok for this to be beyond the start or end of the
  23604. available data - any samples that are out-of-range will be returned
  23605. as zeros.
  23606. @param numSamplesToRead the number of samples to read. If this is greater than the number
  23607. of samples that the file or stream contains. the result will be padded
  23608. with zeros
  23609. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  23610. for some of the channels that you pass in, then they should be filled with
  23611. copies of valid source channels.
  23612. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  23613. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  23614. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  23615. was false, then only the first channel would be filled with the file's contents, and
  23616. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  23617. from a stereo file, then the last 3 would all end up with copies of the same data.
  23618. @returns true if the operation succeeded, false if there was an error. Note
  23619. that reading sections of data beyond the extent of the stream isn't an
  23620. error - the reader should just return zeros for these regions
  23621. @see readMaxLevels
  23622. */
  23623. bool read (int** destSamples,
  23624. int numDestChannels,
  23625. int64 startSampleInSource,
  23626. int numSamplesToRead,
  23627. const bool fillLeftoverChannelsWithCopies);
  23628. /** Finds the highest and lowest sample levels from a section of the audio stream.
  23629. This will read a block of samples from the stream, and measure the
  23630. highest and lowest sample levels from the channels in that section, returning
  23631. these as normalised floating-point levels.
  23632. @param startSample the offset into the audio stream to start reading from. It's
  23633. ok for this to be beyond the start or end of the stream.
  23634. @param numSamples how many samples to read
  23635. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  23636. @param highestLeft on return, this is the highest absolute sample from the left channel
  23637. @param lowestRight on return, this is the lowest absolute sample from the right
  23638. channel (if there is one)
  23639. @param highestRight on return, this is the highest absolute sample from the right
  23640. channel (if there is one)
  23641. @see read
  23642. */
  23643. virtual void readMaxLevels (int64 startSample,
  23644. int64 numSamples,
  23645. float& lowestLeft,
  23646. float& highestLeft,
  23647. float& lowestRight,
  23648. float& highestRight);
  23649. /** Scans the source looking for a sample whose magnitude is in a specified range.
  23650. This will read from the source, either forwards or backwards between two sample
  23651. positions, until it finds a sample whose magnitude lies between two specified levels.
  23652. If it finds a suitable sample, it returns its position; if not, it will return -1.
  23653. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  23654. points when you're searching for a continuous range of samples
  23655. @param startSample the first sample to look at
  23656. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  23657. the search will go backwards
  23658. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23659. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  23660. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  23661. of this many consecutive samples, all of which lie
  23662. within the target range. When it finds such a sequence,
  23663. it returns the position of the first in-range sample
  23664. it found (i.e. the earliest one if scanning forwards, the
  23665. latest one if scanning backwards)
  23666. */
  23667. int64 searchForLevel (int64 startSample,
  23668. int64 numSamplesToSearch,
  23669. const double magnitudeRangeMinimum,
  23670. const double magnitudeRangeMaximum,
  23671. const int minimumConsecutiveSamples);
  23672. /** The sample-rate of the stream. */
  23673. double sampleRate;
  23674. /** The number of bits per sample, e.g. 16, 24, 32. */
  23675. unsigned int bitsPerSample;
  23676. /** The total number of samples in the audio stream. */
  23677. int64 lengthInSamples;
  23678. /** The total number of channels in the audio stream. */
  23679. unsigned int numChannels;
  23680. /** Indicates whether the data is floating-point or fixed. */
  23681. bool usesFloatingPointData;
  23682. /** A set of metadata values that the reader has pulled out of the stream.
  23683. Exactly what these values are depends on the format, so you can
  23684. check out the format implementation code to see what kind of stuff
  23685. they understand.
  23686. */
  23687. StringPairArray metadataValues;
  23688. /** The input stream, for use by subclasses. */
  23689. InputStream* input;
  23690. /** Subclasses must implement this method to perform the low-level read operation.
  23691. Callers should use read() instead of calling this directly.
  23692. @param destSamples the array of destination buffers to fill. Some of these
  23693. pointers may be null
  23694. @param numDestChannels the number of items in the destSamples array. This
  23695. value is guaranteed not to be greater than the number of
  23696. channels that this reader object contains
  23697. @param startOffsetInDestBuffer the number of samples from the start of the
  23698. dest data at which to begin writing
  23699. @param startSampleInFile the number of samples into the source data at which
  23700. to begin reading. This value is guaranteed to be >= 0.
  23701. @param numSamples the number of samples to read
  23702. */
  23703. virtual bool readSamples (int** destSamples,
  23704. int numDestChannels,
  23705. int startOffsetInDestBuffer,
  23706. int64 startSampleInFile,
  23707. int numSamples) = 0;
  23708. juce_UseDebuggingNewOperator
  23709. private:
  23710. String formatName;
  23711. AudioFormatReader (const AudioFormatReader&);
  23712. const AudioFormatReader& operator= (const AudioFormatReader&);
  23713. };
  23714. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23715. /********* End of inlined file: juce_AudioFormatReader.h *********/
  23716. /**
  23717. A type of AudioSource that will read from an AudioFormatReader.
  23718. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23719. */
  23720. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23721. {
  23722. public:
  23723. /** Creates an AudioFormatReaderSource for a given reader.
  23724. @param sourceReader the reader to use as the data source
  23725. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23726. when this object is deleted; if false it will be
  23727. left up to the caller to manage its lifetime
  23728. */
  23729. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23730. const bool deleteReaderWhenThisIsDeleted);
  23731. /** Destructor. */
  23732. ~AudioFormatReaderSource();
  23733. /** Toggles loop-mode.
  23734. If set to true, it will continuously loop the input source. If false,
  23735. it will just emit silence after the source has finished.
  23736. @see isLooping
  23737. */
  23738. void setLooping (const bool shouldLoop) throw();
  23739. /** Returns whether loop-mode is turned on or not. */
  23740. bool isLooping() const { return looping; }
  23741. /** Returns the reader that's being used. */
  23742. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23743. /** Implementation of the AudioSource method. */
  23744. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23745. /** Implementation of the AudioSource method. */
  23746. void releaseResources();
  23747. /** Implementation of the AudioSource method. */
  23748. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23749. /** Implements the PositionableAudioSource method. */
  23750. void setNextReadPosition (int newPosition);
  23751. /** Implements the PositionableAudioSource method. */
  23752. int getNextReadPosition() const;
  23753. /** Implements the PositionableAudioSource method. */
  23754. int getTotalLength() const;
  23755. juce_UseDebuggingNewOperator
  23756. private:
  23757. AudioFormatReader* reader;
  23758. bool deleteReader;
  23759. int volatile nextPlayPos;
  23760. bool volatile looping;
  23761. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23762. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23763. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23764. };
  23765. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23766. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  23767. #endif
  23768. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23769. #endif
  23770. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23771. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  23772. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23773. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23774. /**
  23775. Wrapper class to continuously stream audio from an audio source to an
  23776. AudioIODevice.
  23777. This object acts as an AudioIODeviceCallback, so can be attached to an
  23778. output device, and will stream audio from an AudioSource.
  23779. */
  23780. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23781. {
  23782. public:
  23783. /** Creates an empty AudioSourcePlayer. */
  23784. AudioSourcePlayer();
  23785. /** Destructor.
  23786. Make sure this object isn't still being used by an AudioIODevice before
  23787. deleting it!
  23788. */
  23789. virtual ~AudioSourcePlayer();
  23790. /** Changes the current audio source to play from.
  23791. If the source passed in is already being used, this method will do nothing.
  23792. If the source is not null, its prepareToPlay() method will be called
  23793. before it starts being used for playback.
  23794. If there's another source currently playing, its releaseResources() method
  23795. will be called after it has been swapped for the new one.
  23796. @param newSource the new source to use - this will NOT be deleted
  23797. by this object when no longer needed, so it's the
  23798. caller's responsibility to manage it.
  23799. */
  23800. void setSource (AudioSource* newSource);
  23801. /** Returns the source that's playing.
  23802. May return 0 if there's no source.
  23803. */
  23804. AudioSource* getCurrentSource() const throw() { return source; }
  23805. /** Sets a gain to apply to the audio data. */
  23806. void setGain (const float newGain) throw();
  23807. /** Implementation of the AudioIODeviceCallback method. */
  23808. void audioDeviceIOCallback (const float** inputChannelData,
  23809. int totalNumInputChannels,
  23810. float** outputChannelData,
  23811. int totalNumOutputChannels,
  23812. int numSamples);
  23813. /** Implementation of the AudioIODeviceCallback method. */
  23814. void audioDeviceAboutToStart (AudioIODevice* device);
  23815. /** Implementation of the AudioIODeviceCallback method. */
  23816. void audioDeviceStopped();
  23817. juce_UseDebuggingNewOperator
  23818. private:
  23819. CriticalSection readLock;
  23820. AudioSource* source;
  23821. double sampleRate;
  23822. int bufferSize;
  23823. float* channels [128];
  23824. float* outputChans [128];
  23825. const float* inputChans [128];
  23826. AudioSampleBuffer tempBuffer;
  23827. float lastGain, gain;
  23828. AudioSourcePlayer (const AudioSourcePlayer&);
  23829. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23830. };
  23831. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23832. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  23833. #endif
  23834. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23835. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  23836. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23837. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23838. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  23839. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23840. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23841. /**
  23842. An AudioSource which takes another source as input, and buffers it using a thread.
  23843. Create this as a wrapper around another thread, and it will read-ahead with
  23844. a background thread to smooth out playback. You can either create one of these
  23845. directly, or use it indirectly using an AudioTransportSource.
  23846. @see PositionableAudioSource, AudioTransportSource
  23847. */
  23848. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23849. {
  23850. public:
  23851. /** Creates a BufferingAudioSource.
  23852. @param source the input source to read from
  23853. @param deleteSourceWhenDeleted if true, then the input source object will
  23854. be deleted when this object is deleted
  23855. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23856. */
  23857. BufferingAudioSource (PositionableAudioSource* source,
  23858. const bool deleteSourceWhenDeleted,
  23859. int numberOfSamplesToBuffer);
  23860. /** Destructor.
  23861. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23862. flag was set in the constructor.
  23863. */
  23864. ~BufferingAudioSource();
  23865. /** Implementation of the AudioSource method. */
  23866. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23867. /** Implementation of the AudioSource method. */
  23868. void releaseResources();
  23869. /** Implementation of the AudioSource method. */
  23870. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23871. /** Implements the PositionableAudioSource method. */
  23872. void setNextReadPosition (int newPosition);
  23873. /** Implements the PositionableAudioSource method. */
  23874. int getNextReadPosition() const;
  23875. /** Implements the PositionableAudioSource method. */
  23876. int getTotalLength() const { return source->getTotalLength(); }
  23877. /** Implements the PositionableAudioSource method. */
  23878. bool isLooping() const { return source->isLooping(); }
  23879. juce_UseDebuggingNewOperator
  23880. private:
  23881. PositionableAudioSource* source;
  23882. bool deleteSourceWhenDeleted;
  23883. int numberOfSamplesToBuffer;
  23884. AudioSampleBuffer buffer;
  23885. CriticalSection bufferStartPosLock;
  23886. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23887. bool wasSourceLooping;
  23888. double volatile sampleRate;
  23889. friend class SharedBufferingAudioSourceThread;
  23890. bool readNextBufferChunk();
  23891. void readBufferSection (int start, int length, int bufferOffset);
  23892. BufferingAudioSource (const BufferingAudioSource&);
  23893. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  23894. };
  23895. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23896. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  23897. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  23898. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23899. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23900. /**
  23901. A type of AudioSource that takes an input source and changes its sample rate.
  23902. @see AudioSource
  23903. */
  23904. class JUCE_API ResamplingAudioSource : public AudioSource
  23905. {
  23906. public:
  23907. /** Creates a ResamplingAudioSource for a given input source.
  23908. @param inputSource the input source to read from
  23909. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23910. this object is deleted
  23911. */
  23912. ResamplingAudioSource (AudioSource* const inputSource,
  23913. const bool deleteInputWhenDeleted);
  23914. /** Destructor. */
  23915. ~ResamplingAudioSource();
  23916. /** Changes the resampling ratio.
  23917. (This value can be changed at any time, even while the source is running).
  23918. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23919. values will speed it up; lower values will slow it
  23920. down. The ratio must be greater than 0
  23921. */
  23922. void setResamplingRatio (const double samplesInPerOutputSample);
  23923. /** Returns the current resampling ratio.
  23924. This is the value that was set by setResamplingRatio().
  23925. */
  23926. double getResamplingRatio() const throw() { return ratio; }
  23927. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23928. void releaseResources();
  23929. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23930. juce_UseDebuggingNewOperator
  23931. private:
  23932. AudioSource* const input;
  23933. const bool deleteInputWhenDeleted;
  23934. double ratio, lastRatio;
  23935. AudioSampleBuffer buffer;
  23936. int bufferPos, sampsInBuffer;
  23937. double subSampleOffset;
  23938. double coefficients[6];
  23939. CriticalSection ratioLock;
  23940. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23941. void createLowPass (const double proportionalRate);
  23942. struct FilterState
  23943. {
  23944. double x1, x2, y1, y2;
  23945. };
  23946. FilterState filterStates[2];
  23947. void resetFilters();
  23948. void applyFilter (float* samples, int num, FilterState& fs);
  23949. ResamplingAudioSource (const ResamplingAudioSource&);
  23950. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23951. };
  23952. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23953. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  23954. /**
  23955. An AudioSource that takes a PositionableAudioSource and allows it to be
  23956. played, stopped, started, etc.
  23957. This can also be told use a buffer and background thread to read ahead, and
  23958. if can correct for different sample-rates.
  23959. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23960. to control playback of an audio file.
  23961. @see AudioSource, AudioSourcePlayer
  23962. */
  23963. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23964. public ChangeBroadcaster
  23965. {
  23966. public:
  23967. /** Creates an AudioTransportSource.
  23968. After creating one of these, use the setSource() method to select an input source.
  23969. */
  23970. AudioTransportSource();
  23971. /** Destructor. */
  23972. ~AudioTransportSource();
  23973. /** Sets the reader that is being used as the input source.
  23974. This will stop playback, reset the position to 0 and change to the new reader.
  23975. The source passed in will not be deleted by this object, so must be managed by
  23976. the caller.
  23977. @param newSource the new input source to use. This may be zero
  23978. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23979. is zero, no reading ahead will be done; if it's
  23980. greater than zero, a BufferingAudioSource will be used
  23981. to do the reading-ahead
  23982. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23983. rate of the source, and playback will be sample-rate
  23984. adjusted to maintain playback at the correct pitch. If
  23985. this is 0, no sample-rate adjustment will be performed
  23986. */
  23987. void setSource (PositionableAudioSource* const newSource,
  23988. int readAheadBufferSize = 0,
  23989. double sourceSampleRateToCorrectFor = 0.0);
  23990. /** Changes the current playback position in the source stream.
  23991. The next time the getNextAudioBlock() method is called, this
  23992. is the time from which it'll read data.
  23993. @see getPosition
  23994. */
  23995. void setPosition (double newPosition);
  23996. /** Returns the position that the next data block will be read from
  23997. This is a time in seconds.
  23998. */
  23999. double getCurrentPosition() const;
  24000. /** Returns true if the player has stopped because its input stream ran out of data.
  24001. */
  24002. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  24003. /** Starts playing (if a source has been selected).
  24004. If it starts playing, this will send a message to any ChangeListeners
  24005. that are registered with this object.
  24006. */
  24007. void start();
  24008. /** Stops playing.
  24009. If it's actually playing, this will send a message to any ChangeListeners
  24010. that are registered with this object.
  24011. */
  24012. void stop();
  24013. /** Returns true if it's currently playing. */
  24014. bool isPlaying() const throw() { return playing; }
  24015. /** Changes the gain to apply to the output.
  24016. @param newGain a factor by which to multiply the outgoing samples,
  24017. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  24018. */
  24019. void setGain (const float newGain) throw();
  24020. /** Returns the current gain setting.
  24021. @see setGain
  24022. */
  24023. float getGain() const throw() { return gain; }
  24024. /** Implementation of the AudioSource method. */
  24025. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24026. /** Implementation of the AudioSource method. */
  24027. void releaseResources();
  24028. /** Implementation of the AudioSource method. */
  24029. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24030. /** Implements the PositionableAudioSource method. */
  24031. void setNextReadPosition (int newPosition);
  24032. /** Implements the PositionableAudioSource method. */
  24033. int getNextReadPosition() const;
  24034. /** Implements the PositionableAudioSource method. */
  24035. int getTotalLength() const;
  24036. /** Implements the PositionableAudioSource method. */
  24037. bool isLooping() const;
  24038. juce_UseDebuggingNewOperator
  24039. private:
  24040. PositionableAudioSource* source;
  24041. ResamplingAudioSource* resamplerSource;
  24042. BufferingAudioSource* bufferingSource;
  24043. PositionableAudioSource* positionableSource;
  24044. AudioSource* masterSource;
  24045. CriticalSection callbackLock;
  24046. float volatile gain, lastGain;
  24047. bool volatile playing, stopped;
  24048. double sampleRate, sourceSampleRate;
  24049. int blockSize, readAheadBufferSize;
  24050. bool isPrepared, inputStreamEOF;
  24051. AudioTransportSource (const AudioTransportSource&);
  24052. const AudioTransportSource& operator= (const AudioTransportSource&);
  24053. };
  24054. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24055. /********* End of inlined file: juce_AudioTransportSource.h *********/
  24056. #endif
  24057. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24058. #endif
  24059. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24060. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  24061. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24062. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24063. /**
  24064. An AudioSource that takes the audio from another source, and re-maps its
  24065. input and output channels to a different arrangement.
  24066. You can use this to increase or decrease the number of channels that an
  24067. audio source uses, or to re-order those channels.
  24068. Call the reset() method before using it to set up a default mapping, and then
  24069. the setInputChannelMapping() and setOutputChannelMapping() methods to
  24070. create an appropriate mapping, otherwise no channels will be connected and
  24071. it'll produce silence.
  24072. @see AudioSource
  24073. */
  24074. class ChannelRemappingAudioSource : public AudioSource
  24075. {
  24076. public:
  24077. /** Creates a remapping source that will pass on audio from the given input.
  24078. @param source the input source to use. Make sure that this doesn't
  24079. get deleted before the ChannelRemappingAudioSource object
  24080. @param deleteSourceWhenDeleted if true, the input source will be deleted
  24081. when this object is deleted, if false, the caller is
  24082. responsible for its deletion
  24083. */
  24084. ChannelRemappingAudioSource (AudioSource* const source,
  24085. const bool deleteSourceWhenDeleted);
  24086. /** Destructor. */
  24087. ~ChannelRemappingAudioSource();
  24088. /** Specifies a number of channels that this audio source must produce from its
  24089. getNextAudioBlock() callback.
  24090. */
  24091. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  24092. /** Clears any mapped channels.
  24093. After this, no channels are mapped, so this object will produce silence. Create
  24094. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  24095. */
  24096. void clearAllMappings() throw();
  24097. /** Creates an input channel mapping.
  24098. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  24099. data will be sent to destChannelIndex of our input source.
  24100. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  24101. source specified when this object was created).
  24102. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  24103. during our getNextAudioBlock() callback
  24104. */
  24105. void setInputChannelMapping (const int destChannelIndex,
  24106. const int sourceChannelIndex) throw();
  24107. /** Creates an output channel mapping.
  24108. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  24109. our input audio source will be copied to channel destChannelIndex of the final buffer.
  24110. @param sourceChannelIndex the index of an output channel coming from our input audio source
  24111. (i.e. the source specified when this object was created).
  24112. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  24113. during our getNextAudioBlock() callback
  24114. */
  24115. void setOutputChannelMapping (const int sourceChannelIndex,
  24116. const int destChannelIndex) throw();
  24117. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  24118. our input audio source.
  24119. */
  24120. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  24121. /** Returns the output channel to which channel outputChannelIndex of our input audio
  24122. source will be sent to.
  24123. */
  24124. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  24125. /** Returns an XML object to encapsulate the state of the mappings.
  24126. @see restoreFromXml
  24127. */
  24128. XmlElement* createXml() const throw();
  24129. /** Restores the mappings from an XML object created by createXML().
  24130. @see createXml
  24131. */
  24132. void restoreFromXml (const XmlElement& e) throw();
  24133. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24134. void releaseResources();
  24135. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24136. juce_UseDebuggingNewOperator
  24137. private:
  24138. int requiredNumberOfChannels;
  24139. Array <int> remappedInputs, remappedOutputs;
  24140. AudioSource* const source;
  24141. const bool deleteSourceWhenDeleted;
  24142. AudioSampleBuffer buffer;
  24143. AudioSourceChannelInfo remappedInfo;
  24144. CriticalSection lock;
  24145. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  24146. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  24147. };
  24148. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24149. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  24150. #endif
  24151. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24152. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  24153. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24154. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24155. /**
  24156. An AudioSource that performs an IIR filter on another source.
  24157. */
  24158. class JUCE_API IIRFilterAudioSource : public AudioSource
  24159. {
  24160. public:
  24161. /** Creates a IIRFilterAudioSource for a given input source.
  24162. @param inputSource the input source to read from
  24163. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24164. this object is deleted
  24165. */
  24166. IIRFilterAudioSource (AudioSource* const inputSource,
  24167. const bool deleteInputWhenDeleted);
  24168. /** Destructor. */
  24169. ~IIRFilterAudioSource();
  24170. /** Changes the filter to use the same parameters as the one being passed in.
  24171. */
  24172. void setFilterParameters (const IIRFilter& newSettings);
  24173. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24174. void releaseResources();
  24175. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24176. juce_UseDebuggingNewOperator
  24177. private:
  24178. AudioSource* const input;
  24179. const bool deleteInputWhenDeleted;
  24180. OwnedArray <IIRFilter> iirFilters;
  24181. IIRFilterAudioSource (const IIRFilterAudioSource&);
  24182. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  24183. };
  24184. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24185. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  24186. #endif
  24187. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24188. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  24189. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24190. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24191. /**
  24192. An AudioSource that mixes together the output of a set of other AudioSources.
  24193. Input sources can be added and removed while the mixer is running as long as their
  24194. prepareToPlay() and releaseResources() methods are called before and after adding
  24195. them to the mixer.
  24196. */
  24197. class JUCE_API MixerAudioSource : public AudioSource
  24198. {
  24199. public:
  24200. /** Creates a MixerAudioSource.
  24201. */
  24202. MixerAudioSource();
  24203. /** Destructor. */
  24204. ~MixerAudioSource();
  24205. /** Adds an input source to the mixer.
  24206. If the mixer is running you'll need to make sure that the input source
  24207. is ready to play by calling its prepareToPlay() method before adding it.
  24208. If the mixer is stopped, then its input sources will be automatically
  24209. prepared when the mixer's prepareToPlay() method is called.
  24210. @param newInput the source to add to the mixer
  24211. @param deleteWhenRemoved if true, then this source will be deleted when
  24212. the mixer is deleted or when removeAllInputs() is
  24213. called (unless the source is previously removed
  24214. with the removeInputSource method)
  24215. */
  24216. void addInputSource (AudioSource* newInput,
  24217. const bool deleteWhenRemoved);
  24218. /** Removes an input source.
  24219. If the mixer is running, this will remove the source but not call its
  24220. releaseResources() method, so the caller might want to do this manually.
  24221. @param input the source to remove
  24222. @param deleteSource whether to delete this source after it's been removed
  24223. */
  24224. void removeInputSource (AudioSource* input,
  24225. const bool deleteSource);
  24226. /** Removes all the input sources.
  24227. If the mixer is running, this will remove the sources but not call their
  24228. releaseResources() method, so the caller might want to do this manually.
  24229. Any sources which were added with the deleteWhenRemoved flag set will be
  24230. deleted by this method.
  24231. */
  24232. void removeAllInputs();
  24233. /** Implementation of the AudioSource method.
  24234. This will call prepareToPlay() on all its input sources.
  24235. */
  24236. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24237. /** Implementation of the AudioSource method.
  24238. This will call releaseResources() on all its input sources.
  24239. */
  24240. void releaseResources();
  24241. /** Implementation of the AudioSource method. */
  24242. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24243. juce_UseDebuggingNewOperator
  24244. private:
  24245. VoidArray inputs;
  24246. BitArray inputsToDelete;
  24247. CriticalSection lock;
  24248. AudioSampleBuffer tempBuffer;
  24249. double currentSampleRate;
  24250. int bufferSizeExpected;
  24251. MixerAudioSource (const MixerAudioSource&);
  24252. const MixerAudioSource& operator= (const MixerAudioSource&);
  24253. };
  24254. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24255. /********* End of inlined file: juce_MixerAudioSource.h *********/
  24256. #endif
  24257. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24258. #endif
  24259. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24260. #endif
  24261. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24262. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24263. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24264. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24265. /**
  24266. A simple AudioSource that generates a sine wave.
  24267. */
  24268. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24269. {
  24270. public:
  24271. /** Creates a ToneGeneratorAudioSource. */
  24272. ToneGeneratorAudioSource();
  24273. /** Destructor. */
  24274. ~ToneGeneratorAudioSource();
  24275. /** Sets the signal's amplitude. */
  24276. void setAmplitude (const float newAmplitude);
  24277. /** Sets the signal's frequency. */
  24278. void setFrequency (const double newFrequencyHz);
  24279. /** Implementation of the AudioSource method. */
  24280. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24281. /** Implementation of the AudioSource method. */
  24282. void releaseResources();
  24283. /** Implementation of the AudioSource method. */
  24284. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24285. juce_UseDebuggingNewOperator
  24286. private:
  24287. double frequency, sampleRate;
  24288. double currentPhase, phasePerSample;
  24289. float amplitude;
  24290. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24291. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24292. };
  24293. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24294. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  24295. #endif
  24296. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24297. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  24298. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24299. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24300. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  24301. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24302. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24303. class AudioDeviceManager;
  24304. class Component;
  24305. /**
  24306. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24307. To get a list of available audio driver types, use the createDeviceTypes()
  24308. method. Each of the objects returned can then be used to list the available
  24309. devices of that type. E.g.
  24310. @code
  24311. OwnedArray <AudioIODeviceType> types;
  24312. AudioIODeviceType::createDeviceTypes (types);
  24313. for (int i = 0; i < types.size(); ++i)
  24314. {
  24315. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24316. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24317. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24318. for (int j = 0; j < deviceNames.size(); ++j)
  24319. {
  24320. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24321. ...
  24322. }
  24323. }
  24324. @endcode
  24325. For an easier way of managing audio devices and their settings, have a look at the
  24326. AudioDeviceManager class.
  24327. @see AudioIODevice, AudioDeviceManager
  24328. */
  24329. class JUCE_API AudioIODeviceType
  24330. {
  24331. public:
  24332. /** Returns the name of this type of driver that this object manages.
  24333. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24334. */
  24335. const String& getTypeName() const throw() { return typeName; }
  24336. /** Refreshes the object's cached list of known devices.
  24337. This must be called at least once before calling getDeviceNames() or any of
  24338. the other device creation methods.
  24339. */
  24340. virtual void scanForDevices() = 0;
  24341. /** Returns the list of available devices of this type.
  24342. The scanForDevices() method must have been called to create this list.
  24343. @param wantInputNames only really used by DirectSound where devices are split up
  24344. into inputs and outputs, this indicates whether to use
  24345. the input or output name to refer to a pair of devices.
  24346. */
  24347. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  24348. /** Returns the name of the default device.
  24349. This will be one of the names from the getDeviceNames() list.
  24350. @param forInput if true, this means that a default input device should be
  24351. returned; if false, it should return the default output
  24352. */
  24353. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  24354. /** Returns the index of a given device in the list of device names.
  24355. If asInput is true, it shows the index in the inputs list, otherwise it
  24356. looks for it in the outputs list.
  24357. */
  24358. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  24359. /** Returns true if two different devices can be used for the input and output.
  24360. */
  24361. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24362. /** Creates one of the devices of this type.
  24363. The deviceName must be one of the strings returned by getDeviceNames(), and
  24364. scanForDevices() must have been called before this method is used.
  24365. */
  24366. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24367. const String& inputDeviceName) = 0;
  24368. struct DeviceSetupDetails
  24369. {
  24370. AudioDeviceManager* manager;
  24371. int minNumInputChannels, maxNumInputChannels;
  24372. int minNumOutputChannels, maxNumOutputChannels;
  24373. bool useStereoPairs;
  24374. };
  24375. /** Destructor. */
  24376. virtual ~AudioIODeviceType();
  24377. protected:
  24378. AudioIODeviceType (const tchar* const typeName);
  24379. private:
  24380. String typeName;
  24381. AudioIODeviceType (const AudioIODeviceType&);
  24382. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  24383. };
  24384. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24385. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  24386. /********* Start of inlined file: juce_MidiOutput.h *********/
  24387. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24388. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24389. /**
  24390. Represents a midi output device.
  24391. To create one of these, use the static getDevices() method to find out what
  24392. outputs are available, then use the openDevice() method to try to open one.
  24393. @see MidiInput
  24394. */
  24395. class JUCE_API MidiOutput : private Thread
  24396. {
  24397. public:
  24398. /** Returns a list of the available midi output devices.
  24399. You can open one of the devices by passing its index into the
  24400. openDevice() method.
  24401. @see getDefaultDeviceIndex, openDevice
  24402. */
  24403. static const StringArray getDevices();
  24404. /** Returns the index of the default midi output device to use.
  24405. This refers to the index in the list returned by getDevices().
  24406. */
  24407. static int getDefaultDeviceIndex();
  24408. /** Tries to open one of the midi output devices.
  24409. This will return a MidiOutput object if it manages to open it. You can then
  24410. send messages to this device, and delete it when no longer needed.
  24411. If the device can't be opened, this will return a null pointer.
  24412. @param deviceIndex the index of a device from the list returned by getDevices()
  24413. @see getDevices
  24414. */
  24415. static MidiOutput* openDevice (int deviceIndex);
  24416. #if JUCE_LINUX || DOXYGEN
  24417. /** LINUX ONLY - This will try to create a new midi output device.
  24418. This will attempt to create a new midi output device that other apps can connect
  24419. to and use as their midi input.
  24420. Returns 0 if a device can't be created.
  24421. @param deviceName the name to use for the new device
  24422. */
  24423. static MidiOutput* createNewDevice (const String& deviceName);
  24424. #endif
  24425. /** Destructor. */
  24426. virtual ~MidiOutput();
  24427. /** Makes this device output a midi message.
  24428. @see MidiMessage
  24429. */
  24430. virtual void sendMessageNow (const MidiMessage& message);
  24431. /** Sends a midi reset to the device. */
  24432. virtual void reset();
  24433. /** Returns the current volume setting for this device. */
  24434. virtual bool getVolume (float& leftVol,
  24435. float& rightVol);
  24436. /** Changes the overall volume for this device. */
  24437. virtual void setVolume (float leftVol,
  24438. float rightVol);
  24439. /** This lets you supply a block of messages that will be sent out at some point
  24440. in the future.
  24441. The MidiOutput class has an internal thread that can send out timestamped
  24442. messages - this appends a set of messages to its internal buffer, ready for
  24443. sending.
  24444. This will only work if you've already started the thread with startBackgroundThread().
  24445. A time is supplied, at which the block of messages should be sent. This time uses
  24446. the same time base as Time::getMillisecondCounter(), and must be in the future.
  24447. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  24448. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  24449. samplesPerSecondForBuffer value is needed to convert this sample position to a
  24450. real time.
  24451. */
  24452. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  24453. const double millisecondCounterToStartAt,
  24454. double samplesPerSecondForBuffer) throw();
  24455. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  24456. */
  24457. virtual void clearAllPendingMessages() throw();
  24458. /** Starts up a background thread so that the device can send blocks of data.
  24459. Call this to get the device ready, before using sendBlockOfMessages().
  24460. */
  24461. virtual void startBackgroundThread() throw();
  24462. /** Stops the background thread, and clears any pending midi events.
  24463. @see startBackgroundThread
  24464. */
  24465. virtual void stopBackgroundThread() throw();
  24466. juce_UseDebuggingNewOperator
  24467. protected:
  24468. void* internal;
  24469. struct PendingMessage
  24470. {
  24471. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  24472. MidiMessage message;
  24473. PendingMessage* next;
  24474. juce_UseDebuggingNewOperator
  24475. };
  24476. CriticalSection lock;
  24477. PendingMessage* firstMessage;
  24478. MidiOutput() throw();
  24479. MidiOutput (const MidiOutput&);
  24480. void run();
  24481. };
  24482. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24483. /********* End of inlined file: juce_MidiOutput.h *********/
  24484. /********* Start of inlined file: juce_ComboBox.h *********/
  24485. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24486. #define __JUCE_COMBOBOX_JUCEHEADER__
  24487. /********* Start of inlined file: juce_Label.h *********/
  24488. #ifndef __JUCE_LABEL_JUCEHEADER__
  24489. #define __JUCE_LABEL_JUCEHEADER__
  24490. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  24491. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24492. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24493. /**
  24494. Object for monitoring a component, and later testing whether it's still valid.
  24495. Slightly obscure, this one, but it's used internally for making sure that
  24496. after some callbacks, a component hasn't been deleted. It's more reliable than
  24497. just using isValidComponent(), which can provide false-positives if a new
  24498. component is created at the same memory location as an old one.
  24499. */
  24500. class JUCE_API ComponentDeletionWatcher
  24501. {
  24502. public:
  24503. /** Creates a watcher for a given component.
  24504. The component must be valid at the time it's passed in.
  24505. */
  24506. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  24507. /** Destructor. */
  24508. ~ComponentDeletionWatcher() throw();
  24509. /** Returns true if the component has been deleted since the time that this
  24510. object was created.
  24511. */
  24512. bool hasBeenDeleted() const throw();
  24513. /** Returns the component that's being watched, or null if it has been deleted. */
  24514. const Component* getComponent() const throw();
  24515. juce_UseDebuggingNewOperator
  24516. private:
  24517. const Component* const componentToWatch;
  24518. const uint32 componentUID;
  24519. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  24520. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  24521. };
  24522. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  24523. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  24524. /********* Start of inlined file: juce_TextEditor.h *********/
  24525. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24526. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24527. /********* Start of inlined file: juce_UndoManager.h *********/
  24528. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  24529. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  24530. /********* Start of inlined file: juce_UndoableAction.h *********/
  24531. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  24532. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  24533. /**
  24534. Used by the UndoManager class to store an action which can be done
  24535. and undone.
  24536. @see UndoManager
  24537. */
  24538. class JUCE_API UndoableAction
  24539. {
  24540. protected:
  24541. /** Creates an action. */
  24542. UndoableAction() throw() {}
  24543. public:
  24544. /** Destructor. */
  24545. virtual ~UndoableAction() {}
  24546. /** Overridden by a subclass to perform the action.
  24547. This method is called by the UndoManager, and shouldn't be used directly by
  24548. applications.
  24549. Be careful not to make any calls in a perform() method that could call
  24550. recursively back into the UndoManager::perform() method
  24551. @returns true if the action could be performed.
  24552. @see UndoManager::perform
  24553. */
  24554. virtual bool perform() = 0;
  24555. /** Overridden by a subclass to undo the action.
  24556. This method is called by the UndoManager, and shouldn't be used directly by
  24557. applications.
  24558. Be careful not to make any calls in an undo() method that could call
  24559. recursively back into the UndoManager::perform() method
  24560. @returns true if the action could be undone without any errors.
  24561. @see UndoManager::perform
  24562. */
  24563. virtual bool undo() = 0;
  24564. /** Returns a value to indicate how much memory this object takes up.
  24565. Because the UndoManager keeps a list of UndoableActions, this is used
  24566. to work out how much space each one will take up, so that the UndoManager
  24567. can work out how many to keep.
  24568. The default value returned here is 10 - units are arbitrary and
  24569. don't have to be accurate.
  24570. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  24571. UndoManager::setMaxNumberOfStoredUnits
  24572. */
  24573. virtual int getSizeInUnits() { return 10; }
  24574. };
  24575. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  24576. /********* End of inlined file: juce_UndoableAction.h *********/
  24577. /**
  24578. Manages a list of undo/redo commands.
  24579. An UndoManager object keeps a list of past actions and can use these actions
  24580. to move backwards and forwards through an undo history.
  24581. To use it, create subclasses of UndoableAction which perform all the
  24582. actions you need, then when you need to actually perform an action, create one
  24583. and pass it to the UndoManager's perform() method.
  24584. The manager also uses the concept of 'transactions' to group the actions
  24585. together - all actions performed between calls to beginNewTransaction() are
  24586. grouped together and are all undone/redone as a group.
  24587. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  24588. when actions are performed or undone.
  24589. @see UndoableAction
  24590. */
  24591. class JUCE_API UndoManager : public ChangeBroadcaster
  24592. {
  24593. public:
  24594. /** Creates an UndoManager.
  24595. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24596. to indicate how much storage it takes up
  24597. (UndoableAction::getSizeInUnits()), so this
  24598. lets you specify the maximum total number of
  24599. units that the undomanager is allowed to
  24600. keep in memory before letting the older actions
  24601. drop off the end of the list.
  24602. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24603. that will be kept, even if this involves exceeding
  24604. the amount of space specified in maxNumberOfUnitsToKeep
  24605. */
  24606. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  24607. const int minimumTransactionsToKeep = 30);
  24608. /** Destructor. */
  24609. ~UndoManager();
  24610. /** Deletes all stored actions in the list. */
  24611. void clearUndoHistory();
  24612. /** Returns the current amount of space to use for storing UndoableAction objects.
  24613. @see setMaxNumberOfStoredUnits
  24614. */
  24615. int getNumberOfUnitsTakenUpByStoredCommands() const;
  24616. /** Sets the amount of space that can be used for storing UndoableAction objects.
  24617. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  24618. to indicate how much storage it takes up
  24619. (UndoableAction::getSizeInUnits()), so this
  24620. lets you specify the maximum total number of
  24621. units that the undomanager is allowed to
  24622. keep in memory before letting the older actions
  24623. drop off the end of the list.
  24624. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  24625. that will be kept, even if this involves exceeding
  24626. the amount of space specified in maxNumberOfUnitsToKeep
  24627. @see getNumberOfUnitsTakenUpByStoredCommands
  24628. */
  24629. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  24630. const int minimumTransactionsToKeep);
  24631. /** Performs an action and adds it to the undo history list.
  24632. @param action the action to perform - this will be deleted by the UndoManager
  24633. when no longer needed
  24634. @param actionName if this string is non-empty, the current transaction will be
  24635. given this name; if it's empty, the current transaction name will
  24636. be left unchanged. See setCurrentTransactionName()
  24637. @returns true if the command succeeds - see UndoableAction::perform
  24638. @see beginNewTransaction
  24639. */
  24640. bool perform (UndoableAction* const action,
  24641. const String& actionName = String::empty);
  24642. /** Starts a new group of actions that together will be treated as a single transaction.
  24643. All actions that are passed to the perform() method between calls to this
  24644. method are grouped together and undone/redone together by a single call to
  24645. undo() or redo().
  24646. @param actionName a description of the transaction that is about to be
  24647. performed
  24648. */
  24649. void beginNewTransaction (const String& actionName = String::empty);
  24650. /** Changes the name stored for the current transaction.
  24651. Each transaction is given a name when the beginNewTransaction() method is
  24652. called, but this can be used to change that name without starting a new
  24653. transaction.
  24654. */
  24655. void setCurrentTransactionName (const String& newName);
  24656. /** Returns true if there's at least one action in the list to undo.
  24657. @see getUndoDescription, undo, canRedo
  24658. */
  24659. bool canUndo() const;
  24660. /** Returns the description of the transaction that would be next to get undone.
  24661. The description returned is the one that was passed into beginNewTransaction
  24662. before the set of actions was performed.
  24663. @see undo
  24664. */
  24665. const String getUndoDescription() const;
  24666. /** Tries to roll-back the last transaction.
  24667. @returns true if the transaction can be undone, and false if it fails, or
  24668. if there aren't any transactions to undo
  24669. */
  24670. bool undo();
  24671. /** Tries to roll-back any actions that were added to the current transaction.
  24672. This will perform an undo() only if there are some actions in the undo list
  24673. that were added after the last call to beginNewTransaction().
  24674. This is useful because it lets you call beginNewTransaction(), then
  24675. perform an operation which may or may not actually perform some actions, and
  24676. then call this method to get rid of any actions that might have been done
  24677. without it rolling back the previous transaction if nothing was actually
  24678. done.
  24679. @returns true if any actions were undone.
  24680. */
  24681. bool undoCurrentTransactionOnly();
  24682. /** Returns a list of the UndoableAction objects that have been performed during the
  24683. transaction that is currently open.
  24684. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  24685. were to be called now.
  24686. The first item in the list is the earliest action performed.
  24687. */
  24688. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  24689. /** Returns true if there's at least one action in the list to redo.
  24690. @see getRedoDescription, redo, canUndo
  24691. */
  24692. bool canRedo() const;
  24693. /** Returns the description of the transaction that would be next to get redone.
  24694. The description returned is the one that was passed into beginNewTransaction
  24695. before the set of actions was performed.
  24696. @see redo
  24697. */
  24698. const String getRedoDescription() const;
  24699. /** Tries to redo the last transaction that was undone.
  24700. @returns true if the transaction can be redone, and false if it fails, or
  24701. if there aren't any transactions to redo
  24702. */
  24703. bool redo();
  24704. juce_UseDebuggingNewOperator
  24705. private:
  24706. OwnedArray <OwnedArray <UndoableAction> > transactions;
  24707. StringArray transactionNames;
  24708. String currentTransactionName;
  24709. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  24710. bool newTransaction, reentrancyCheck;
  24711. // disallow copy constructor
  24712. UndoManager (const UndoManager&);
  24713. const UndoManager& operator= (const UndoManager&);
  24714. };
  24715. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  24716. /********* End of inlined file: juce_UndoManager.h *********/
  24717. class TextEditor;
  24718. class TextHolderComponent;
  24719. /**
  24720. Receives callbacks from a TextEditor component when it changes.
  24721. @see TextEditor::addListener
  24722. */
  24723. class JUCE_API TextEditorListener
  24724. {
  24725. public:
  24726. /** Destructor. */
  24727. virtual ~TextEditorListener() {}
  24728. /** Called when the user changes the text in some way. */
  24729. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24730. /** Called when the user presses the return key. */
  24731. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24732. /** Called when the user presses the escape key. */
  24733. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24734. /** Called when the text editor loses focus. */
  24735. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24736. };
  24737. /**
  24738. A component containing text that can be edited.
  24739. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24740. fonts and colours.
  24741. @see TextEditorListener, Label
  24742. */
  24743. class JUCE_API TextEditor : public Component,
  24744. public SettableTooltipClient
  24745. {
  24746. public:
  24747. /** Creates a new, empty text editor.
  24748. @param componentName the name to pass to the component for it to use as its name
  24749. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24750. for all characters that are drawn on screen - e.g. to create
  24751. a password-style textbox containing circular blobs instead of text,
  24752. you could set this value to 0x25cf, which is the unicode character
  24753. for a black splodge (not all fonts include this, though), or 0x2022,
  24754. which is a bullet (probably the best choice for linux).
  24755. */
  24756. TextEditor (const String& componentName = String::empty,
  24757. const tchar passwordCharacter = 0);
  24758. /** Destructor. */
  24759. virtual ~TextEditor();
  24760. /** Puts the editor into either multi- or single-line mode.
  24761. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24762. editor.
  24763. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24764. on if you want a multi-line editor with line-breaks.
  24765. @see isMultiLine, setReturnKeyStartsNewLine
  24766. */
  24767. void setMultiLine (const bool shouldBeMultiLine,
  24768. const bool shouldWordWrap = true);
  24769. /** Returns true if the editor is in multi-line mode.
  24770. */
  24771. bool isMultiLine() const throw();
  24772. /** Changes the behaviour of the return key.
  24773. If set to true, the return key will insert a new-line into the text; if false
  24774. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24775. method. By default this is set to false, and when true it will only insert
  24776. new-lines when in multi-line mode (see setMultiLine()).
  24777. */
  24778. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24779. /** Returns the value set by setReturnKeyStartsNewLine().
  24780. See setReturnKeyStartsNewLine() for more info.
  24781. */
  24782. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24783. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24784. or whether it gets ignored.
  24785. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24786. between components.
  24787. */
  24788. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24789. /** Returns true if the tab key is being used for input.
  24790. @see setTabKeyUsedAsCharacter
  24791. */
  24792. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24793. /** Changes the editor to read-only mode.
  24794. By default, the text editor is not read-only. If you're making it read-only, you
  24795. might also want to call setCaretVisible (false) to get rid of the caret.
  24796. The text can still be highlighted and copied when in read-only mode.
  24797. @see isReadOnly, setCaretVisible
  24798. */
  24799. void setReadOnly (const bool shouldBeReadOnly);
  24800. /** Returns true if the editor is in read-only mode.
  24801. */
  24802. bool isReadOnly() const throw();
  24803. /** Makes the caret visible or invisible.
  24804. By default the caret is visible.
  24805. @see setCaretColour, setCaretPosition
  24806. */
  24807. void setCaretVisible (const bool shouldBeVisible) throw();
  24808. /** Returns true if the caret is enabled.
  24809. @see setCaretVisible
  24810. */
  24811. bool isCaretVisible() const throw() { return caretVisible; }
  24812. /** Enables/disables a vertical scrollbar.
  24813. (This only applies when in multi-line mode). When the text gets too long to fit
  24814. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24815. this is enabled, the scrollbar will be hidden unless it's needed.
  24816. By default the scrollbar is enabled.
  24817. */
  24818. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24819. /** Returns true if scrollbars are enabled.
  24820. @see setScrollbarsShown
  24821. */
  24822. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24823. /** Changes the password character used to disguise the text.
  24824. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24825. for all characters that are drawn on screen - e.g. to create
  24826. a password-style textbox containing circular blobs instead of text,
  24827. you could set this value to 0x25cf, which is the unicode character
  24828. for a black splodge (not all fonts include this, though), or 0x2022,
  24829. which is a bullet (probably the best choice for linux).
  24830. */
  24831. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24832. /** Returns the current password character.
  24833. @see setPasswordCharacter
  24834. l */
  24835. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24836. /** Allows a right-click menu to appear for the editor.
  24837. (This defaults to being enabled).
  24838. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24839. of options such as cut/copy/paste, undo/redo, etc.
  24840. */
  24841. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24842. /** Returns true if the right-click menu is enabled.
  24843. @see setPopupMenuEnabled
  24844. */
  24845. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24846. /** Returns true if a popup-menu is currently being displayed.
  24847. */
  24848. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24849. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24850. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24851. methods.
  24852. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24853. */
  24854. enum ColourIds
  24855. {
  24856. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24857. transparent if necessary. */
  24858. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24859. that because the editor can contain multiple colours, calling this
  24860. method won't change the colour of existing text - to do that, call
  24861. applyFontToAllText() after calling this method.*/
  24862. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24863. the text - this can be transparent if you don't want to show any
  24864. highlighting.*/
  24865. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24866. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24867. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24868. the edge of the component. */
  24869. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24870. the edge of the component when it has focus. */
  24871. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24872. around the edge of the editor. */
  24873. };
  24874. /** Sets the font to use for newly added text.
  24875. This will change the font that will be used next time any text is added or entered
  24876. into the editor. It won't change the font of any existing text - to do that, use
  24877. applyFontToAllText() instead.
  24878. @see applyFontToAllText
  24879. */
  24880. void setFont (const Font& newFont) throw();
  24881. /** Applies a font to all the text in the editor.
  24882. This will also set the current font to use for any new text that's added.
  24883. @see setFont
  24884. */
  24885. void applyFontToAllText (const Font& newFont);
  24886. /** Returns the font that's currently being used for new text.
  24887. @see setFont
  24888. */
  24889. const Font getFont() const throw();
  24890. /** If set to true, focusing on the editor will highlight all its text.
  24891. (Set to false by default).
  24892. This is useful for boxes where you expect the user to re-enter all the
  24893. text when they focus on the component, rather than editing what's already there.
  24894. */
  24895. void setSelectAllWhenFocused (const bool b) throw();
  24896. /** Sets limits on the characters that can be entered.
  24897. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24898. limit is set
  24899. @param allowedCharacters if this is non-empty, then only characters that occur in
  24900. this string are allowed to be entered into the editor.
  24901. */
  24902. void setInputRestrictions (const int maxTextLength,
  24903. const String& allowedCharacters = String::empty) throw();
  24904. /** When the text editor is empty, it can be set to display a message.
  24905. This is handy for things like telling the user what to type in the box - the
  24906. string is only displayed, it's not taken to actually be the contents of
  24907. the editor.
  24908. */
  24909. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24910. /** Changes the size of the scrollbars that are used.
  24911. Handy if you need smaller scrollbars for a small text box.
  24912. */
  24913. void setScrollBarThickness (const int newThicknessPixels);
  24914. /** Shows or hides the buttons on any scrollbars that are used.
  24915. @see ScrollBar::setButtonVisibility
  24916. */
  24917. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24918. /** Registers a listener to be told when things happen to the text.
  24919. @see removeListener
  24920. */
  24921. void addListener (TextEditorListener* const newListener) throw();
  24922. /** Deregisters a listener.
  24923. @see addListener
  24924. */
  24925. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24926. /** Returns the entire contents of the editor. */
  24927. const String getText() const throw();
  24928. /** Returns a section of the contents of the editor. */
  24929. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24930. /** Returns true if there are no characters in the editor.
  24931. This is more efficient than calling getText().isEmpty().
  24932. */
  24933. bool isEmpty() const throw();
  24934. /** Sets the entire content of the editor.
  24935. This will clear the editor and insert the given text (using the current text colour
  24936. and font). You can set the current text colour using
  24937. @code setColour (TextEditor::textColourId, ...);
  24938. @endcode
  24939. @param newText the text to add
  24940. @param sendTextChangeMessage if true, this will cause a change message to
  24941. be sent to all the listeners.
  24942. @see insertText
  24943. */
  24944. void setText (const String& newText,
  24945. const bool sendTextChangeMessage = true);
  24946. /** Inserts some text at the current cursor position.
  24947. If a section of the text is highlighted, it will be replaced by
  24948. this string, otherwise it will be inserted.
  24949. To delete a section of text, you can use setHighlightedRegion() to
  24950. highlight it, and call insertTextAtCursor (String::empty).
  24951. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  24952. */
  24953. void insertTextAtCursor (String textToInsert);
  24954. /** Deletes all the text from the editor. */
  24955. void clear();
  24956. /** Deletes the currently selected region, and puts it on the clipboard.
  24957. @see copy, paste, SystemClipboard
  24958. */
  24959. void cut();
  24960. /** Copies any currently selected region to the clipboard.
  24961. @see cut, paste, SystemClipboard
  24962. */
  24963. void copy();
  24964. /** Pastes the contents of the clipboard into the editor at the cursor position.
  24965. @see cut, copy, SystemClipboard
  24966. */
  24967. void paste();
  24968. /** Moves the caret to be in front of a given character.
  24969. @see getCaretPosition
  24970. */
  24971. void setCaretPosition (const int newIndex) throw();
  24972. /** Returns the current index of the caret.
  24973. @see setCaretPosition
  24974. */
  24975. int getCaretPosition() const throw();
  24976. /** Attempts to scroll the text editor so that the caret ends up at
  24977. a specified position.
  24978. This won't affect the caret's position within the text, it tries to scroll
  24979. the entire editor vertically and horizontally so that the caret is sitting
  24980. at the given position (relative to the top-left of this component).
  24981. Depending on the amount of text available, it might not be possible to
  24982. scroll far enough for the caret to reach this exact position, but it
  24983. will go as far as it can in that direction.
  24984. */
  24985. void scrollEditorToPositionCaret (const int desiredCaretX,
  24986. const int desiredCaretY) throw();
  24987. /** Get the graphical position of the caret.
  24988. The rectangle returned is relative to the component's top-left corner.
  24989. @see scrollEditorToPositionCaret
  24990. */
  24991. const Rectangle getCaretRectangle() throw();
  24992. /** Selects a section of the text.
  24993. */
  24994. void setHighlightedRegion (int startIndex,
  24995. int numberOfCharactersToHighlight) throw();
  24996. /** Returns the first character that is selected.
  24997. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  24998. will return 0.
  24999. @see setHighlightedRegion, getHighlightedRegionLength
  25000. */
  25001. int getHighlightedRegionStart() const throw() { return selectionStart; }
  25002. /** Returns the number of characters that are selected.
  25003. @see setHighlightedRegion, getHighlightedRegionStart
  25004. */
  25005. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  25006. /** Returns the section of text that is currently selected. */
  25007. const String getHighlightedText() const throw();
  25008. /** Finds the index of the character at a given position.
  25009. The co-ordinates are relative to the component's top-left.
  25010. */
  25011. int getTextIndexAt (const int x, const int y) throw();
  25012. /** Counts the number of characters in the text.
  25013. This is quicker than getting the text as a string if you just need to know
  25014. the length.
  25015. */
  25016. int getTotalNumChars() throw();
  25017. /** Returns the total width of the text, as it is currently laid-out.
  25018. This may be larger than the size of the TextEditor, and can change when
  25019. the TextEditor is resized or the text changes.
  25020. */
  25021. int getTextWidth() const throw();
  25022. /** Returns the maximum height of the text, as it is currently laid-out.
  25023. This may be larger than the size of the TextEditor, and can change when
  25024. the TextEditor is resized or the text changes.
  25025. */
  25026. int getTextHeight() const throw();
  25027. /** Changes the size of the gap at the top and left-edge of the editor.
  25028. By default there's a gap of 4 pixels.
  25029. */
  25030. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  25031. /** Changes the size of border left around the edge of the component.
  25032. @see getBorder
  25033. */
  25034. void setBorder (const BorderSize& border) throw();
  25035. /** Returns the size of border around the edge of the component.
  25036. @see setBorder
  25037. */
  25038. const BorderSize getBorder() const throw();
  25039. /** Used to disable the auto-scrolling which keeps the cursor visible.
  25040. If true (the default), the editor will scroll when the cursor moves offscreen. If
  25041. set to false, it won't.
  25042. */
  25043. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  25044. /** @internal */
  25045. void paint (Graphics& g);
  25046. /** @internal */
  25047. void paintOverChildren (Graphics& g);
  25048. /** @internal */
  25049. void mouseDown (const MouseEvent& e);
  25050. /** @internal */
  25051. void mouseUp (const MouseEvent& e);
  25052. /** @internal */
  25053. void mouseDrag (const MouseEvent& e);
  25054. /** @internal */
  25055. void mouseDoubleClick (const MouseEvent& e);
  25056. /** @internal */
  25057. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25058. /** @internal */
  25059. bool keyPressed (const KeyPress& key);
  25060. /** @internal */
  25061. bool keyStateChanged (const bool isKeyDown);
  25062. /** @internal */
  25063. void focusGained (FocusChangeType cause);
  25064. /** @internal */
  25065. void focusLost (FocusChangeType cause);
  25066. /** @internal */
  25067. void resized();
  25068. /** @internal */
  25069. void enablementChanged();
  25070. /** @internal */
  25071. void colourChanged();
  25072. juce_UseDebuggingNewOperator
  25073. protected:
  25074. /** This adds the items to the popup menu.
  25075. By default it adds the cut/copy/paste items, but you can override this if
  25076. you need to replace these with your own items.
  25077. If you want to add your own items to the existing ones, you can override this,
  25078. call the base class's addPopupMenuItems() method, then append your own items.
  25079. When the menu has been shown, performPopupMenuAction() will be called to
  25080. perform the item that the user has chosen.
  25081. The default menu items will be added using item IDs in the range
  25082. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  25083. menu IDs.
  25084. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  25085. a pointer to the info about it, or may be null if the menu is being triggered
  25086. by some other means.
  25087. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  25088. */
  25089. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  25090. const MouseEvent* mouseClickEvent);
  25091. /** This is called to perform one of the items that was shown on the popup menu.
  25092. If you've overridden addPopupMenuItems(), you should also override this
  25093. to perform the actions that you've added.
  25094. If you've overridden addPopupMenuItems() but have still left the default items
  25095. on the menu, remember to call the superclass's performPopupMenuAction()
  25096. so that it can perform the default actions if that's what the user clicked on.
  25097. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  25098. */
  25099. virtual void performPopupMenuAction (const int menuItemID);
  25100. /** Scrolls the minimum distance needed to get the caret into view. */
  25101. void scrollToMakeSureCursorIsVisible() throw();
  25102. /** @internal */
  25103. void moveCaret (int newCaretPos) throw();
  25104. /** @internal */
  25105. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  25106. /** Used internally to dispatch a text-change message. */
  25107. void textChanged() throw();
  25108. /** Begins a new transaction in the UndoManager.
  25109. */
  25110. void newTransaction() throw();
  25111. /** Used internally to trigger an undo or redo. */
  25112. void doUndoRedo (const bool isRedo);
  25113. /** Can be overridden to intercept return key presses directly */
  25114. virtual void returnPressed();
  25115. /** Can be overridden to intercept escape key presses directly */
  25116. virtual void escapePressed();
  25117. /** @internal */
  25118. void handleCommandMessage (int commandId);
  25119. private:
  25120. Viewport* viewport;
  25121. TextHolderComponent* textHolder;
  25122. BorderSize borderSize;
  25123. bool readOnly : 1;
  25124. bool multiline : 1;
  25125. bool wordWrap : 1;
  25126. bool returnKeyStartsNewLine : 1;
  25127. bool caretVisible : 1;
  25128. bool popupMenuEnabled : 1;
  25129. bool selectAllTextWhenFocused : 1;
  25130. bool scrollbarVisible : 1;
  25131. bool wasFocused : 1;
  25132. bool caretFlashState : 1;
  25133. bool keepCursorOnScreen : 1;
  25134. bool tabKeyUsed : 1;
  25135. bool menuActive : 1;
  25136. UndoManager undoManager;
  25137. float cursorX, cursorY, cursorHeight;
  25138. int maxTextLength;
  25139. int selectionStart, selectionEnd;
  25140. int leftIndent, topIndent;
  25141. unsigned int lastTransactionTime;
  25142. Font currentFont;
  25143. int totalNumChars, caretPosition;
  25144. VoidArray sections;
  25145. String textToShowWhenEmpty;
  25146. Colour colourForTextWhenEmpty;
  25147. tchar passwordCharacter;
  25148. enum
  25149. {
  25150. notDragging,
  25151. draggingSelectionStart,
  25152. draggingSelectionEnd
  25153. } dragType;
  25154. String allowedCharacters;
  25155. SortedSet <void*> listeners;
  25156. friend class TextEditorInsertAction;
  25157. friend class TextEditorRemoveAction;
  25158. void coalesceSimilarSections() throw();
  25159. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  25160. void clearInternal (UndoManager* const um) throw();
  25161. void insert (const String& text,
  25162. const int insertIndex,
  25163. const Font& font,
  25164. const Colour& colour,
  25165. UndoManager* const um,
  25166. const int caretPositionToMoveTo) throw();
  25167. void reinsert (const int insertIndex,
  25168. const VoidArray& sections) throw();
  25169. void remove (const int startIndex,
  25170. int endIndex,
  25171. UndoManager* const um,
  25172. const int caretPositionToMoveTo) throw();
  25173. void getCharPosition (const int index,
  25174. float& x, float& y,
  25175. float& lineHeight) const throw();
  25176. void updateCaretPosition() throw();
  25177. int indexAtPosition (const float x,
  25178. const float y) throw();
  25179. int findWordBreakAfter (const int position) const throw();
  25180. int findWordBreakBefore (const int position) const throw();
  25181. friend class TextHolderComponent;
  25182. friend class TextEditorViewport;
  25183. void drawContent (Graphics& g);
  25184. void updateTextHolderSize() throw();
  25185. float getWordWrapWidth() const throw();
  25186. void timerCallbackInt();
  25187. void repaintCaret();
  25188. void repaintText (int textStartIndex, int textEndIndex);
  25189. TextEditor (const TextEditor&);
  25190. const TextEditor& operator= (const TextEditor&);
  25191. };
  25192. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  25193. /********* End of inlined file: juce_TextEditor.h *********/
  25194. class Label;
  25195. /**
  25196. A class for receiving events from a Label.
  25197. You can register a LabelListener with a Label using the Label::addListener()
  25198. method, and it will be called when the text of the label changes, either because
  25199. of a call to Label::setText() or by the user editing the text (if the label is
  25200. editable).
  25201. @see Label::addListener, Label::removeListener
  25202. */
  25203. class JUCE_API LabelListener
  25204. {
  25205. public:
  25206. /** Destructor. */
  25207. virtual ~LabelListener() {}
  25208. /** Called when a Label's text has changed.
  25209. */
  25210. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  25211. };
  25212. /**
  25213. A component that displays a text string, and can optionally become a text
  25214. editor when clicked.
  25215. */
  25216. class JUCE_API Label : public Component,
  25217. public SettableTooltipClient,
  25218. protected TextEditorListener,
  25219. private ComponentListener
  25220. {
  25221. public:
  25222. /** Creates a Label.
  25223. @param componentName the name to give the component
  25224. @param labelText the text to show in the label
  25225. */
  25226. Label (const String& componentName,
  25227. const String& labelText);
  25228. /** Destructor. */
  25229. ~Label();
  25230. /** Changes the label text.
  25231. If broadcastChangeMessage is true and the new text is different to the current
  25232. text, then the class will broadcast a change message to any LabelListeners that
  25233. are registered.
  25234. */
  25235. void setText (const String& newText,
  25236. const bool broadcastChangeMessage);
  25237. /** Returns the label's current text.
  25238. @param returnActiveEditorContents if this is true and the label is currently
  25239. being edited, then this method will return the
  25240. text as it's being shown in the editor. If false,
  25241. then the value returned here won't be updated until
  25242. the user has finished typing and pressed the return
  25243. key.
  25244. */
  25245. const String getText (const bool returnActiveEditorContents = false) const throw();
  25246. /** Changes the font to use to draw the text.
  25247. @see getFont
  25248. */
  25249. void setFont (const Font& newFont) throw();
  25250. /** Returns the font currently being used.
  25251. @see setFont
  25252. */
  25253. const Font& getFont() const throw();
  25254. /** A set of colour IDs to use to change the colour of various aspects of the label.
  25255. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25256. methods.
  25257. Note that you can also use the constants from TextEditor::ColourIds to change the
  25258. colour of the text editor that is opened when a label is editable.
  25259. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25260. */
  25261. enum ColourIds
  25262. {
  25263. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  25264. textColourId = 0x1000281, /**< The colour for the text. */
  25265. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  25266. Leave this transparent to not have an outline. */
  25267. };
  25268. /** Sets the style of justification to be used for positioning the text.
  25269. (The default is Justification::centredLeft)
  25270. */
  25271. void setJustificationType (const Justification& justification) throw();
  25272. /** Returns the type of justification, as set in setJustificationType(). */
  25273. const Justification getJustificationType() const throw() { return justification; }
  25274. /** Changes the gap that is left between the edge of the component and the text.
  25275. By default there's a small gap left at the sides of the component to allow for
  25276. the drawing of the border, but you can change this if necessary.
  25277. */
  25278. void setBorderSize (int horizontalBorder, int verticalBorder);
  25279. /** Returns the size of the horizontal gap being left around the text.
  25280. */
  25281. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  25282. /** Returns the size of the vertical gap being left around the text.
  25283. */
  25284. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  25285. /** Makes this label "stick to" another component.
  25286. This will cause the label to follow another component around, staying
  25287. either to its left or above it.
  25288. @param owner the component to follow
  25289. @param onLeft if true, the label will stay on the left of its component; if
  25290. false, it will stay above it.
  25291. */
  25292. void attachToComponent (Component* owner,
  25293. const bool onLeft);
  25294. /** If this label has been attached to another component using attachToComponent, this
  25295. returns the other component.
  25296. Returns 0 if the label is not attached.
  25297. */
  25298. Component* getAttachedComponent() const throw() { return ownerComponent; }
  25299. /** If the label is attached to the left of another component, this returns true.
  25300. Returns false if the label is above the other component. This is only relevent if
  25301. attachToComponent() has been called.
  25302. */
  25303. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  25304. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  25305. using ellipsis.
  25306. @see Graphics::drawFittedText
  25307. */
  25308. void setMinimumHorizontalScale (const float newScale);
  25309. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  25310. /** Registers a listener that will be called when the label's text changes. */
  25311. void addListener (LabelListener* const listener) throw();
  25312. /** Deregisters a previously-registered listener. */
  25313. void removeListener (LabelListener* const listener) throw();
  25314. /** Makes the label turn into a TextEditor when clicked.
  25315. By default this is turned off.
  25316. If turned on, then single- or double-clicking will turn the label into
  25317. an editor. If the user then changes the text, then the ChangeBroadcaster
  25318. base class will be used to send change messages to any listeners that
  25319. have registered.
  25320. If the user changes the text, the textWasEdited() method will be called
  25321. afterwards, and subclasses can override this if they need to do anything
  25322. special.
  25323. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  25324. @param editOnDoubleClick if true, a double-click is needed to start editing
  25325. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  25326. edited will discard any changes; if false, then this will
  25327. commit the changes.
  25328. @see showEditor, setEditorColours, TextEditor
  25329. */
  25330. void setEditable (const bool editOnSingleClick,
  25331. const bool editOnDoubleClick = false,
  25332. const bool lossOfFocusDiscardsChanges = false) throw();
  25333. /** Returns true if this option was set using setEditable(). */
  25334. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  25335. /** Returns true if this option was set using setEditable(). */
  25336. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  25337. /** Returns true if this option has been set in a call to setEditable(). */
  25338. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  25339. /** Returns true if the user can edit this label's text. */
  25340. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  25341. /** Makes the editor appear as if the label had been clicked by the user.
  25342. @see textWasEdited, setEditable
  25343. */
  25344. void showEditor();
  25345. /** Hides the editor if it was being shown.
  25346. @param discardCurrentEditorContents if true, the label's text will be
  25347. reset to whatever it was before the editor
  25348. was shown; if false, the current contents of the
  25349. editor will be used to set the label's text
  25350. before it is hidden.
  25351. */
  25352. void hideEditor (const bool discardCurrentEditorContents);
  25353. /** Returns true if the editor is currently focused and active. */
  25354. bool isBeingEdited() const throw();
  25355. juce_UseDebuggingNewOperator
  25356. protected:
  25357. /** @internal */
  25358. void paint (Graphics& g);
  25359. /** @internal */
  25360. void resized();
  25361. /** @internal */
  25362. void mouseUp (const MouseEvent& e);
  25363. /** @internal */
  25364. void mouseDoubleClick (const MouseEvent& e);
  25365. /** @internal */
  25366. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  25367. /** @internal */
  25368. void componentParentHierarchyChanged (Component& component);
  25369. /** @internal */
  25370. void componentVisibilityChanged (Component& component);
  25371. /** @internal */
  25372. void inputAttemptWhenModal();
  25373. /** @internal */
  25374. void focusGained (FocusChangeType);
  25375. /** @internal */
  25376. void enablementChanged();
  25377. /** @internal */
  25378. KeyboardFocusTraverser* createFocusTraverser();
  25379. /** @internal */
  25380. void textEditorTextChanged (TextEditor& editor);
  25381. /** @internal */
  25382. void textEditorReturnKeyPressed (TextEditor& editor);
  25383. /** @internal */
  25384. void textEditorEscapeKeyPressed (TextEditor& editor);
  25385. /** @internal */
  25386. void textEditorFocusLost (TextEditor& editor);
  25387. /** @internal */
  25388. void colourChanged();
  25389. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  25390. Subclasses can override this if they need to customise this component in some way.
  25391. */
  25392. virtual TextEditor* createEditorComponent();
  25393. /** Called after the user changes the text.
  25394. */
  25395. virtual void textWasEdited();
  25396. /** Called when the text has been altered.
  25397. */
  25398. virtual void textWasChanged();
  25399. /** Called when the text editor has just appeared, due to a user click or other
  25400. focus change.
  25401. */
  25402. virtual void editorShown (TextEditor* editorComponent);
  25403. /** Called when the text editor is going to be deleted, after editing has finished.
  25404. */
  25405. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  25406. private:
  25407. String text;
  25408. Font font;
  25409. Justification justification;
  25410. TextEditor* editor;
  25411. SortedSet <void*> listeners;
  25412. Component* ownerComponent;
  25413. ComponentDeletionWatcher* deletionWatcher;
  25414. int horizontalBorderSize, verticalBorderSize;
  25415. float minimumHorizontalScale;
  25416. bool editSingleClick : 1;
  25417. bool editDoubleClick : 1;
  25418. bool lossOfFocusDiscardsChanges : 1;
  25419. bool leftOfOwnerComp : 1;
  25420. bool updateFromTextEditorContents();
  25421. void callChangeListeners();
  25422. Label (const Label&);
  25423. const Label& operator= (const Label&);
  25424. };
  25425. #endif // __JUCE_LABEL_JUCEHEADER__
  25426. /********* End of inlined file: juce_Label.h *********/
  25427. class ComboBox;
  25428. /**
  25429. A class for receiving events from a ComboBox.
  25430. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  25431. method, and it will be called when the selected item in the box changes.
  25432. @see ComboBox::addListener, ComboBox::removeListener
  25433. */
  25434. class JUCE_API ComboBoxListener
  25435. {
  25436. public:
  25437. /** Destructor. */
  25438. virtual ~ComboBoxListener() {}
  25439. /** Called when a ComboBox has its selected item changed.
  25440. */
  25441. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  25442. };
  25443. /**
  25444. A component that lets the user choose from a drop-down list of choices.
  25445. The combo-box has a list of text strings, each with an associated id number,
  25446. that will be shown in the drop-down list when the user clicks on the component.
  25447. The currently selected choice is displayed in the combo-box, and this can
  25448. either be read-only text, or editable.
  25449. To find out when the user selects a different item or edits the text, you
  25450. can register a ComboBoxListener to receive callbacks.
  25451. @see ComboBoxListener
  25452. */
  25453. class JUCE_API ComboBox : public Component,
  25454. public SettableTooltipClient,
  25455. private LabelListener,
  25456. private AsyncUpdater
  25457. {
  25458. public:
  25459. /** Creates a combo-box.
  25460. On construction, the text field will be empty, so you should call the
  25461. setSelectedId() or setText() method to choose the initial value before
  25462. displaying it.
  25463. @param componentName the name to set for the component (see Component::setName())
  25464. */
  25465. ComboBox (const String& componentName);
  25466. /** Destructor. */
  25467. ~ComboBox();
  25468. /** Sets whether the test in the combo-box is editable.
  25469. The default state for a new ComboBox is non-editable, and can only be changed
  25470. by choosing from the drop-down list.
  25471. */
  25472. void setEditableText (const bool isEditable);
  25473. /** Returns true if the text is directly editable.
  25474. @see setEditableText
  25475. */
  25476. bool isTextEditable() const throw();
  25477. /** Sets the style of justification to be used for positioning the text.
  25478. The default is Justification::centredLeft. The text is displayed using a
  25479. Label component inside the ComboBox.
  25480. */
  25481. void setJustificationType (const Justification& justification) throw();
  25482. /** Returns the current justification for the text box.
  25483. @see setJustificationType
  25484. */
  25485. const Justification getJustificationType() const throw();
  25486. /** Adds an item to be shown in the drop-down list.
  25487. @param newItemText the text of the item to show in the list
  25488. @param newItemId an associated ID number that can be set or retrieved - see
  25489. getSelectedId() and setSelectedId()
  25490. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25491. */
  25492. void addItem (const String& newItemText,
  25493. const int newItemId) throw();
  25494. /** Adds a separator line to the drop-down list.
  25495. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25496. */
  25497. void addSeparator() throw();
  25498. /** Adds a heading to the drop-down list, so that you can group the items into
  25499. different sections.
  25500. The headings are indented slightly differently to set them apart from the
  25501. items on the list, and obviously can't be selected. You might want to add
  25502. separators between your sections too.
  25503. @see addItem, addSeparator
  25504. */
  25505. void addSectionHeading (const String& headingName) throw();
  25506. /** This allows items in the drop-down list to be selectively disabled.
  25507. When you add an item, it's enabled by default, but you can call this
  25508. method to change its status.
  25509. If you disable an item which is already selected, this won't change the
  25510. current selection - it just stops the user choosing that item from the list.
  25511. */
  25512. void setItemEnabled (const int itemId,
  25513. const bool isEnabled) throw();
  25514. /** Changes the text for an existing item.
  25515. */
  25516. void changeItemText (const int itemId,
  25517. const String& newText) throw();
  25518. /** Removes all the items from the drop-down list.
  25519. If this call causes the content to be cleared, then a change-message
  25520. will be broadcast unless dontSendChangeMessage is true.
  25521. @see addItem, removeItem, getNumItems
  25522. */
  25523. void clear (const bool dontSendChangeMessage = false);
  25524. /** Returns the number of items that have been added to the list.
  25525. Note that this doesn't include headers or separators.
  25526. */
  25527. int getNumItems() const throw();
  25528. /** Returns the text for one of the items in the list.
  25529. Note that this doesn't include headers or separators.
  25530. @param index the item's index from 0 to (getNumItems() - 1)
  25531. */
  25532. const String getItemText (const int index) const throw();
  25533. /** Returns the ID for one of the items in the list.
  25534. Note that this doesn't include headers or separators.
  25535. @param index the item's index from 0 to (getNumItems() - 1)
  25536. */
  25537. int getItemId (const int index) const throw();
  25538. /** Returns the ID of the item that's currently shown in the box.
  25539. If no item is selected, or if the text is editable and the user
  25540. has entered something which isn't one of the items in the list, then
  25541. this will return 0.
  25542. @see setSelectedId, getSelectedItemIndex, getText
  25543. */
  25544. int getSelectedId() const throw();
  25545. /** Sets one of the items to be the current selection.
  25546. This will set the ComboBox's text to that of the item that matches
  25547. this ID.
  25548. @param newItemId the new item to select
  25549. @param dontSendChangeMessage if set to true, this method won't trigger a
  25550. change notification
  25551. @see getSelectedId, setSelectedItemIndex, setText
  25552. */
  25553. void setSelectedId (const int newItemId,
  25554. const bool dontSendChangeMessage = false) throw();
  25555. /** Returns the index of the item that's currently shown in the box.
  25556. If no item is selected, or if the text is editable and the user
  25557. has entered something which isn't one of the items in the list, then
  25558. this will return -1.
  25559. @see setSelectedItemIndex, getSelectedId, getText
  25560. */
  25561. int getSelectedItemIndex() const throw();
  25562. /** Sets one of the items to be the current selection.
  25563. This will set the ComboBox's text to that of the item at the given
  25564. index in the list.
  25565. @param newItemIndex the new item to select
  25566. @param dontSendChangeMessage if set to true, this method won't trigger a
  25567. change notification
  25568. @see getSelectedItemIndex, setSelectedId, setText
  25569. */
  25570. void setSelectedItemIndex (const int newItemIndex,
  25571. const bool dontSendChangeMessage = false) throw();
  25572. /** Returns the text that is currently shown in the combo-box's text field.
  25573. If the ComboBox has editable text, then this text may have been edited
  25574. by the user; otherwise it will be one of the items from the list, or
  25575. possibly an empty string if nothing was selected.
  25576. @see setText, getSelectedId, getSelectedItemIndex
  25577. */
  25578. const String getText() const throw();
  25579. /** Sets the contents of the combo-box's text field.
  25580. The text passed-in will be set as the current text regardless of whether
  25581. it is one of the items in the list. If the current text isn't one of the
  25582. items, then getSelectedId() will return -1, otherwise it wil return
  25583. the approriate ID.
  25584. @param newText the text to select
  25585. @param dontSendChangeMessage if set to true, this method won't trigger a
  25586. change notification
  25587. @see getText
  25588. */
  25589. void setText (const String& newText,
  25590. const bool dontSendChangeMessage = false) throw();
  25591. /** Programmatically opens the text editor to allow the user to edit the current item.
  25592. This is the same effect as when the box is clicked-on.
  25593. @see Label::showEditor();
  25594. */
  25595. void showEditor();
  25596. /** Registers a listener that will be called when the box's content changes. */
  25597. void addListener (ComboBoxListener* const listener) throw();
  25598. /** Deregisters a previously-registered listener. */
  25599. void removeListener (ComboBoxListener* const listener) throw();
  25600. /** Sets a message to display when there is no item currently selected.
  25601. @see getTextWhenNothingSelected
  25602. */
  25603. void setTextWhenNothingSelected (const String& newMessage) throw();
  25604. /** Returns the text that is shown when no item is selected.
  25605. @see setTextWhenNothingSelected
  25606. */
  25607. const String getTextWhenNothingSelected() const throw();
  25608. /** Sets the message to show when there are no items in the list, and the user clicks
  25609. on the drop-down box.
  25610. By default it just says "no choices", but this lets you change it to something more
  25611. meaningful.
  25612. */
  25613. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25614. /** Returns the text shown when no items have been added to the list.
  25615. @see setTextWhenNoChoicesAvailable
  25616. */
  25617. const String getTextWhenNoChoicesAvailable() const throw();
  25618. /** Gives the ComboBox a tooltip. */
  25619. void setTooltip (const String& newTooltip);
  25620. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25621. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25622. methods.
  25623. To change the colours of the menu that pops up
  25624. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25625. */
  25626. enum ColourIds
  25627. {
  25628. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25629. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25630. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25631. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25632. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25633. };
  25634. /** @internal */
  25635. void labelTextChanged (Label*);
  25636. /** @internal */
  25637. void enablementChanged();
  25638. /** @internal */
  25639. void colourChanged();
  25640. /** @internal */
  25641. void focusGained (Component::FocusChangeType cause);
  25642. /** @internal */
  25643. void focusLost (Component::FocusChangeType cause);
  25644. /** @internal */
  25645. void handleAsyncUpdate();
  25646. /** @internal */
  25647. const String getTooltip() { return label->getTooltip(); }
  25648. /** @internal */
  25649. void mouseDown (const MouseEvent&);
  25650. /** @internal */
  25651. void mouseDrag (const MouseEvent&);
  25652. /** @internal */
  25653. void mouseUp (const MouseEvent&);
  25654. /** @internal */
  25655. void lookAndFeelChanged();
  25656. /** @internal */
  25657. void paint (Graphics&);
  25658. /** @internal */
  25659. void resized();
  25660. /** @internal */
  25661. bool keyStateChanged (const bool isKeyDown);
  25662. /** @internal */
  25663. bool keyPressed (const KeyPress&);
  25664. juce_UseDebuggingNewOperator
  25665. private:
  25666. struct ItemInfo
  25667. {
  25668. String name;
  25669. int itemId;
  25670. bool isEnabled : 1, isHeading : 1;
  25671. bool isSeparator() const throw();
  25672. bool isRealItem() const throw();
  25673. };
  25674. OwnedArray <ItemInfo> items;
  25675. int currentIndex;
  25676. bool isButtonDown;
  25677. bool separatorPending;
  25678. bool menuActive;
  25679. SortedSet <void*> listeners;
  25680. Label* label;
  25681. String textWhenNothingSelected, noChoicesMessage;
  25682. void showPopup();
  25683. ItemInfo* getItemForId (const int itemId) const throw();
  25684. ItemInfo* getItemForIndex (const int index) const throw();
  25685. ComboBox (const ComboBox&);
  25686. const ComboBox& operator= (const ComboBox&);
  25687. };
  25688. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25689. /********* End of inlined file: juce_ComboBox.h *********/
  25690. /**
  25691. Manages the state of some audio and midi i/o devices.
  25692. This class keeps tracks of a currently-selected audio device, through
  25693. with which it continuously streams data from an audio callback, as well as
  25694. one or more midi inputs.
  25695. The idea is that your application will create one global instance of this object,
  25696. and let it take care of creating and deleting specific types of audio devices
  25697. internally. So when the device is changed, your callbacks will just keep running
  25698. without having to worry about this.
  25699. The manager can save and reload all of its device settings as XML, which
  25700. makes it very easy for you to save and reload the audio setup of your
  25701. application.
  25702. And to make it easy to let the user change its settings, there's a component
  25703. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25704. device selection/sample-rate/latency controls.
  25705. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25706. call addAudioCallback() to register your audio callback with it, and use that to process
  25707. your audio data.
  25708. The manager also acts as a handy hub for incoming midi messages, allowing a
  25709. listener to register for messages from either a specific midi device, or from whatever
  25710. the current default midi input device is. The listener then doesn't have to worry about
  25711. re-registering with different midi devices if they are changed or deleted.
  25712. And yet another neat trick is that amount of CPU time being used is measured and
  25713. available with the getCpuUsage() method.
  25714. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25715. listeners whenever one of its settings is changed.
  25716. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25717. */
  25718. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25719. {
  25720. public:
  25721. /** Creates a default AudioDeviceManager.
  25722. Initially no audio device will be selected. You should call the initialise() method
  25723. and register an audio callback with setAudioCallback() before it'll be able to
  25724. actually make any noise.
  25725. */
  25726. AudioDeviceManager();
  25727. /** Destructor. */
  25728. ~AudioDeviceManager();
  25729. /**
  25730. This structure holds a set of properties describing the current audio setup.
  25731. @see AudioDeviceManager::setAudioDeviceSetup()
  25732. */
  25733. struct JUCE_API AudioDeviceSetup
  25734. {
  25735. AudioDeviceSetup();
  25736. bool operator== (const AudioDeviceSetup& other) const;
  25737. /** The name of the audio device used for output.
  25738. This may be the same as the input device.
  25739. */
  25740. String outputDeviceName;
  25741. /** The name of the audio device used for input.
  25742. This may be the same as the output device.
  25743. */
  25744. String inputDeviceName;
  25745. /** The current sample rate.
  25746. This rate is used for both the input and output devices.
  25747. */
  25748. double sampleRate;
  25749. /** The buffer size, in samples.
  25750. This buffer size is used for both the input and output devices.
  25751. */
  25752. int bufferSize;
  25753. /** The set of active input channels.
  25754. The bits that are set in this array indicate the channels of the
  25755. input device that are active.
  25756. */
  25757. BitArray inputChannels;
  25758. /** If this is true, it indicates that the inputChannels array
  25759. should be ignored, and instead, the device's default channels
  25760. should be used.
  25761. */
  25762. bool useDefaultInputChannels;
  25763. /** The set of active output channels.
  25764. The bits that are set in this array indicate the channels of the
  25765. input device that are active.
  25766. */
  25767. BitArray outputChannels;
  25768. /** If this is true, it indicates that the outputChannels array
  25769. should be ignored, and instead, the device's default channels
  25770. should be used.
  25771. */
  25772. bool useDefaultOutputChannels;
  25773. };
  25774. /** Opens a set of audio devices ready for use.
  25775. This will attempt to open either a default audio device, or one that was
  25776. previously saved as XML.
  25777. @param numInputChannelsNeeded a minimum number of input channels needed
  25778. by your app.
  25779. @param numOutputChannelsNeeded a minimum number of output channels to open
  25780. @param savedState either a previously-saved state that was produced
  25781. by createStateXml(), or 0 if you want the manager
  25782. to choose the best device to open.
  25783. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25784. fails to open, then a default device will be used
  25785. instead. If false, then on failure, no device is
  25786. opened.
  25787. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25788. name, then that will be used as the default device
  25789. (assuming that there wasn't one specified in the XML).
  25790. The string can actually be a simple wildcard, containing "*"
  25791. and "?" characters
  25792. @param preferredSetupOptions if this is non-null, the structure will be used as the
  25793. set of preferred settings when opening the device. If you
  25794. use this parameter, the preferredDefaultDeviceName
  25795. field will be ignored
  25796. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25797. */
  25798. const String initialise (const int numInputChannelsNeeded,
  25799. const int numOutputChannelsNeeded,
  25800. const XmlElement* const savedState,
  25801. const bool selectDefaultDeviceOnFailure,
  25802. const String& preferredDefaultDeviceName = String::empty,
  25803. const AudioDeviceSetup* preferredSetupOptions = 0);
  25804. /** Returns some XML representing the current state of the manager.
  25805. This stores the current device, its samplerate, block size, etc, and
  25806. can be restored later with initialise().
  25807. */
  25808. XmlElement* createStateXml() const;
  25809. /** Returns the current device properties that are in use.
  25810. @see setAudioDeviceSetup
  25811. */
  25812. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25813. /** Changes the current device or its settings.
  25814. If you want to change a device property, like the current sample rate or
  25815. block size, you can call getAudioDeviceSetup() to retrieve the current
  25816. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  25817. and pass it back into this method to apply the new settings.
  25818. @param newSetup the settings that you'd like to use
  25819. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25820. settings will be taken as having been explicitly chosen by the
  25821. user, and the next time createStateXml() is called, these settings
  25822. will be returned. If it's false, then the device is treated as a
  25823. temporary or default device, and a call to createStateXml() will
  25824. return either the last settings that were made with treatAsChosenDevice
  25825. as true, or the last XML settings that were passed into initialise().
  25826. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25827. @see getAudioDeviceSetup
  25828. */
  25829. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25830. const bool treatAsChosenDevice);
  25831. /** Returns the currently-active audio device. */
  25832. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25833. /** Returns the type of audio device currently in use.
  25834. @see setCurrentAudioDeviceType
  25835. */
  25836. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25837. /** Changes the class of audio device being used.
  25838. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  25839. this because there's only one type: CoreAudio.
  25840. For a list of types, see getAvailableDeviceTypes().
  25841. */
  25842. void setCurrentAudioDeviceType (const String& type,
  25843. const bool treatAsChosenDevice);
  25844. /** Closes the currently-open device.
  25845. You can call restartLastAudioDevice() later to reopen it in the same state
  25846. that it was just in.
  25847. */
  25848. void closeAudioDevice();
  25849. /** Tries to reload the last audio device that was running.
  25850. Note that this only reloads the last device that was running before
  25851. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25852. and can only be called after a device has been opened with SetAudioDevice().
  25853. If a device is already open, this call will do nothing.
  25854. */
  25855. void restartLastAudioDevice();
  25856. /** Registers an audio callback to be used.
  25857. The manager will redirect callbacks from whatever audio device is currently
  25858. in use to all registered callback objects. If more than one callback is
  25859. active, they will all be given the same input data, and their outputs will
  25860. be summed.
  25861. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  25862. object before returning.
  25863. To remove a callback, use removeAudioCallback().
  25864. */
  25865. void addAudioCallback (AudioIODeviceCallback* newCallback);
  25866. /** Deregisters a previously added callback.
  25867. If necessary, this method will invoke audioDeviceStopped() on the callback
  25868. object before returning.
  25869. @see addAudioCallback
  25870. */
  25871. void removeAudioCallback (AudioIODeviceCallback* callback);
  25872. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25873. Returns a value between 0 and 1.0
  25874. */
  25875. double getCpuUsage() const;
  25876. /** Enables or disables a midi input device.
  25877. The list of devices can be obtained with the MidiInput::getDevices() method.
  25878. Any incoming messages from enabled input devices will be forwarded on to all the
  25879. listeners that have been registered with the addMidiInputCallback() method. They
  25880. can either register for messages from a particular device, or from just the
  25881. "default" midi input.
  25882. Routing the midi input via an AudioDeviceManager means that when a listener
  25883. registers for the default midi input, this default device can be changed by the
  25884. manager without the listeners having to know about it or re-register.
  25885. It also means that a listener can stay registered for a midi input that is disabled
  25886. or not present, so that when the input is re-enabled, the listener will start
  25887. receiving messages again.
  25888. @see addMidiInputCallback, isMidiInputEnabled
  25889. */
  25890. void setMidiInputEnabled (const String& midiInputDeviceName,
  25891. const bool enabled);
  25892. /** Returns true if a given midi input device is being used.
  25893. @see setMidiInputEnabled
  25894. */
  25895. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25896. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25897. The device name can be empty to indicate that it wants events from whatever the
  25898. current "default" device is. Or it can be the name of one of the midi input devices
  25899. (see MidiInput::getDevices() for the names).
  25900. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25901. events forwarded on to listeners.
  25902. */
  25903. void addMidiInputCallback (const String& midiInputDeviceName,
  25904. MidiInputCallback* callback);
  25905. /** Removes a listener that was previously registered with addMidiInputCallback().
  25906. */
  25907. void removeMidiInputCallback (const String& midiInputDeviceName,
  25908. MidiInputCallback* callback);
  25909. /** Sets a midi output device to use as the default.
  25910. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25911. The specified device will be opened automatically and can be retrieved with the
  25912. getDefaultMidiOutput() method.
  25913. Pass in an empty string to deselect all devices. For the default device, you
  25914. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25915. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25916. */
  25917. void setDefaultMidiOutput (const String& deviceName);
  25918. /** Returns the name of the default midi output.
  25919. @see setDefaultMidiOutput, getDefaultMidiOutput
  25920. */
  25921. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25922. /** Returns the current default midi output device.
  25923. If no device has been selected, or the device can't be opened, this will
  25924. return 0.
  25925. @see getDefaultMidiOutputName
  25926. */
  25927. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25928. /** Returns a list of the types of device supported.
  25929. */
  25930. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25931. /** Creates a list of available types.
  25932. This will add a set of new AudioIODeviceType objects to the specified list, to
  25933. represent each available types of device.
  25934. You can override this if your app needs to do something specific, like avoid
  25935. using DirectSound devices, etc.
  25936. */
  25937. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  25938. /** Plays a beep through the current audio device.
  25939. This is here to allow the audio setup UI panels to easily include a "test"
  25940. button so that the user can check where the audio is coming from.
  25941. */
  25942. void playTestSound();
  25943. /** Turns on level-measuring.
  25944. When enabled, the device manager will measure the peak input level
  25945. across all channels, and you can get this level by calling getCurrentInputLevel().
  25946. This is mainly intended for audio setup UI panels to use to create a mic
  25947. level display, so that the user can check that they've selected the right
  25948. device.
  25949. A simple filter is used to make the level decay smoothly, but this is
  25950. only intended for giving rough feedback, and not for any kind of accurate
  25951. measurement.
  25952. */
  25953. void enableInputLevelMeasurement (const bool enableMeasurement);
  25954. /** Returns the current input level.
  25955. To use this, you must first enable it by calling enableInputLevelMeasurement().
  25956. See enableInputLevelMeasurement() for more info.
  25957. */
  25958. double getCurrentInputLevel() const;
  25959. juce_UseDebuggingNewOperator
  25960. private:
  25961. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  25962. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  25963. AudioDeviceSetup currentSetup;
  25964. AudioIODevice* currentAudioDevice;
  25965. SortedSet <AudioIODeviceCallback*> callbacks;
  25966. int numInputChansNeeded, numOutputChansNeeded;
  25967. String currentDeviceType;
  25968. BitArray inputChannels, outputChannels;
  25969. XmlElement* lastExplicitSettings;
  25970. mutable bool listNeedsScanning;
  25971. bool useInputNames;
  25972. int inputLevelMeasurementEnabledCount;
  25973. double inputLevel;
  25974. AudioSampleBuffer* testSound;
  25975. int testSoundPosition;
  25976. AudioSampleBuffer tempBuffer;
  25977. StringArray midiInsFromXml;
  25978. OwnedArray <MidiInput> enabledMidiInputs;
  25979. Array <MidiInputCallback*> midiCallbacks;
  25980. Array <MidiInput*> midiCallbackDevices;
  25981. String defaultMidiOutputName;
  25982. MidiOutput* defaultMidiOutput;
  25983. CriticalSection audioCallbackLock, midiCallbackLock;
  25984. double cpuUsageMs, timeToCpuScale;
  25985. class CallbackHandler : public AudioIODeviceCallback,
  25986. public MidiInputCallback
  25987. {
  25988. public:
  25989. AudioDeviceManager* owner;
  25990. void audioDeviceIOCallback (const float** inputChannelData,
  25991. int totalNumInputChannels,
  25992. float** outputChannelData,
  25993. int totalNumOutputChannels,
  25994. int numSamples);
  25995. void audioDeviceAboutToStart (AudioIODevice*);
  25996. void audioDeviceStopped();
  25997. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  25998. };
  25999. CallbackHandler callbackHandler;
  26000. friend class CallbackHandler;
  26001. void audioDeviceIOCallbackInt (const float** inputChannelData,
  26002. int totalNumInputChannels,
  26003. float** outputChannelData,
  26004. int totalNumOutputChannels,
  26005. int numSamples);
  26006. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  26007. void audioDeviceStoppedInt();
  26008. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  26009. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  26010. const BitArray& ins, const BitArray& outs);
  26011. void stopDevice();
  26012. void updateXml();
  26013. void createDeviceTypesIfNeeded();
  26014. void scanDevicesIfNeeded();
  26015. void deleteCurrentDevice();
  26016. double chooseBestSampleRate (double preferred) const;
  26017. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  26018. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  26019. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  26020. AudioDeviceManager (const AudioDeviceManager&);
  26021. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  26022. };
  26023. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26024. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  26025. #endif
  26026. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  26027. #endif
  26028. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26029. #endif
  26030. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  26031. #endif
  26032. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  26033. #endif
  26034. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  26035. /********* Start of inlined file: juce_Sampler.h *********/
  26036. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  26037. #define __JUCE_SAMPLER_JUCEHEADER__
  26038. /********* Start of inlined file: juce_Synthesiser.h *********/
  26039. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26040. #define __JUCE_SYNTHESISER_JUCEHEADER__
  26041. /**
  26042. Describes one of the sounds that a Synthesiser can play.
  26043. A synthesiser can contain one or more sounds, and a sound can choose which
  26044. midi notes and channels can trigger it.
  26045. The SynthesiserSound is a passive class that just describes what the sound is -
  26046. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  26047. more than one SynthesiserVoice to play the same sound at the same time.
  26048. @see Synthesiser, SynthesiserVoice
  26049. */
  26050. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  26051. {
  26052. protected:
  26053. SynthesiserSound();
  26054. public:
  26055. /** Destructor. */
  26056. virtual ~SynthesiserSound();
  26057. /** Returns true if this sound should be played when a given midi note is pressed.
  26058. The Synthesiser will use this information when deciding which sounds to trigger
  26059. for a given note.
  26060. */
  26061. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  26062. /** Returns true if the sound should be triggered by midi events on a given channel.
  26063. The Synthesiser will use this information when deciding which sounds to trigger
  26064. for a given note.
  26065. */
  26066. virtual bool appliesToChannel (const int midiChannel) = 0;
  26067. /**
  26068. */
  26069. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  26070. juce_UseDebuggingNewOperator
  26071. };
  26072. /**
  26073. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  26074. A voice plays a single sound at a time, and a synthesiser holds an array of
  26075. voices so that it can play polyphonically.
  26076. @see Synthesiser, SynthesiserSound
  26077. */
  26078. class JUCE_API SynthesiserVoice
  26079. {
  26080. public:
  26081. /** Creates a voice. */
  26082. SynthesiserVoice();
  26083. /** Destructor. */
  26084. virtual ~SynthesiserVoice();
  26085. /** Returns the midi note that this voice is currently playing.
  26086. Returns a value less than 0 if no note is playing.
  26087. */
  26088. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  26089. /** Returns the sound that this voice is currently playing.
  26090. Returns 0 if it's not playing.
  26091. */
  26092. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  26093. /** Must return true if this voice object is capable of playing the given sound.
  26094. If there are different classes of sound, and different classes of voice, a voice can
  26095. choose which ones it wants to take on.
  26096. A typical implementation of this method may just return true if there's only one type
  26097. of voice and sound, or it might check the type of the sound object passed-in and
  26098. see if it's one that it understands.
  26099. */
  26100. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  26101. /** Called to start a new note.
  26102. This will be called during the rendering callback, so must be fast and thread-safe.
  26103. */
  26104. virtual void startNote (const int midiNoteNumber,
  26105. const float velocity,
  26106. SynthesiserSound* sound,
  26107. const int currentPitchWheelPosition) = 0;
  26108. /** Called to stop a note.
  26109. This will be called during the rendering callback, so must be fast and thread-safe.
  26110. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  26111. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  26112. and allow the synth to reassign it another sound.
  26113. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  26114. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  26115. finishes playing (during the rendering callback), it must make sure that it calls
  26116. clearCurrentNote().
  26117. */
  26118. virtual void stopNote (const bool allowTailOff) = 0;
  26119. /** Called to let the voice know that the pitch wheel has been moved.
  26120. This will be called during the rendering callback, so must be fast and thread-safe.
  26121. */
  26122. virtual void pitchWheelMoved (const int newValue) = 0;
  26123. /** Called to let the voice know that a midi controller has been moved.
  26124. This will be called during the rendering callback, so must be fast and thread-safe.
  26125. */
  26126. virtual void controllerMoved (const int controllerNumber,
  26127. const int newValue) = 0;
  26128. /** Renders the next block of data for this voice.
  26129. The output audio data must be added to the current contents of the buffer provided.
  26130. Only the region of the buffer between startSample and (startSample + numSamples)
  26131. should be altered by this method.
  26132. If the voice is currently silent, it should just return without doing anything.
  26133. If the sound that the voice is playing finishes during the course of this rendered
  26134. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  26135. The size of the blocks that are rendered can change each time it is called, and may
  26136. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  26137. the voice's methods will be called to tell it about note and controller events.
  26138. */
  26139. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  26140. int startSample,
  26141. int numSamples) = 0;
  26142. /** Returns true if the voice is currently playing a sound which is mapped to the given
  26143. midi channel.
  26144. If it's not currently playing, this will return false.
  26145. */
  26146. bool isPlayingChannel (const int midiChannel) const;
  26147. /** Changes the voice's reference sample rate.
  26148. The rate is set so that subclasses know the output rate and can set their pitch
  26149. accordingly.
  26150. This method is called by the synth, and subclasses can access the current rate with
  26151. the currentSampleRate member.
  26152. */
  26153. void setCurrentPlaybackSampleRate (const double newRate);
  26154. juce_UseDebuggingNewOperator
  26155. protected:
  26156. /** Returns the current target sample rate at which rendering is being done.
  26157. This is available for subclasses so they can pitch things correctly.
  26158. */
  26159. double getSampleRate() const throw() { return currentSampleRate; }
  26160. /** Resets the state of this voice after a sound has finished playing.
  26161. The subclass must call this when it finishes playing a note and becomes available
  26162. to play new ones.
  26163. It must either call it in the stopNote() method, or if the voice is tailing off,
  26164. then it should call it later during the renderNextBlock method, as soon as it
  26165. finishes its tail-off.
  26166. It can also be called at any time during the render callback if the sound happens
  26167. to have finished, e.g. if it's playing a sample and the sample finishes.
  26168. */
  26169. void clearCurrentNote();
  26170. private:
  26171. friend class Synthesiser;
  26172. double currentSampleRate;
  26173. int currentlyPlayingNote;
  26174. uint32 noteOnTime;
  26175. SynthesiserSound::Ptr currentlyPlayingSound;
  26176. };
  26177. /**
  26178. Base class for a musical device that can play sounds.
  26179. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  26180. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  26181. which can play back one of these sounds.
  26182. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  26183. set of sounds, and a set of voices it can use to play them. If you only give it
  26184. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  26185. have available.
  26186. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  26187. events that go in will be scanned for note on/off messages, and these are used to
  26188. start and stop the voices playing the appropriate sounds.
  26189. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  26190. noteOff() and other controller methods.
  26191. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  26192. what the target playback rate is. This value is passed on to the voices so that
  26193. they can pitch their output correctly.
  26194. */
  26195. class JUCE_API Synthesiser
  26196. {
  26197. public:
  26198. /** Creates a new synthesiser.
  26199. You'll need to add some sounds and voices before it'll make any sound..
  26200. */
  26201. Synthesiser();
  26202. /** Destructor. */
  26203. virtual ~Synthesiser();
  26204. /** Deletes all voices. */
  26205. void clearVoices();
  26206. /** Returns the number of voices that have been added. */
  26207. int getNumVoices() const throw() { return voices.size(); }
  26208. /** Returns one of the voices that have been added. */
  26209. SynthesiserVoice* getVoice (const int index) const throw();
  26210. /** Adds a new voice to the synth.
  26211. All the voices should be the same class of object and are treated equally.
  26212. The object passed in will be managed by the synthesiser, which will delete
  26213. it later on when no longer needed. The caller should not retain a pointer to the
  26214. voice.
  26215. */
  26216. void addVoice (SynthesiserVoice* const newVoice);
  26217. /** Deletes one of the voices. */
  26218. void removeVoice (const int index);
  26219. /** Deletes all sounds. */
  26220. void clearSounds();
  26221. /** Returns the number of sounds that have been added to the synth. */
  26222. int getNumSounds() const throw() { return sounds.size(); }
  26223. /** Returns one of the sounds. */
  26224. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  26225. /** Adds a new sound to the synthesiser.
  26226. The object passed in is reference counted, so will be deleted when it is removed
  26227. from the synthesiser, and when no voices are still using it.
  26228. */
  26229. void addSound (const SynthesiserSound::Ptr& newSound);
  26230. /** Removes and deletes one of the sounds. */
  26231. void removeSound (const int index);
  26232. /** If set to true, then the synth will try to take over an existing voice if
  26233. it runs out and needs to play another note.
  26234. The value of this boolean is passed into findFreeVoice(), so the result will
  26235. depend on the implementation of this method.
  26236. */
  26237. void setNoteStealingEnabled (const bool shouldStealNotes);
  26238. /** Returns true if note-stealing is enabled.
  26239. @see setNoteStealingEnabled
  26240. */
  26241. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  26242. /** Triggers a note-on event.
  26243. The default method here will find all the sounds that want to be triggered by
  26244. this note/channel. For each sound, it'll try to find a free voice, and use the
  26245. voice to start playing the sound.
  26246. Subclasses might want to override this if they need a more complex algorithm.
  26247. This method will be called automatically according to the midi data passed into
  26248. renderNextBlock(), but may be called explicitly too.
  26249. */
  26250. virtual void noteOn (const int midiChannel,
  26251. const int midiNoteNumber,
  26252. const float velocity);
  26253. /** Triggers a note-off event.
  26254. This will turn off any voices that are playing a sound for the given note/channel.
  26255. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  26256. (if they can do). If this is false, the notes will all be cut off immediately.
  26257. This method will be called automatically according to the midi data passed into
  26258. renderNextBlock(), but may be called explicitly too.
  26259. */
  26260. virtual void noteOff (const int midiChannel,
  26261. const int midiNoteNumber,
  26262. const bool allowTailOff);
  26263. /** Turns off all notes.
  26264. This will turn off any voices that are playing a sound on the given midi channel.
  26265. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  26266. which channel they're playing.
  26267. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  26268. (if they can do). If this is false, the notes will all be cut off immediately.
  26269. This method will be called automatically according to the midi data passed into
  26270. renderNextBlock(), but may be called explicitly too.
  26271. */
  26272. virtual void allNotesOff (const int midiChannel,
  26273. const bool allowTailOff);
  26274. /** Sends a pitch-wheel message.
  26275. This will send a pitch-wheel message to any voices that are playing sounds on
  26276. the given midi channel.
  26277. This method will be called automatically according to the midi data passed into
  26278. renderNextBlock(), but may be called explicitly too.
  26279. @param midiChannel the midi channel for the event
  26280. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  26281. */
  26282. virtual void handlePitchWheel (const int midiChannel,
  26283. const int wheelValue);
  26284. /** Sends a midi controller message.
  26285. This will send a midi controller message to any voices that are playing sounds on
  26286. the given midi channel.
  26287. This method will be called automatically according to the midi data passed into
  26288. renderNextBlock(), but may be called explicitly too.
  26289. @param midiChannel the midi channel for the event
  26290. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  26291. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  26292. */
  26293. virtual void handleController (const int midiChannel,
  26294. const int controllerNumber,
  26295. const int controllerValue);
  26296. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  26297. render.
  26298. This value is propagated to the voices so that they can use it to render the correct
  26299. pitches.
  26300. */
  26301. void setCurrentPlaybackSampleRate (const double sampleRate);
  26302. /** Creates the next block of audio output.
  26303. This will process the next numSamples of data from all the voices, and add that output
  26304. to the audio block supplied, starting from the offset specified. Note that the
  26305. data will be added to the current contents of the buffer, so you should clear it
  26306. before calling this method if necessary.
  26307. The midi events in the inputMidi buffer are parsed for note and controller events,
  26308. and these are used to trigger the voices. Note that the startSample offset applies
  26309. both to the audio output buffer and the midi input buffer, so any midi events
  26310. with timestamps outside the specified region will be ignored.
  26311. */
  26312. void renderNextBlock (AudioSampleBuffer& outputAudio,
  26313. const MidiBuffer& inputMidi,
  26314. int startSample,
  26315. int numSamples);
  26316. juce_UseDebuggingNewOperator
  26317. protected:
  26318. /** This is used to control access to the rendering callback and the note trigger methods. */
  26319. CriticalSection lock;
  26320. OwnedArray <SynthesiserVoice> voices;
  26321. ReferenceCountedArray <SynthesiserSound> sounds;
  26322. /** The last pitch-wheel values for each midi channel. */
  26323. int lastPitchWheelValues [16];
  26324. /** Searches through the voices to find one that's not currently playing, and which
  26325. can play the given sound.
  26326. Returns 0 if all voices are busy and stealing isn't enabled.
  26327. This can be overridden to implement custom voice-stealing algorithms.
  26328. */
  26329. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  26330. const bool stealIfNoneAvailable) const;
  26331. /** Starts a specified voice playing a particular sound.
  26332. You'll probably never need to call this, it's used internally by noteOn(), but
  26333. may be needed by subclasses for custom behaviours.
  26334. */
  26335. void startVoice (SynthesiserVoice* const voice,
  26336. SynthesiserSound* const sound,
  26337. const int midiChannel,
  26338. const int midiNoteNumber,
  26339. const float velocity);
  26340. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  26341. int findFreeVoice (const bool) const { return 0; }
  26342. private:
  26343. double sampleRate;
  26344. uint32 lastNoteOnCounter;
  26345. bool shouldStealNotes;
  26346. Synthesiser (const Synthesiser&);
  26347. const Synthesiser& operator= (const Synthesiser&);
  26348. };
  26349. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  26350. /********* End of inlined file: juce_Synthesiser.h *********/
  26351. /**
  26352. A subclass of SynthesiserSound that represents a sampled audio clip.
  26353. This is a pretty basic sampler, and just attempts to load the whole audio stream
  26354. into memory.
  26355. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26356. give it some SampledSound objects to play.
  26357. @see SamplerVoice, Synthesiser, SynthesiserSound
  26358. */
  26359. class JUCE_API SamplerSound : public SynthesiserSound
  26360. {
  26361. public:
  26362. /** Creates a sampled sound from an audio reader.
  26363. This will attempt to load the audio from the source into memory and store
  26364. it in this object.
  26365. @param name a name for the sample
  26366. @param source the audio to load. This object can be safely deleted by the
  26367. caller after this constructor returns
  26368. @param midiNotes the set of midi keys that this sound should be played on. This
  26369. is used by the SynthesiserSound::appliesToNote() method
  26370. @param midiNoteForNormalPitch the midi note at which the sample should be played
  26371. with its natural rate. All other notes will be pitched
  26372. up or down relative to this one
  26373. @param attackTimeSecs the attack (fade-in) time, in seconds
  26374. @param releaseTimeSecs the decay (fade-out) time, in seconds
  26375. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  26376. source, in seconds
  26377. */
  26378. SamplerSound (const String& name,
  26379. AudioFormatReader& source,
  26380. const BitArray& midiNotes,
  26381. const int midiNoteForNormalPitch,
  26382. const double attackTimeSecs,
  26383. const double releaseTimeSecs,
  26384. const double maxSampleLengthSeconds);
  26385. /** Destructor. */
  26386. ~SamplerSound();
  26387. /** Returns the sample's name */
  26388. const String& getName() const throw() { return name; }
  26389. /** Returns the audio sample data.
  26390. This could be 0 if there was a problem loading it.
  26391. */
  26392. AudioSampleBuffer* getAudioData() const throw() { return data; }
  26393. bool appliesToNote (const int midiNoteNumber);
  26394. bool appliesToChannel (const int midiChannel);
  26395. juce_UseDebuggingNewOperator
  26396. private:
  26397. friend class SamplerVoice;
  26398. String name;
  26399. AudioSampleBuffer* data;
  26400. double sourceSampleRate;
  26401. BitArray midiNotes;
  26402. int length, attackSamples, releaseSamples;
  26403. int midiRootNote;
  26404. };
  26405. /**
  26406. A subclass of SynthesiserVoice that can play a SamplerSound.
  26407. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  26408. give it some SampledSound objects to play.
  26409. @see SamplerSound, Synthesiser, SynthesiserVoice
  26410. */
  26411. class JUCE_API SamplerVoice : public SynthesiserVoice
  26412. {
  26413. public:
  26414. /** Creates a SamplerVoice.
  26415. */
  26416. SamplerVoice();
  26417. /** Destructor. */
  26418. ~SamplerVoice();
  26419. bool canPlaySound (SynthesiserSound* sound);
  26420. void startNote (const int midiNoteNumber,
  26421. const float velocity,
  26422. SynthesiserSound* sound,
  26423. const int currentPitchWheelPosition);
  26424. void stopNote (const bool allowTailOff);
  26425. void pitchWheelMoved (const int newValue);
  26426. void controllerMoved (const int controllerNumber,
  26427. const int newValue);
  26428. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  26429. juce_UseDebuggingNewOperator
  26430. private:
  26431. double pitchRatio;
  26432. double sourceSamplePosition;
  26433. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  26434. bool isInAttack, isInRelease;
  26435. };
  26436. #endif // __JUCE_SAMPLER_JUCEHEADER__
  26437. /********* End of inlined file: juce_Sampler.h *********/
  26438. #endif
  26439. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  26440. #endif
  26441. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26442. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  26443. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26444. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26445. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  26446. /**
  26447. Implements a plugin format manager for AudioUnits.
  26448. */
  26449. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  26450. {
  26451. public:
  26452. AudioUnitPluginFormat();
  26453. ~AudioUnitPluginFormat();
  26454. const String getName() const { return "AudioUnit"; }
  26455. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26456. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26457. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26458. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26459. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26460. bool doesPluginStillExist (const PluginDescription& desc);
  26461. const FileSearchPath getDefaultLocationsToSearch();
  26462. juce_UseDebuggingNewOperator
  26463. private:
  26464. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  26465. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  26466. };
  26467. #endif
  26468. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26469. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  26470. #endif
  26471. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26472. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  26473. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26474. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26475. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  26476. // Sorry, this file is just a placeholder at the moment!...
  26477. /**
  26478. Implements a plugin format manager for DirectX plugins.
  26479. */
  26480. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  26481. {
  26482. public:
  26483. DirectXPluginFormat();
  26484. ~DirectXPluginFormat();
  26485. const String getName() const { return "DirectX"; }
  26486. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26487. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26488. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26489. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26490. const FileSearchPath getDefaultLocationsToSearch();
  26491. juce_UseDebuggingNewOperator
  26492. private:
  26493. DirectXPluginFormat (const DirectXPluginFormat&);
  26494. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  26495. };
  26496. #endif
  26497. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  26498. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  26499. #endif
  26500. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26501. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  26502. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26503. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26504. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  26505. // Sorry, this file is just a placeholder at the moment!...
  26506. /**
  26507. Implements a plugin format manager for DirectX plugins.
  26508. */
  26509. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  26510. {
  26511. public:
  26512. LADSPAPluginFormat();
  26513. ~LADSPAPluginFormat();
  26514. const String getName() const { return "LADSPA"; }
  26515. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26516. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26517. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26518. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  26519. const FileSearchPath getDefaultLocationsToSearch();
  26520. juce_UseDebuggingNewOperator
  26521. private:
  26522. LADSPAPluginFormat (const LADSPAPluginFormat&);
  26523. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  26524. };
  26525. #endif
  26526. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  26527. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  26528. #endif
  26529. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26530. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  26531. #ifdef __aeffect__
  26532. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26533. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26534. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26535. events to the list.
  26536. This is used by both the VST hosting code and the plugin wrapper.
  26537. */
  26538. class VSTMidiEventList
  26539. {
  26540. public:
  26541. VSTMidiEventList()
  26542. : events (0), numEventsUsed (0), numEventsAllocated (0)
  26543. {
  26544. }
  26545. ~VSTMidiEventList()
  26546. {
  26547. freeEvents();
  26548. }
  26549. void clear()
  26550. {
  26551. numEventsUsed = 0;
  26552. if (events != 0)
  26553. events->numEvents = 0;
  26554. }
  26555. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26556. {
  26557. ensureSize (numEventsUsed + 1);
  26558. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26559. events->numEvents = ++numEventsUsed;
  26560. if (numBytes <= 4)
  26561. {
  26562. if (e->type == kVstSysExType)
  26563. {
  26564. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26565. e->type = kVstMidiType;
  26566. e->byteSize = sizeof (VstMidiEvent);
  26567. e->noteLength = 0;
  26568. e->noteOffset = 0;
  26569. e->detune = 0;
  26570. e->noteOffVelocity = 0;
  26571. }
  26572. e->deltaFrames = frameOffset;
  26573. memcpy (e->midiData, midiData, numBytes);
  26574. }
  26575. else
  26576. {
  26577. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26578. if (se->type == kVstSysExType)
  26579. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26580. else
  26581. se->sysexDump = (char*) juce_malloc (numBytes);
  26582. memcpy (se->sysexDump, midiData, numBytes);
  26583. se->type = kVstSysExType;
  26584. se->byteSize = sizeof (VstMidiSysexEvent);
  26585. se->deltaFrames = frameOffset;
  26586. se->flags = 0;
  26587. se->dumpBytes = numBytes;
  26588. se->resvd1 = 0;
  26589. se->resvd2 = 0;
  26590. }
  26591. }
  26592. // Handy method to pull the events out of an event buffer supplied by the host
  26593. // or plugin.
  26594. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26595. {
  26596. for (int i = 0; i < events->numEvents; ++i)
  26597. {
  26598. const VstEvent* const e = events->events[i];
  26599. if (e != 0)
  26600. {
  26601. if (e->type == kVstMidiType)
  26602. {
  26603. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26604. 4, e->deltaFrames);
  26605. }
  26606. else if (e->type == kVstSysExType)
  26607. {
  26608. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26609. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26610. e->deltaFrames);
  26611. }
  26612. }
  26613. }
  26614. }
  26615. void ensureSize (int numEventsNeeded)
  26616. {
  26617. if (numEventsNeeded > numEventsAllocated)
  26618. {
  26619. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26620. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26621. if (events == 0)
  26622. events = (VstEvents*) juce_calloc (size);
  26623. else
  26624. events = (VstEvents*) juce_realloc (events, size);
  26625. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26626. {
  26627. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26628. (int) sizeof (VstMidiSysexEvent)));
  26629. e->type = kVstMidiType;
  26630. e->byteSize = sizeof (VstMidiEvent);
  26631. events->events[i] = (VstEvent*) e;
  26632. }
  26633. numEventsAllocated = numEventsNeeded;
  26634. }
  26635. }
  26636. void freeEvents()
  26637. {
  26638. if (events != 0)
  26639. {
  26640. for (int i = numEventsAllocated; --i >= 0;)
  26641. {
  26642. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26643. if (e->type == kVstSysExType)
  26644. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26645. juce_free (e);
  26646. }
  26647. juce_free (events);
  26648. events = 0;
  26649. numEventsUsed = 0;
  26650. numEventsAllocated = 0;
  26651. }
  26652. }
  26653. VstEvents* events;
  26654. private:
  26655. int numEventsUsed, numEventsAllocated;
  26656. };
  26657. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26658. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26659. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  26660. #endif
  26661. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26662. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  26663. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26664. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26665. #if JUCE_PLUGINHOST_VST
  26666. /**
  26667. Implements a plugin format manager for VSTs.
  26668. */
  26669. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  26670. {
  26671. public:
  26672. VSTPluginFormat();
  26673. ~VSTPluginFormat();
  26674. const String getName() const { return "VST"; }
  26675. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  26676. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  26677. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  26678. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  26679. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  26680. bool doesPluginStillExist (const PluginDescription& desc);
  26681. const FileSearchPath getDefaultLocationsToSearch();
  26682. juce_UseDebuggingNewOperator
  26683. private:
  26684. VSTPluginFormat (const VSTPluginFormat&);
  26685. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  26686. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  26687. };
  26688. #endif
  26689. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  26690. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  26691. #endif
  26692. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26693. #endif
  26694. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  26695. #endif
  26696. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26697. #endif
  26698. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  26699. #endif
  26700. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  26701. #endif
  26702. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26703. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  26704. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26705. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26706. /**
  26707. Scans a directory for plugins, and adds them to a KnownPluginList.
  26708. To use one of these, create it and call scanNextFile() repeatedly, until
  26709. it returns false.
  26710. */
  26711. class JUCE_API PluginDirectoryScanner
  26712. {
  26713. public:
  26714. /**
  26715. Creates a scanner.
  26716. @param listToAddResultsTo this will get the new types added to it.
  26717. @param formatToLookFor this is the type of format that you want to look for
  26718. @param directoriesToSearch the path to search
  26719. @param searchRecursively true to search recursively
  26720. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  26721. be used as a file to store the names of any plugins
  26722. that crash during initialisation. If there are
  26723. any plugins listed in it, then these will always
  26724. be scanned after all other possible files have
  26725. been tried - in this way, even if there's a few
  26726. dodgy plugins in your path, then a couple of rescans
  26727. will still manage to find all the proper plugins.
  26728. It's probably best to choose a file in the user's
  26729. application data directory (alongside your app's
  26730. settings file) for this. The file format it uses
  26731. is just a list of filenames of the modules that
  26732. failed.
  26733. */
  26734. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  26735. AudioPluginFormat& formatToLookFor,
  26736. FileSearchPath directoriesToSearch,
  26737. const bool searchRecursively,
  26738. const File& deadMansPedalFile);
  26739. /** Destructor. */
  26740. ~PluginDirectoryScanner();
  26741. /** Tries the next likely-looking file.
  26742. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  26743. re-tested if it's not already in the list, or if the file's modification
  26744. time has changed since the list was created. If dontRescanIfAlreadyInList is
  26745. false, the file will always be reloaded and tested.
  26746. Returns false when there are no more files to try.
  26747. */
  26748. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  26749. /** Returns the description of the plugin that will be scanned during the next
  26750. call to scanNextFile().
  26751. This is handy if you want to show the user which file is currently getting
  26752. scanned.
  26753. */
  26754. const String getNextPluginFileThatWillBeScanned() const throw();
  26755. /** Returns the estimated progress, between 0 and 1.
  26756. */
  26757. float getProgress() const { return progress; }
  26758. /** This returns a list of all the filenames of things that looked like being
  26759. a plugin file, but which failed to open for some reason.
  26760. */
  26761. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  26762. juce_UseDebuggingNewOperator
  26763. private:
  26764. KnownPluginList& list;
  26765. AudioPluginFormat& format;
  26766. StringArray filesOrIdentifiersToScan;
  26767. File deadMansPedalFile;
  26768. StringArray failedFiles;
  26769. int nextIndex;
  26770. float progress;
  26771. const StringArray getDeadMansPedalFile() throw();
  26772. void setDeadMansPedalFile (const StringArray& newContents) throw();
  26773. PluginDirectoryScanner (const PluginDirectoryScanner&);
  26774. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  26775. };
  26776. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  26777. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  26778. #endif
  26779. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26780. /********* Start of inlined file: juce_PluginListComponent.h *********/
  26781. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26782. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  26783. /********* Start of inlined file: juce_ListBox.h *********/
  26784. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  26785. #define __JUCE_LISTBOX_JUCEHEADER__
  26786. class ListViewport;
  26787. /**
  26788. A subclass of this is used to drive a ListBox.
  26789. @see ListBox
  26790. */
  26791. class JUCE_API ListBoxModel
  26792. {
  26793. public:
  26794. /** Destructor. */
  26795. virtual ~ListBoxModel() {}
  26796. /** This has to return the number of items in the list.
  26797. @see ListBox::getNumRows()
  26798. */
  26799. virtual int getNumRows() = 0;
  26800. /** This method must be implemented to draw a row of the list.
  26801. */
  26802. virtual void paintListBoxItem (int rowNumber,
  26803. Graphics& g,
  26804. int width, int height,
  26805. bool rowIsSelected) = 0;
  26806. /** This is used to create or update a custom component to go in a row of the list.
  26807. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  26808. and handle mouse clicks with listBoxItemClicked().
  26809. This method will be called whenever a custom component might need to be updated - e.g.
  26810. when the table is changed, or TableListBox::updateContent() is called.
  26811. If you don't need a custom component for the specified row, then return 0.
  26812. If you do want a custom component, and the existingComponentToUpdate is null, then
  26813. this method must create a suitable new component and return it.
  26814. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  26815. by this method. In this case, the method must either update it to make sure it's correctly representing
  26816. the given row (which may be different from the one that the component was created for), or it can
  26817. delete this component and return a new one.
  26818. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  26819. */
  26820. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  26821. Component* existingComponentToUpdate);
  26822. /** This can be overridden to react to the user clicking on a row.
  26823. @see listBoxItemDoubleClicked
  26824. */
  26825. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  26826. /** This can be overridden to react to the user double-clicking on a row.
  26827. @see listBoxItemClicked
  26828. */
  26829. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  26830. /** This can be overridden to react to the user double-clicking on a part of the list where
  26831. there are no rows.
  26832. @see listBoxItemClicked
  26833. */
  26834. virtual void backgroundClicked();
  26835. /** Override this to be informed when rows are selected or deselected.
  26836. This will be called whenever a row is selected or deselected. If a range of
  26837. rows is selected all at once, this will just be called once for that event.
  26838. @param lastRowSelected the last row that the user selected. If no
  26839. rows are currently selected, this may be -1.
  26840. */
  26841. virtual void selectedRowsChanged (int lastRowSelected);
  26842. /** Override this to be informed when the delete key is pressed.
  26843. If no rows are selected when they press the key, this won't be called.
  26844. @param lastRowSelected the last row that had been selected when they pressed the
  26845. key - if there are multiple selections, this might not be
  26846. very useful
  26847. */
  26848. virtual void deleteKeyPressed (int lastRowSelected);
  26849. /** Override this to be informed when the return key is pressed.
  26850. If no rows are selected when they press the key, this won't be called.
  26851. @param lastRowSelected the last row that had been selected when they pressed the
  26852. key - if there are multiple selections, this might not be
  26853. very useful
  26854. */
  26855. virtual void returnKeyPressed (int lastRowSelected);
  26856. /** Override this to be informed when the list is scrolled.
  26857. This might be caused by the user moving the scrollbar, or by programmatic changes
  26858. to the list position.
  26859. */
  26860. virtual void listWasScrolled();
  26861. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  26862. If this returns a non-empty name then when the user drags a row, the listbox will
  26863. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  26864. a drag-and-drop operation, using this string as the source description, with the listbox
  26865. itself as the source component.
  26866. @see DragAndDropContainer::startDragging
  26867. */
  26868. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  26869. };
  26870. /**
  26871. A list of items that can be scrolled vertically.
  26872. To create a list, you'll need to create a subclass of ListBoxModel. This can
  26873. either paint each row of the list and respond to events via callbacks, or for
  26874. more specialised tasks, it can supply a custom component to fill each row.
  26875. @see ComboBox, TableListBox
  26876. */
  26877. class JUCE_API ListBox : public Component,
  26878. public SettableTooltipClient
  26879. {
  26880. public:
  26881. /** Creates a ListBox.
  26882. The model pointer passed-in can be null, in which case you can set it later
  26883. with setModel().
  26884. */
  26885. ListBox (const String& componentName,
  26886. ListBoxModel* const model);
  26887. /** Destructor. */
  26888. ~ListBox();
  26889. /** Changes the current data model to display. */
  26890. void setModel (ListBoxModel* const newModel);
  26891. /** Returns the current list model. */
  26892. ListBoxModel* getModel() const throw() { return model; }
  26893. /** Causes the list to refresh its content.
  26894. Call this when the number of rows in the list changes, or if you want it
  26895. to call refreshComponentForRow() on all the row components.
  26896. Be careful not to call it from a different thread, though, as it's not
  26897. thread-safe.
  26898. */
  26899. void updateContent();
  26900. /** Turns on multiple-selection of rows.
  26901. By default this is disabled.
  26902. When your row component gets clicked you'll need to call the
  26903. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  26904. clicked and to get it to do the appropriate selection based on whether
  26905. the ctrl/shift keys are held down.
  26906. */
  26907. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  26908. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  26909. This function is here primarily for the ComboBox class to use, but might be
  26910. useful for some other purpose too.
  26911. */
  26912. void setMouseMoveSelectsRows (bool shouldSelect);
  26913. /** Selects a row.
  26914. If the row is already selected, this won't do anything.
  26915. @param rowNumber the row to select
  26916. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  26917. the selected row is off-screen, it'll scroll to make
  26918. sure that row is on-screen
  26919. @param deselectOthersFirst if true and there are multiple selections, these will
  26920. first be deselected before this item is selected
  26921. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  26922. deselectAllRows, selectRangeOfRows
  26923. */
  26924. void selectRow (const int rowNumber,
  26925. bool dontScrollToShowThisRow = false,
  26926. bool deselectOthersFirst = true);
  26927. /** Selects a set of rows.
  26928. This will add these rows to the current selection, so you might need to
  26929. clear the current selection first with deselectAllRows()
  26930. @param firstRow the first row to select (inclusive)
  26931. @param lastRow the last row to select (inclusive)
  26932. */
  26933. void selectRangeOfRows (int firstRow,
  26934. int lastRow);
  26935. /** Deselects a row.
  26936. If it's not currently selected, this will do nothing.
  26937. @see selectRow, deselectAllRows
  26938. */
  26939. void deselectRow (const int rowNumber);
  26940. /** Deselects any currently selected rows.
  26941. @see deselectRow
  26942. */
  26943. void deselectAllRows();
  26944. /** Selects or deselects a row.
  26945. If the row's currently selected, this deselects it, and vice-versa.
  26946. */
  26947. void flipRowSelection (const int rowNumber);
  26948. /** Returns a sparse set indicating the rows that are currently selected.
  26949. @see setSelectedRows
  26950. */
  26951. const SparseSet<int> getSelectedRows() const;
  26952. /** Sets the rows that should be selected, based on an explicit set of ranges.
  26953. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  26954. method will be called. If it's false, no notification will be sent to the model.
  26955. @see getSelectedRows
  26956. */
  26957. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  26958. const bool sendNotificationEventToModel = true);
  26959. /** Checks whether a row is selected.
  26960. */
  26961. bool isRowSelected (const int rowNumber) const;
  26962. /** Returns the number of rows that are currently selected.
  26963. @see getSelectedRow, isRowSelected, getLastRowSelected
  26964. */
  26965. int getNumSelectedRows() const;
  26966. /** Returns the row number of a selected row.
  26967. This will return the row number of the Nth selected row. The row numbers returned will
  26968. be sorted in order from low to high.
  26969. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  26970. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  26971. selected
  26972. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  26973. */
  26974. int getSelectedRow (const int index = 0) const;
  26975. /** Returns the last row that the user selected.
  26976. This isn't the same as the highest row number that is currently selected - if the user
  26977. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  26978. If nothing is selected, it will return -1.
  26979. */
  26980. int getLastRowSelected() const;
  26981. /** Multiply-selects rows based on the modifier keys.
  26982. If no modifier keys are down, this will select the given row and
  26983. deselect any others.
  26984. If the ctrl (or command on the Mac) key is down, it'll flip the
  26985. state of the selected row.
  26986. If the shift key is down, it'll select up to the given row from the
  26987. last row selected.
  26988. @see selectRow
  26989. */
  26990. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  26991. const ModifierKeys& modifiers);
  26992. /** Scrolls the list to a particular position.
  26993. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  26994. 1.0 scrolls to the bottom.
  26995. If the total number of rows all fit onto the screen at once, then this
  26996. method won't do anything.
  26997. @see getVerticalPosition
  26998. */
  26999. void setVerticalPosition (const double newProportion);
  27000. /** Returns the current vertical position as a proportion of the total.
  27001. This can be used in conjunction with setVerticalPosition() to save and restore
  27002. the list's position. It returns a value in the range 0 to 1.
  27003. @see setVerticalPosition
  27004. */
  27005. double getVerticalPosition() const;
  27006. /** Scrolls if necessary to make sure that a particular row is visible.
  27007. */
  27008. void scrollToEnsureRowIsOnscreen (const int row);
  27009. /** Returns a pointer to the scrollbar.
  27010. (Unlikely to be useful for most people).
  27011. */
  27012. ScrollBar* getVerticalScrollBar() const throw();
  27013. /** Returns a pointer to the scrollbar.
  27014. (Unlikely to be useful for most people).
  27015. */
  27016. ScrollBar* getHorizontalScrollBar() const throw();
  27017. /** Finds the row index that contains a given x,y position.
  27018. The position is relative to the ListBox's top-left.
  27019. If no row exists at this position, the method will return -1.
  27020. @see getComponentForRowNumber
  27021. */
  27022. int getRowContainingPosition (const int x, const int y) const throw();
  27023. /** Finds a row index that would be the most suitable place to insert a new
  27024. item for a given position.
  27025. This is useful when the user is e.g. dragging and dropping onto the listbox,
  27026. because it lets you easily choose the best position to insert the item that
  27027. they drop, based on where they drop it.
  27028. If the position is out of range, this will return -1. If the position is
  27029. beyond the end of the list, it will return getNumRows() to indicate the end
  27030. of the list.
  27031. @see getComponentForRowNumber
  27032. */
  27033. int getInsertionIndexForPosition (const int x, const int y) const throw();
  27034. /** Returns the position of one of the rows, relative to the top-left of
  27035. the listbox.
  27036. This may be off-screen, and the range of the row number that is passed-in is
  27037. not checked to see if it's a valid row.
  27038. */
  27039. const Rectangle getRowPosition (const int rowNumber,
  27040. const bool relativeToComponentTopLeft) const throw();
  27041. /** Finds the row component for a given row in the list.
  27042. The component returned will have been created using createRowComponent().
  27043. If the component for this row is off-screen or if the row is out-of-range,
  27044. this will return 0.
  27045. @see getRowContainingPosition
  27046. */
  27047. Component* getComponentForRowNumber (const int rowNumber) const throw();
  27048. /** Returns the row number that the given component represents.
  27049. If the component isn't one of the list's rows, this will return -1.
  27050. */
  27051. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  27052. /** Returns the width of a row (which may be less than the width of this component
  27053. if there's a scrollbar).
  27054. */
  27055. int getVisibleRowWidth() const throw();
  27056. /** Sets the height of each row in the list.
  27057. The default height is 22 pixels.
  27058. @see getRowHeight
  27059. */
  27060. void setRowHeight (const int newHeight);
  27061. /** Returns the height of a row in the list.
  27062. @see setRowHeight
  27063. */
  27064. int getRowHeight() const throw() { return rowHeight; }
  27065. /** Returns the number of rows actually visible.
  27066. This is the number of whole rows which will fit on-screen, so the value might
  27067. be more than the actual number of rows in the list.
  27068. */
  27069. int getNumRowsOnScreen() const throw();
  27070. /** A set of colour IDs to use to change the colour of various aspects of the label.
  27071. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27072. methods.
  27073. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27074. */
  27075. enum ColourIds
  27076. {
  27077. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  27078. Make this transparent if you don't want the background to be filled. */
  27079. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  27080. Make this transparent to not have an outline. */
  27081. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  27082. };
  27083. /** Sets the thickness of a border that will be drawn around the box.
  27084. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  27085. @see outlineColourId
  27086. */
  27087. void setOutlineThickness (const int outlineThickness);
  27088. /** Returns the thickness of outline that will be drawn around the listbox.
  27089. @see setOutlineColour
  27090. */
  27091. int getOutlineThickness() const throw() { return outlineThickness; }
  27092. /** Sets a component that the list should use as a header.
  27093. This will position the given component at the top of the list, maintaining the
  27094. height of the component passed-in, but rescaling it horizontally to match the
  27095. width of the items in the listbox.
  27096. The component will be deleted when setHeaderComponent() is called with a
  27097. different component, or when the listbox is deleted.
  27098. */
  27099. void setHeaderComponent (Component* const newHeaderComponent);
  27100. /** Changes the width of the rows in the list.
  27101. This can be used to make the list's row components wider than the list itself - the
  27102. width of the rows will be either the width of the list or this value, whichever is
  27103. greater, and if the rows become wider than the list, a horizontal scrollbar will
  27104. appear.
  27105. The default value for this is 0, which means that the rows will always
  27106. be the same width as the list.
  27107. */
  27108. void setMinimumContentWidth (const int newMinimumWidth);
  27109. /** Returns the space currently available for the row items, taking into account
  27110. borders, scrollbars, etc.
  27111. */
  27112. int getVisibleContentWidth() const throw();
  27113. /** Repaints one of the rows.
  27114. This is a lightweight alternative to calling updateContent, and just causes a
  27115. repaint of the row's area.
  27116. */
  27117. void repaintRow (const int rowNumber) throw();
  27118. /** This fairly obscure method creates an image that just shows the currently
  27119. selected row components.
  27120. It's a handy method for doing drag-and-drop, as it can be passed to the
  27121. DragAndDropContainer for use as the drag image.
  27122. Note that it will make the row components temporarily invisible, so if you're
  27123. using custom components this could affect them if they're sensitive to that
  27124. sort of thing.
  27125. @see Component::createComponentSnapshot
  27126. */
  27127. Image* createSnapshotOfSelectedRows();
  27128. /** Returns the viewport that this ListBox uses.
  27129. You may need to use this to change parameters such as whether scrollbars
  27130. are shown, etc.
  27131. */
  27132. Viewport* getViewport() const throw();
  27133. /** @internal */
  27134. bool keyPressed (const KeyPress& key);
  27135. /** @internal */
  27136. bool keyStateChanged (const bool isKeyDown);
  27137. /** @internal */
  27138. void paint (Graphics& g);
  27139. /** @internal */
  27140. void paintOverChildren (Graphics& g);
  27141. /** @internal */
  27142. void resized();
  27143. /** @internal */
  27144. void visibilityChanged();
  27145. /** @internal */
  27146. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  27147. /** @internal */
  27148. void mouseMove (const MouseEvent&);
  27149. /** @internal */
  27150. void mouseExit (const MouseEvent&);
  27151. /** @internal */
  27152. void mouseUp (const MouseEvent&);
  27153. /** @internal */
  27154. void colourChanged();
  27155. juce_UseDebuggingNewOperator
  27156. private:
  27157. friend class ListViewport;
  27158. friend class TableListBox;
  27159. ListBoxModel* model;
  27160. ListViewport* viewport;
  27161. Component* headerComponent;
  27162. int totalItems, rowHeight, minimumRowWidth;
  27163. int outlineThickness;
  27164. int lastMouseX, lastMouseY, lastRowSelected;
  27165. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  27166. SparseSet <int> selected;
  27167. void selectRowInternal (const int rowNumber,
  27168. bool dontScrollToShowThisRow,
  27169. bool deselectOthersFirst,
  27170. bool isMouseClick);
  27171. ListBox (const ListBox&);
  27172. const ListBox& operator= (const ListBox&);
  27173. };
  27174. #endif // __JUCE_LISTBOX_JUCEHEADER__
  27175. /********* End of inlined file: juce_ListBox.h *********/
  27176. /********* Start of inlined file: juce_TextButton.h *********/
  27177. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  27178. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  27179. /**
  27180. A button that uses the standard lozenge-shaped background with a line of
  27181. text on it.
  27182. @see Button, DrawableButton
  27183. */
  27184. class JUCE_API TextButton : public Button
  27185. {
  27186. public:
  27187. /** Creates a TextButton.
  27188. @param buttonName the text to put in the button (the component's name is also
  27189. initially set to this string, but these can be changed later
  27190. using the setName() and setButtonText() methods)
  27191. @param toolTip an optional string to use as a toolip
  27192. @see Button
  27193. */
  27194. TextButton (const String& buttonName,
  27195. const String& toolTip = String::empty);
  27196. /** Destructor. */
  27197. ~TextButton();
  27198. /** A set of colour IDs to use to change the colour of various aspects of the button.
  27199. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27200. methods.
  27201. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27202. */
  27203. enum ColourIds
  27204. {
  27205. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  27206. 'off'). The look-and-feel class might re-interpret this to add
  27207. effects, etc. */
  27208. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  27209. 'on'). The look-and-feel class might re-interpret this to add
  27210. effects, etc. */
  27211. textColourId = 0x1000102 /**< The colour to use for the button's text. */
  27212. };
  27213. /** Resizes the button to fit neatly around its current text.
  27214. If newHeight is >= 0, the button's height will be changed to this
  27215. value. If it's less than zero, its height will be unaffected.
  27216. */
  27217. void changeWidthToFitText (const int newHeight = -1);
  27218. /** This can be overridden to use different fonts than the default one.
  27219. Note that you'll need to set the font's size appropriately, too.
  27220. */
  27221. virtual const Font getFont();
  27222. juce_UseDebuggingNewOperator
  27223. protected:
  27224. /** @internal */
  27225. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  27226. /** @internal */
  27227. void colourChanged();
  27228. private:
  27229. TextButton (const TextButton&);
  27230. const TextButton& operator= (const TextButton&);
  27231. };
  27232. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  27233. /********* End of inlined file: juce_TextButton.h *********/
  27234. /**
  27235. A component displaying a list of plugins, with options to scan for them,
  27236. add, remove and sort them.
  27237. */
  27238. class JUCE_API PluginListComponent : public Component,
  27239. public ListBoxModel,
  27240. public ChangeListener,
  27241. public ButtonListener,
  27242. public Timer
  27243. {
  27244. public:
  27245. /**
  27246. Creates the list component.
  27247. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  27248. The properties file, if supplied, is used to store the user's last search paths.
  27249. */
  27250. PluginListComponent (KnownPluginList& listToRepresent,
  27251. const File& deadMansPedalFile,
  27252. PropertiesFile* const propertiesToUse);
  27253. /** Destructor. */
  27254. ~PluginListComponent();
  27255. /** @internal */
  27256. void resized();
  27257. /** @internal */
  27258. bool isInterestedInFileDrag (const StringArray& files);
  27259. /** @internal */
  27260. void filesDropped (const StringArray& files, int, int);
  27261. /** @internal */
  27262. int getNumRows();
  27263. /** @internal */
  27264. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  27265. /** @internal */
  27266. void deleteKeyPressed (int lastRowSelected);
  27267. /** @internal */
  27268. void buttonClicked (Button* b);
  27269. /** @internal */
  27270. void changeListenerCallback (void*);
  27271. /** @internal */
  27272. void timerCallback();
  27273. juce_UseDebuggingNewOperator
  27274. private:
  27275. KnownPluginList& list;
  27276. File deadMansPedalFile;
  27277. ListBox* listBox;
  27278. TextButton* optionsButton;
  27279. PropertiesFile* propertiesToUse;
  27280. int typeToScan;
  27281. void scanFor (AudioPluginFormat* format);
  27282. PluginListComponent (const PluginListComponent&);
  27283. const PluginListComponent& operator= (const PluginListComponent&);
  27284. };
  27285. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27286. /********* End of inlined file: juce_PluginListComponent.h *********/
  27287. #endif
  27288. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27289. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  27290. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27291. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27292. /********* Start of inlined file: juce_AudioFormat.h *********/
  27293. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27294. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  27295. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  27296. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27297. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27298. /**
  27299. Writes samples to an audio file stream.
  27300. A subclass that writes a specific type of audio format will be created by
  27301. an AudioFormat object.
  27302. After creating one of these with the AudioFormat::createWriterFor() method
  27303. you can call its write() method to store the samples, and then delete it.
  27304. @see AudioFormat, AudioFormatReader
  27305. */
  27306. class JUCE_API AudioFormatWriter
  27307. {
  27308. protected:
  27309. /** Creates an AudioFormatWriter object.
  27310. @param destStream the stream to write to - this will be deleted
  27311. by this object when it is no longer needed
  27312. @param formatName the description that will be returned by the getFormatName()
  27313. method
  27314. @param sampleRate the sample rate to use - the base class just stores
  27315. this value, it doesn't do anything with it
  27316. @param numberOfChannels the number of channels to write - the base class just stores
  27317. this value, it doesn't do anything with it
  27318. @param bitsPerSample the bit depth of the stream - the base class just stores
  27319. this value, it doesn't do anything with it
  27320. */
  27321. AudioFormatWriter (OutputStream* const destStream,
  27322. const String& formatName,
  27323. const double sampleRate,
  27324. const unsigned int numberOfChannels,
  27325. const unsigned int bitsPerSample);
  27326. public:
  27327. /** Destructor. */
  27328. virtual ~AudioFormatWriter();
  27329. /** Returns a description of what type of format this is.
  27330. E.g. "AIFF file"
  27331. */
  27332. const String getFormatName() const throw() { return formatName; }
  27333. /** Writes a set of samples to the audio stream.
  27334. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  27335. can use AudioSampleBuffer::writeToAudioWriter().
  27336. @param samplesToWrite an array of arrays containing the sample data for
  27337. each channel to write. This is a zero-terminated
  27338. array of arrays, and can contain a different number
  27339. of channels than the actual stream uses, and the
  27340. writer should do its best to cope with this.
  27341. If the format is fixed-point, each channel will be formatted
  27342. as an array of signed integers using the full 32-bit
  27343. range -0x80000000 to 0x7fffffff, regardless of the source's
  27344. bit-depth. If it is a floating-point format, you should treat
  27345. the arrays as arrays of floats, and just cast it to an (int**)
  27346. to pass it into the method.
  27347. @param numSamples the number of samples to write
  27348. */
  27349. virtual bool write (const int** samplesToWrite,
  27350. int numSamples) = 0;
  27351. /** Reads a section of samples from an AudioFormatReader, and writes these to
  27352. the output.
  27353. This will take care of any floating-point conversion that's required to convert
  27354. between the two formats. It won't deal with sample-rate conversion, though.
  27355. If numSamplesToRead < 0, it will write the entire length of the reader.
  27356. @returns false if it can't read or write properly during the operation
  27357. */
  27358. bool writeFromAudioReader (AudioFormatReader& reader,
  27359. int64 startSample,
  27360. int64 numSamplesToRead);
  27361. /** Reads some samples from an AudioSource, and writes these to the output.
  27362. The source must already have been initialised with the AudioSource::prepareToPlay() method
  27363. @param source the source to read from
  27364. @param numSamplesToRead total number of samples to read and write
  27365. @param samplesPerBlock the maximum number of samples to fetch from the source
  27366. @returns false if it can't read or write properly during the operation
  27367. */
  27368. bool writeFromAudioSource (AudioSource& source,
  27369. int numSamplesToRead,
  27370. const int samplesPerBlock = 2048);
  27371. /** Returns the sample rate being used. */
  27372. double getSampleRate() const throw() { return sampleRate; }
  27373. /** Returns the number of channels being written. */
  27374. int getNumChannels() const throw() { return numChannels; }
  27375. /** Returns the bit-depth of the data being written. */
  27376. int getBitsPerSample() const throw() { return bitsPerSample; }
  27377. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  27378. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  27379. juce_UseDebuggingNewOperator
  27380. protected:
  27381. /** The sample rate of the stream. */
  27382. double sampleRate;
  27383. /** The number of channels being written to the stream. */
  27384. unsigned int numChannels;
  27385. /** The bit depth of the file. */
  27386. unsigned int bitsPerSample;
  27387. /** True if it's a floating-point format, false if it's fixed-point. */
  27388. bool usesFloatingPointData;
  27389. /** The output stream for Use by subclasses. */
  27390. OutputStream* output;
  27391. private:
  27392. String formatName;
  27393. };
  27394. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27395. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  27396. /**
  27397. Subclasses of AudioFormat are used to read and write different audio
  27398. file formats.
  27399. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  27400. */
  27401. class JUCE_API AudioFormat
  27402. {
  27403. public:
  27404. /** Destructor. */
  27405. virtual ~AudioFormat();
  27406. /** Returns the name of this format.
  27407. e.g. "WAV file" or "AIFF file"
  27408. */
  27409. const String& getFormatName() const;
  27410. /** Returns all the file extensions that might apply to a file of this format.
  27411. The first item will be the one that's preferred when creating a new file.
  27412. So for a wav file this might just return ".wav"; for an AIFF file it might
  27413. return two items, ".aif" and ".aiff"
  27414. */
  27415. const StringArray& getFileExtensions() const;
  27416. /** Returns true if this the given file can be read by this format.
  27417. Subclasses shouldn't do too much work here, just check the extension or
  27418. file type. The base class implementation just checks the file's extension
  27419. against one of the ones that was registered in the constructor.
  27420. */
  27421. virtual bool canHandleFile (const File& fileToTest);
  27422. /** Returns a set of sample rates that the format can read and write. */
  27423. virtual const Array <int> getPossibleSampleRates() = 0;
  27424. /** Returns a set of bit depths that the format can read and write. */
  27425. virtual const Array <int> getPossibleBitDepths() = 0;
  27426. /** Returns true if the format can do 2-channel audio. */
  27427. virtual bool canDoStereo() = 0;
  27428. /** Returns true if the format can do 1-channel audio. */
  27429. virtual bool canDoMono() = 0;
  27430. /** Returns true if the format uses compressed data. */
  27431. virtual bool isCompressed();
  27432. /** Returns a list of different qualities that can be used when writing.
  27433. Non-compressed formats will just return an empty array, but for something
  27434. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  27435. When calling createWriterFor(), an index from this array is passed in to
  27436. tell the format which option is required.
  27437. */
  27438. virtual const StringArray getQualityOptions();
  27439. /** Tries to create an object that can read from a stream containing audio
  27440. data in this format.
  27441. The reader object that is returned can be used to read from the stream, and
  27442. should then be deleted by the caller.
  27443. @param sourceStream the stream to read from - the AudioFormatReader object
  27444. that is returned will delete this stream when it no longer
  27445. needs it.
  27446. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  27447. should delete the stream object that was passed-in. (If a valid
  27448. reader is returned, it will always be in charge of deleting the
  27449. stream, so this parameter is ignored)
  27450. @see AudioFormatReader
  27451. */
  27452. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27453. const bool deleteStreamIfOpeningFails) = 0;
  27454. /** Tries to create an object that can write to a stream with this audio format.
  27455. The writer object that is returned can be used to write to the stream, and
  27456. should then be deleted by the caller.
  27457. If the stream can't be created for some reason (e.g. the parameters passed in
  27458. here aren't suitable), this will return 0.
  27459. @param streamToWriteTo the stream that the data will go to - this will be
  27460. deleted by the AudioFormatWriter object when it's no longer
  27461. needed. If no AudioFormatWriter can be created by this method,
  27462. the stream will NOT be deleted, so that the caller can re-use it
  27463. to try to open a different format, etc
  27464. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  27465. returned by getPossibleSampleRates()
  27466. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  27467. the choice will depend on the results of canDoMono() and
  27468. canDoStereo()
  27469. @param bitsPerSample the bits per sample to use - this must be one of the values
  27470. returned by getPossibleBitDepths()
  27471. @param metadataValues a set of metadata values that the writer should try to write
  27472. to the stream. Exactly what these are depends on the format,
  27473. and the subclass doesn't actually have to do anything with
  27474. them if it doesn't want to. Have a look at the specific format
  27475. implementation classes to see possible values that can be
  27476. used
  27477. @param qualityOptionIndex the index of one of compression qualities returned by the
  27478. getQualityOptions() method. If there aren't any quality options
  27479. for this format, just pass 0 in this parameter, as it'll be
  27480. ignored
  27481. @see AudioFormatWriter
  27482. */
  27483. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27484. double sampleRateToUse,
  27485. unsigned int numberOfChannels,
  27486. int bitsPerSample,
  27487. const StringPairArray& metadataValues,
  27488. int qualityOptionIndex) = 0;
  27489. protected:
  27490. /** Creates an AudioFormat object.
  27491. @param formatName this sets the value that will be returned by getFormatName()
  27492. @param fileExtensions a zero-terminated list of file extensions - this is what will
  27493. be returned by getFileExtension()
  27494. */
  27495. AudioFormat (const String& formatName,
  27496. const tchar** const fileExtensions);
  27497. private:
  27498. String formatName;
  27499. StringArray fileExtensions;
  27500. };
  27501. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  27502. /********* End of inlined file: juce_AudioFormat.h *********/
  27503. /**
  27504. Reads and Writes AIFF format audio files.
  27505. @see AudioFormat
  27506. */
  27507. class JUCE_API AiffAudioFormat : public AudioFormat
  27508. {
  27509. public:
  27510. /** Creates an format object. */
  27511. AiffAudioFormat();
  27512. /** Destructor. */
  27513. ~AiffAudioFormat();
  27514. const Array <int> getPossibleSampleRates();
  27515. const Array <int> getPossibleBitDepths();
  27516. bool canDoStereo();
  27517. bool canDoMono();
  27518. #if JUCE_MAC
  27519. bool canHandleFile (const File& fileToTest);
  27520. #endif
  27521. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  27522. const bool deleteStreamIfOpeningFails);
  27523. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  27524. double sampleRateToUse,
  27525. unsigned int numberOfChannels,
  27526. int bitsPerSample,
  27527. const StringPairArray& metadataValues,
  27528. int qualityOptionIndex);
  27529. juce_UseDebuggingNewOperator
  27530. };
  27531. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  27532. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  27533. #endif
  27534. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27535. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  27536. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27537. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27538. /**
  27539. */
  27540. class AudioCDBurner
  27541. {
  27542. public:
  27543. /** Returns a list of available optical drives.
  27544. Use openDevice() to open one of the items from this list.
  27545. */
  27546. static const StringArray findAvailableDevices();
  27547. /** Tries to open one of the optical drives.
  27548. The deviceIndex is an index into the array returned by findAvailableDevices().
  27549. */
  27550. static AudioCDBurner* openDevice (const int deviceIndex);
  27551. /** Destructor. */
  27552. ~AudioCDBurner();
  27553. /** Returns true if there's a writable disk in the drive.
  27554. */
  27555. bool isDiskPresent() const;
  27556. /** Returns the number of free blocks on the disk.
  27557. There are 75 blocks per second, at 44100Hz.
  27558. */
  27559. int getNumAvailableAudioBlocks() const;
  27560. /** Adds a track to be written.
  27561. The source passed-in here will be kept by this object, and it will
  27562. be used and deleted at some point in the future, either during the
  27563. burn() method or when this AudioCDBurner object is deleted. Your caller
  27564. method shouldn't keep a reference to it or use it again after passing
  27565. it in here.
  27566. */
  27567. bool addAudioTrack (AudioSource* source, int numSamples);
  27568. /**
  27569. Return true to cancel the current burn operation
  27570. */
  27571. class BurnProgressListener
  27572. {
  27573. public:
  27574. BurnProgressListener() throw() {}
  27575. virtual ~BurnProgressListener() {}
  27576. /** Called at intervals to report on the progress of the AudioCDBurner.
  27577. To cancel the burn, return true from this.
  27578. */
  27579. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  27580. };
  27581. const String burn (BurnProgressListener* listener,
  27582. const bool ejectDiscAfterwards,
  27583. const bool peformFakeBurnForTesting);
  27584. juce_UseDebuggingNewOperator
  27585. private:
  27586. AudioCDBurner (const int deviceIndex);
  27587. void* internal;
  27588. };
  27589. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  27590. /********* End of inlined file: juce_AudioCDBurner.h *********/
  27591. #endif
  27592. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27593. /********* Start of inlined file: juce_AudioCDReader.h *********/
  27594. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  27595. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  27596. #if JUCE_MAC
  27597. #endif
  27598. /**
  27599. A type of AudioFormatReader that reads from an audio CD.
  27600. One of these can be used to read a CD as if it's one big audio stream. Use the
  27601. getPositionOfTrackStart() method to find where the individual tracks are
  27602. within the stream.
  27603. @see AudioFormatReader
  27604. */
  27605. class JUCE_API AudioCDReader : public AudioFormatReader
  27606. {
  27607. public:
  27608. /** Returns a list of names of Audio CDs currently available for reading.
  27609. If there's a CD drive but no CD in it, this might return an empty list, or
  27610. possibly a device that can be opened but which has no tracks, depending
  27611. on the platform.
  27612. @see createReaderForCD
  27613. */
  27614. static const StringArray getAvailableCDNames();
  27615. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  27616. @param index the index of one of the available CDs - use getAvailableCDNames()
  27617. to find out how many there are.
  27618. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  27619. caller will be responsible for deleting the object returned.
  27620. */
  27621. static AudioCDReader* createReaderForCD (const int index);
  27622. /** Destructor. */
  27623. ~AudioCDReader();
  27624. /** Implementation of the AudioFormatReader method. */
  27625. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27626. int64 startSampleInFile, int numSamples);
  27627. /** Checks whether the CD has been removed from the drive.
  27628. */
  27629. bool isCDStillPresent() const;
  27630. /** Returns the total number of tracks (audio + data).
  27631. */
  27632. int getNumTracks() const;
  27633. /** Finds the sample offset of the start of a track.
  27634. @param trackNum the track number, where 0 is the first track.
  27635. */
  27636. int getPositionOfTrackStart (int trackNum) const;
  27637. /** Returns true if a given track is an audio track.
  27638. @param trackNum the track number, where 0 is the first track.
  27639. */
  27640. bool isTrackAudio (int trackNum) const;
  27641. /** Refreshes the object's table of contents.
  27642. If the disc has been ejected and a different one put in since this
  27643. object was created, this will cause it to update its idea of how many tracks
  27644. there are, etc.
  27645. */
  27646. void refreshTrackLengths();
  27647. /** Enables scanning for indexes within tracks.
  27648. @see getLastIndex
  27649. */
  27650. void enableIndexScanning (bool enabled);
  27651. /** Returns the index number found during the last read() call.
  27652. Index scanning is turned off by default - turn it on with enableIndexScanning().
  27653. Then when the read() method is called, if it comes across an index within that
  27654. block, the index number is stored and returned by this method.
  27655. Some devices might not support indexes, of course.
  27656. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  27657. @see enableIndexScanning
  27658. */
  27659. int getLastIndex() const;
  27660. /** Scans a track to find the position of any indexes within it.
  27661. @param trackNumber the track to look in, where 0 is the first track on the disc
  27662. @returns an array of sample positions of any index points found (not including
  27663. the index that marks the start of the track)
  27664. */
  27665. const Array <int> findIndexesInTrack (const int trackNumber);
  27666. /** Returns the CDDB id number for the CD.
  27667. It's not a great way of identifying a disc, but it's traditional.
  27668. */
  27669. int getCDDBId();
  27670. /** Tries to eject the disk.
  27671. Of course this might not be possible, if some other process is using it.
  27672. */
  27673. void ejectDisk();
  27674. juce_UseDebuggingNewOperator
  27675. private:
  27676. #if JUCE_MAC
  27677. File volumeDir;
  27678. OwnedArray<File> tracks;
  27679. Array <int> trackStartSamples;
  27680. int currentReaderTrack;
  27681. AudioFormatReader* reader;
  27682. AudioCDReader (const File& volume);
  27683. public:
  27684. static int compareElements (const File* const, const File* const) throw();
  27685. private:
  27686. #elif JUCE_WIN32
  27687. int numTracks;
  27688. int trackStarts[100];
  27689. bool audioTracks [100];
  27690. void* handle;
  27691. bool indexingEnabled;
  27692. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  27693. MemoryBlock buffer;
  27694. AudioCDReader (void* handle);
  27695. int getIndexAt (int samplePos);
  27696. #elif JUCE_LINUX
  27697. AudioCDReader();
  27698. #endif
  27699. AudioCDReader (const AudioCDReader&);
  27700. const AudioCDReader& operator= (const AudioCDReader&);
  27701. };
  27702. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  27703. /********* End of inlined file: juce_AudioCDReader.h *********/
  27704. #endif
  27705. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  27706. #endif
  27707. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27708. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  27709. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27710. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27711. /**
  27712. A class for keeping a list of available audio formats, and for deciding which
  27713. one to use to open a given file.
  27714. You can either use this class as a singleton object, or create instances of it
  27715. yourself. Once created, use its registerFormat() method to tell it which
  27716. formats it should use.
  27717. @see AudioFormat
  27718. */
  27719. class JUCE_API AudioFormatManager
  27720. {
  27721. public:
  27722. /** Creates an empty format manager.
  27723. Before it'll be any use, you'll need to call registerFormat() with all the
  27724. formats you want it to be able to recognise.
  27725. */
  27726. AudioFormatManager();
  27727. /** Destructor. */
  27728. ~AudioFormatManager();
  27729. juce_DeclareSingleton (AudioFormatManager, false);
  27730. /** Adds a format to the manager's list of available file types.
  27731. The object passed-in will be deleted by this object, so don't keep a pointer
  27732. to it!
  27733. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  27734. return this one when called.
  27735. */
  27736. void registerFormat (AudioFormat* newFormat,
  27737. const bool makeThisTheDefaultFormat);
  27738. /** Handy method to make it easy to register the formats that come with Juce.
  27739. Currently, this will add WAV and AIFF to the list.
  27740. */
  27741. void registerBasicFormats();
  27742. /** Clears the list of known formats. */
  27743. void clearFormats();
  27744. /** Returns the number of currently registered file formats. */
  27745. int getNumKnownFormats() const;
  27746. /** Returns one of the registered file formats. */
  27747. AudioFormat* getKnownFormat (const int index) const;
  27748. /** Looks for which of the known formats is listed as being for a given file
  27749. extension.
  27750. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  27751. */
  27752. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  27753. /** Returns the format which has been set as the default one.
  27754. You can set a format as being the default when it is registered. It's useful
  27755. when you want to write to a file, because the best format may change between
  27756. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  27757. If none has been set as the default, this method will just return the first
  27758. one in the list.
  27759. */
  27760. AudioFormat* getDefaultFormat() const;
  27761. /** Returns a set of wildcards for file-matching that contains the extensions for
  27762. all known formats.
  27763. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  27764. */
  27765. const String getWildcardForAllFormats() const;
  27766. /** Searches through the known formats to try to create a suitable reader for
  27767. this file.
  27768. If none of the registered formats can open the file, it'll return 0. If it
  27769. returns a reader, it's the caller's responsibility to delete the reader.
  27770. */
  27771. AudioFormatReader* createReaderFor (const File& audioFile);
  27772. /** Searches through the known formats to try to create a suitable reader for
  27773. this stream.
  27774. The stream object that is passed-in will be deleted by this method or by the
  27775. reader that is returned, so the caller should not keep any references to it.
  27776. The stream that is passed-in must be capable of being repositioned so
  27777. that all the formats can have a go at opening it.
  27778. If none of the registered formats can open the stream, it'll return 0. If it
  27779. returns a reader, it's the caller's responsibility to delete the reader.
  27780. */
  27781. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  27782. juce_UseDebuggingNewOperator
  27783. private:
  27784. VoidArray knownFormats;
  27785. int defaultFormatIndex;
  27786. };
  27787. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  27788. /********* End of inlined file: juce_AudioFormatManager.h *********/
  27789. #endif
  27790. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  27791. #endif
  27792. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  27793. #endif
  27794. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27795. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  27796. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27797. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27798. class AudioThumbnailCache;
  27799. /**
  27800. Makes it easy to quickly draw scaled views of the waveform shape of an
  27801. audio file.
  27802. To use this class, just create an AudioThumbNail class for the file you want
  27803. to draw, call setSource to tell it which file or resource to use, then call
  27804. drawChannel() to draw it.
  27805. The class will asynchronously scan the wavefile to create its scaled-down view,
  27806. so you should make your UI repaint itself as this data comes in. To do this, the
  27807. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  27808. listeners should repaint themselves.
  27809. The thumbnail stores an internal low-res version of the wave data, and this can
  27810. be loaded and saved to avoid having to scan the file again.
  27811. @see AudioThumbnailCache
  27812. */
  27813. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  27814. public TimeSliceClient,
  27815. private Timer
  27816. {
  27817. public:
  27818. /** Creates an audio thumbnail.
  27819. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  27820. of the audio data, this is the scale at which it should be done. (This
  27821. number is the number of original samples that will be averaged for each
  27822. low-res sample)
  27823. @param formatManagerToUse the audio format manager that is used to open the file
  27824. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  27825. thread and storage that is used to by the thumbnail, and the cache
  27826. object can be shared between multiple thumbnails
  27827. */
  27828. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  27829. AudioFormatManager& formatManagerToUse,
  27830. AudioThumbnailCache& cacheToUse);
  27831. /** Destructor. */
  27832. ~AudioThumbnail();
  27833. /** Specifies the file or stream that contains the audio file.
  27834. For a file, just call
  27835. @code
  27836. setSource (new FileInputSource (file))
  27837. @endcode
  27838. You can pass a zero in here to clear the thumbnail.
  27839. The source that is passed in will be deleted by this object when it is no
  27840. longer needed
  27841. */
  27842. void setSource (InputSource* const newSource);
  27843. /** Reloads the low res thumbnail data from an input stream.
  27844. The thumb will automatically attempt to reload itself from its
  27845. AudioThumbnailCache.
  27846. */
  27847. void loadFrom (InputStream& input);
  27848. /** Saves the low res thumbnail data to an output stream.
  27849. The thumb will automatically attempt to save itself to its
  27850. AudioThumbnailCache after it finishes scanning the wave file.
  27851. */
  27852. void saveTo (OutputStream& output) const;
  27853. /** Returns the number of channels in the file.
  27854. */
  27855. int getNumChannels() const throw();
  27856. /** Returns the length of the audio file, in seconds.
  27857. */
  27858. double getTotalLength() const throw();
  27859. /** Renders the waveform shape for a channel.
  27860. The waveform will be drawn within the specified rectangle, where startTime
  27861. and endTime specify the times within the audio file that should be positioned
  27862. at the left and right edges of the rectangle.
  27863. The waveform will be scaled vertically so that a full-volume sample will fill
  27864. the rectangle vertically, but you can also specify an extra vertical scale factor
  27865. with the verticalZoomFactor parameter.
  27866. */
  27867. void drawChannel (Graphics& g,
  27868. int x, int y, int w, int h,
  27869. double startTimeSeconds,
  27870. double endTimeSeconds,
  27871. int channelNum,
  27872. const float verticalZoomFactor);
  27873. /** Returns true if the low res preview is fully generated.
  27874. */
  27875. bool isFullyLoaded() const throw();
  27876. /** @internal */
  27877. bool useTimeSlice();
  27878. /** @internal */
  27879. void timerCallback();
  27880. juce_UseDebuggingNewOperator
  27881. private:
  27882. AudioFormatManager& formatManagerToUse;
  27883. AudioThumbnailCache& cache;
  27884. InputSource* source;
  27885. CriticalSection readerLock;
  27886. AudioFormatReader* reader;
  27887. MemoryBlock data, cachedLevels;
  27888. int orginalSamplesPerThumbnailSample;
  27889. int numChannelsCached, numSamplesCached;
  27890. double cachedStart, cachedTimePerPixel;
  27891. bool cacheNeedsRefilling;
  27892. void clear();
  27893. AudioFormatReader* createReader() const;
  27894. void generateSection (AudioFormatReader& reader,
  27895. int64 startSample,
  27896. int numSamples);
  27897. char* getChannelData (int channel) const;
  27898. void refillCache (const int numSamples,
  27899. double startTime,
  27900. const double timePerPixel);
  27901. friend class AudioThumbnailCache;
  27902. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  27903. bool initialiseFromAudioFile (AudioFormatReader& reader);
  27904. // returns true if more needs to be read
  27905. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  27906. };
  27907. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  27908. /********* End of inlined file: juce_AudioThumbnail.h *********/
  27909. #endif
  27910. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27911. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  27912. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27913. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27914. /**
  27915. This class is used to wrap an AudioFormatReader and only read from a
  27916. subsection of the file.
  27917. So if you have a reader which can read a 1000 sample file, you could wrap it
  27918. in one of these to only access, e.g. samples 100 to 200, and any samples
  27919. outside that will come back as 0. Accessing sample 0 from this reader will
  27920. actually read the first sample from the other's subsection, which might
  27921. be at a non-zero position.
  27922. @see AudioFormatReader
  27923. */
  27924. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  27925. {
  27926. public:
  27927. /** Creates a AudioSubsectionReader for a given data source.
  27928. @param sourceReader the source reader from which we'll be taking data
  27929. @param subsectionStartSample the sample within the source reader which will be
  27930. mapped onto sample 0 for this reader.
  27931. @param subsectionLength the number of samples from the source that will
  27932. make up the subsection. If this reader is asked for
  27933. any samples beyond this region, it will return zero.
  27934. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  27935. this object is deleted.
  27936. */
  27937. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  27938. const int64 subsectionStartSample,
  27939. const int64 subsectionLength,
  27940. const bool deleteSourceWhenDeleted);
  27941. /** Destructor. */
  27942. ~AudioSubsectionReader();
  27943. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  27944. int64 startSampleInFile, int numSamples);
  27945. void readMaxLevels (int64 startSample,
  27946. int64 numSamples,
  27947. float& lowestLeft,
  27948. float& highestLeft,
  27949. float& lowestRight,
  27950. float& highestRight);
  27951. juce_UseDebuggingNewOperator
  27952. private:
  27953. AudioFormatReader* const source;
  27954. int64 startSample, length;
  27955. const bool deleteSourceWhenDeleted;
  27956. AudioSubsectionReader (const AudioSubsectionReader&);
  27957. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  27958. };
  27959. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  27960. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  27961. #endif
  27962. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27963. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  27964. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27965. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  27966. struct ThumbnailCacheEntry;
  27967. /**
  27968. An instance of this class is used to manage multiple AudioThumbnail objects.
  27969. The cache runs a single background thread that is shared by all the thumbnails
  27970. that need it, and it maintains a set of low-res previews in memory, to avoid
  27971. having to re-scan audio files too often.
  27972. @see AudioThumbnail
  27973. */
  27974. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  27975. {
  27976. public:
  27977. /** Creates a cache object.
  27978. The maxNumThumbsToStore parameter lets you specify how many previews should
  27979. be kept in memory at once.
  27980. */
  27981. AudioThumbnailCache (const int maxNumThumbsToStore);
  27982. /** Destructor. */
  27983. ~AudioThumbnailCache();
  27984. /** Clears out any stored thumbnails.
  27985. */
  27986. void clear();
  27987. /** Reloads the specified thumb if this cache contains the appropriate stored
  27988. data.
  27989. This is called automatically by the AudioThumbnail class, so you shouldn't
  27990. normally need to call it directly.
  27991. */
  27992. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  27993. /** Stores the cachable data from the specified thumb in this cache.
  27994. This is called automatically by the AudioThumbnail class, so you shouldn't
  27995. normally need to call it directly.
  27996. */
  27997. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  27998. juce_UseDebuggingNewOperator
  27999. private:
  28000. OwnedArray <ThumbnailCacheEntry> thumbs;
  28001. int maxNumThumbsToStore;
  28002. friend class AudioThumbnail;
  28003. void addThumbnail (AudioThumbnail* const thumb);
  28004. void removeThumbnail (AudioThumbnail* const thumb);
  28005. };
  28006. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  28007. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  28008. #endif
  28009. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28010. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  28011. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28012. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28013. #if JUCE_USE_FLAC || defined (DOXYGEN)
  28014. /**
  28015. Reads and writes the lossless-compression FLAC audio format.
  28016. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  28017. and make sure your include search path and library search path are set up to find
  28018. the FLAC header files and static libraries.
  28019. @see AudioFormat
  28020. */
  28021. class JUCE_API FlacAudioFormat : public AudioFormat
  28022. {
  28023. public:
  28024. FlacAudioFormat();
  28025. ~FlacAudioFormat();
  28026. const Array <int> getPossibleSampleRates();
  28027. const Array <int> getPossibleBitDepths();
  28028. bool canDoStereo();
  28029. bool canDoMono();
  28030. bool isCompressed();
  28031. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28032. const bool deleteStreamIfOpeningFails);
  28033. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28034. double sampleRateToUse,
  28035. unsigned int numberOfChannels,
  28036. int bitsPerSample,
  28037. const StringPairArray& metadataValues,
  28038. int qualityOptionIndex);
  28039. juce_UseDebuggingNewOperator
  28040. };
  28041. #endif
  28042. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  28043. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  28044. #endif
  28045. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28046. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  28047. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28048. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28049. /**
  28050. Reads and Writes WAV format audio files.
  28051. @see AudioFormat
  28052. */
  28053. class JUCE_API WavAudioFormat : public AudioFormat
  28054. {
  28055. public:
  28056. /** Creates a format object. */
  28057. WavAudioFormat();
  28058. /** Destructor. */
  28059. ~WavAudioFormat();
  28060. /** Metadata property name used by wav readers and writers for adding
  28061. a BWAV chunk to the file.
  28062. @see AudioFormatReader::metadataValues, createWriterFor
  28063. */
  28064. static const tchar* const bwavDescription;
  28065. /** Metadata property name used by wav readers and writers for adding
  28066. a BWAV chunk to the file.
  28067. @see AudioFormatReader::metadataValues, createWriterFor
  28068. */
  28069. static const tchar* const bwavOriginator;
  28070. /** Metadata property name used by wav readers and writers for adding
  28071. a BWAV chunk to the file.
  28072. @see AudioFormatReader::metadataValues, createWriterFor
  28073. */
  28074. static const tchar* const bwavOriginatorRef;
  28075. /** Metadata property name used by wav readers and writers for adding
  28076. a BWAV chunk to the file.
  28077. Date format is: yyyy-mm-dd
  28078. @see AudioFormatReader::metadataValues, createWriterFor
  28079. */
  28080. static const tchar* const bwavOriginationDate;
  28081. /** Metadata property name used by wav readers and writers for adding
  28082. a BWAV chunk to the file.
  28083. Time format is: hh-mm-ss
  28084. @see AudioFormatReader::metadataValues, createWriterFor
  28085. */
  28086. static const tchar* const bwavOriginationTime;
  28087. /** Metadata property name used by wav readers and writers for adding
  28088. a BWAV chunk to the file.
  28089. This is the number of samples from the start of an edit that the
  28090. file is supposed to begin at. Seems like an obvious mistake to
  28091. only allow a file to occur in an edit once, but that's the way
  28092. it is..
  28093. @see AudioFormatReader::metadataValues, createWriterFor
  28094. */
  28095. static const tchar* const bwavTimeReference;
  28096. /** Metadata property name used by wav readers and writers for adding
  28097. a BWAV chunk to the file.
  28098. This is a
  28099. @see AudioFormatReader::metadataValues, createWriterFor
  28100. */
  28101. static const tchar* const bwavCodingHistory;
  28102. /** Utility function to fill out the appropriate metadata for a BWAV file.
  28103. This just makes it easier than using the property names directly, and it
  28104. fills out the time and date in the right format.
  28105. */
  28106. static const StringPairArray createBWAVMetadata (const String& description,
  28107. const String& originator,
  28108. const String& originatorRef,
  28109. const Time& dateAndTime,
  28110. const int64 timeReferenceSamples,
  28111. const String& codingHistory);
  28112. const Array <int> getPossibleSampleRates();
  28113. const Array <int> getPossibleBitDepths();
  28114. bool canDoStereo();
  28115. bool canDoMono();
  28116. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28117. const bool deleteStreamIfOpeningFails);
  28118. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28119. double sampleRateToUse,
  28120. unsigned int numberOfChannels,
  28121. int bitsPerSample,
  28122. const StringPairArray& metadataValues,
  28123. int qualityOptionIndex);
  28124. /** Utility function to replace the metadata in a wav file with a new set of values.
  28125. If possible, this cheats by overwriting just the metadata region of the file, rather
  28126. than by copying the whole file again.
  28127. */
  28128. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  28129. juce_UseDebuggingNewOperator
  28130. };
  28131. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  28132. /********* End of inlined file: juce_WavAudioFormat.h *********/
  28133. #endif
  28134. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28135. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  28136. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28137. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28138. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  28139. /**
  28140. Reads and writes the Ogg-Vorbis audio format.
  28141. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  28142. and make sure your include search path and library search path are set up to find
  28143. the Vorbis and Ogg header files and static libraries.
  28144. @see AudioFormat,
  28145. */
  28146. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  28147. {
  28148. public:
  28149. OggVorbisAudioFormat();
  28150. ~OggVorbisAudioFormat();
  28151. const Array <int> getPossibleSampleRates();
  28152. const Array <int> getPossibleBitDepths();
  28153. bool canDoStereo();
  28154. bool canDoMono();
  28155. bool isCompressed();
  28156. const StringArray getQualityOptions();
  28157. /** Tries to estimate the quality level of an ogg file based on its size.
  28158. If it can't read the file for some reason, this will just return 1 (medium quality),
  28159. otherwise it will return the approximate quality setting that would have been used
  28160. to create the file.
  28161. @see getQualityOptions
  28162. */
  28163. int estimateOggFileQuality (const File& source);
  28164. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28165. const bool deleteStreamIfOpeningFails);
  28166. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28167. double sampleRateToUse,
  28168. unsigned int numberOfChannels,
  28169. int bitsPerSample,
  28170. const StringPairArray& metadataValues,
  28171. int qualityOptionIndex);
  28172. juce_UseDebuggingNewOperator
  28173. };
  28174. #endif
  28175. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  28176. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  28177. #endif
  28178. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28179. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  28180. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28181. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28182. #if JUCE_QUICKTIME
  28183. /**
  28184. Uses QuickTime to read the audio track a movie or media file.
  28185. As well as QuickTime movies, this should also manage to open other audio
  28186. files that quicktime can understand, like mp3, m4a, etc.
  28187. @see AudioFormat
  28188. */
  28189. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  28190. {
  28191. public:
  28192. /** Creates a format object. */
  28193. QuickTimeAudioFormat();
  28194. /** Destructor. */
  28195. ~QuickTimeAudioFormat();
  28196. const Array <int> getPossibleSampleRates();
  28197. const Array <int> getPossibleBitDepths();
  28198. bool canDoStereo();
  28199. bool canDoMono();
  28200. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  28201. const bool deleteStreamIfOpeningFails);
  28202. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  28203. double sampleRateToUse,
  28204. unsigned int numberOfChannels,
  28205. int bitsPerSample,
  28206. const StringPairArray& metadataValues,
  28207. int qualityOptionIndex);
  28208. juce_UseDebuggingNewOperator
  28209. };
  28210. #endif
  28211. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  28212. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  28213. #endif
  28214. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28215. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  28216. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28217. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28218. /********* Start of inlined file: juce_ActionListenerList.h *********/
  28219. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28220. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28221. /**
  28222. A set of ActionListeners.
  28223. Listeners can be added and removed from the list, and messages can be
  28224. broadcast to all the listeners.
  28225. @see ActionListener, ActionBroadcaster
  28226. */
  28227. class JUCE_API ActionListenerList : public MessageListener
  28228. {
  28229. public:
  28230. /** Creates an empty list. */
  28231. ActionListenerList() throw();
  28232. /** Destructor. */
  28233. ~ActionListenerList() throw();
  28234. /** Adds a listener to the list.
  28235. (Trying to add a listener that's already on the list will have no effect).
  28236. */
  28237. void addActionListener (ActionListener* const listener) throw();
  28238. /** Removes a listener from the list.
  28239. If the listener isn't on the list, this won't have any effect.
  28240. */
  28241. void removeActionListener (ActionListener* const listener) throw();
  28242. /** Removes all listeners from the list. */
  28243. void removeAllActionListeners() throw();
  28244. /** Broadcasts a message to all the registered listeners.
  28245. This sends the message asynchronously.
  28246. If a listener is on the list when this method is called but is removed from
  28247. the list before the message arrives, it won't receive the message. Similarly
  28248. listeners that are added to the list after the message is sent but before it
  28249. arrives won't get the message either.
  28250. */
  28251. void sendActionMessage (const String& message) const;
  28252. /** @internal */
  28253. void handleMessage (const Message&);
  28254. juce_UseDebuggingNewOperator
  28255. private:
  28256. SortedSet <void*> actionListeners_;
  28257. CriticalSection actionListenerLock_;
  28258. ActionListenerList (const ActionListenerList&);
  28259. const ActionListenerList& operator= (const ActionListenerList&);
  28260. };
  28261. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28262. /********* End of inlined file: juce_ActionListenerList.h *********/
  28263. /** Manages a list of ActionListeners, and can send them messages.
  28264. To quickly add methods to your class that can add/remove action
  28265. listeners and broadcast to them, you can derive from this.
  28266. @see ActionListenerList, ActionListener
  28267. */
  28268. class JUCE_API ActionBroadcaster
  28269. {
  28270. public:
  28271. /** Creates an ActionBroadcaster. */
  28272. ActionBroadcaster() throw();
  28273. /** Destructor. */
  28274. virtual ~ActionBroadcaster();
  28275. /** Adds a listener to the list.
  28276. (Trying to add a listener that's already on the list will have no effect).
  28277. */
  28278. void addActionListener (ActionListener* const listener);
  28279. /** Removes a listener from the list.
  28280. If the listener isn't on the list, this won't have any effect.
  28281. */
  28282. void removeActionListener (ActionListener* const listener);
  28283. /** Removes all listeners from the list. */
  28284. void removeAllActionListeners();
  28285. /** Broadcasts a message to all the registered listeners.
  28286. @see ActionListenerList::sendActionMessage
  28287. */
  28288. void sendActionMessage (const String& message) const;
  28289. private:
  28290. ActionListenerList actionListenerList;
  28291. ActionBroadcaster (const ActionBroadcaster&);
  28292. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  28293. };
  28294. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  28295. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  28296. #endif
  28297. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  28298. #endif
  28299. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  28300. #endif
  28301. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  28302. #endif
  28303. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28304. /********* Start of inlined file: juce_CallbackMessage.h *********/
  28305. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28306. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28307. /**
  28308. A message that calls a custom function when it gets delivered.
  28309. You can use this class to fire off actions that you want to be performed later
  28310. on the message thread.
  28311. Unlike other Message objects, these don't get sent to a MessageListener, you
  28312. just call the post() method to send them, and when they arrive, your
  28313. messageCallback() method will automatically be invoked.
  28314. @see MessageListener, MessageManager, ActionListener, ChangeListener
  28315. */
  28316. class JUCE_API CallbackMessage : public Message
  28317. {
  28318. public:
  28319. CallbackMessage() throw();
  28320. /** Destructor. */
  28321. ~CallbackMessage() throw();
  28322. /** Called when the message is delivered.
  28323. You should implement this method and make it do whatever action you want
  28324. to perform.
  28325. Note that like all other messages, this object will be deleted immediately
  28326. after this method has been invoked.
  28327. */
  28328. virtual void messageCallback() = 0;
  28329. /** Instead of sending this message to a MessageListener, just call this method
  28330. to post it to the event queue.
  28331. After you've called this, this object will belong to the MessageManager,
  28332. which will delete it later. So make sure you don't delete the object yourself,
  28333. call post() more than once, or call post() on a stack-based obect!
  28334. */
  28335. void post();
  28336. juce_UseDebuggingNewOperator
  28337. private:
  28338. CallbackMessage (const CallbackMessage&);
  28339. const CallbackMessage& operator= (const CallbackMessage&);
  28340. };
  28341. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  28342. /********* End of inlined file: juce_CallbackMessage.h *********/
  28343. #endif
  28344. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  28345. #endif
  28346. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  28347. #endif
  28348. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  28349. #endif
  28350. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28351. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  28352. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28353. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28354. class InterprocessConnectionServer;
  28355. /**
  28356. Manages a simple two-way messaging connection to another process, using either
  28357. a socket or a named pipe as the transport medium.
  28358. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  28359. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  28360. and incoming messages will result in a callback via the messageReceived()
  28361. method.
  28362. To open a pipe and wait for another client to connect to it, use the createPipe()
  28363. method.
  28364. To act as a socket server and create connections for one or more client, see the
  28365. InterprocessConnectionServer class.
  28366. @see InterprocessConnectionServer, Socket, NamedPipe
  28367. */
  28368. class JUCE_API InterprocessConnection : public Thread,
  28369. private MessageListener
  28370. {
  28371. public:
  28372. /** Creates a connection.
  28373. Connections are created manually, connecting them with the connectToSocket()
  28374. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  28375. when a client wants to connect.
  28376. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  28377. connectionLost() and messageReceived() methods will
  28378. always be made using the message thread; if false,
  28379. these will be called immediately on the connection's
  28380. own thread.
  28381. @param magicMessageHeaderNumber a magic number to use in the header to check the
  28382. validity of the data blocks being sent and received. This
  28383. can be any number, but the sender and receiver must obviously
  28384. use matching values or they won't recognise each other.
  28385. */
  28386. InterprocessConnection (const bool callbacksOnMessageThread = true,
  28387. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  28388. /** Destructor. */
  28389. ~InterprocessConnection();
  28390. /** Tries to connect this object to a socket.
  28391. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  28392. object waiting to receive client connections on this port number.
  28393. @param hostName the host computer, either a network address or name
  28394. @param portNumber the socket port number to try to connect to
  28395. @param timeOutMillisecs how long to keep trying before giving up
  28396. @returns true if the connection is established successfully
  28397. @see Socket
  28398. */
  28399. bool connectToSocket (const String& hostName,
  28400. const int portNumber,
  28401. const int timeOutMillisecs);
  28402. /** Tries to connect the object to an existing named pipe.
  28403. For this to work, another process on the same computer must already have opened
  28404. an InterprocessConnection object and used createPipe() to create a pipe for this
  28405. to connect to.
  28406. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  28407. @returns true if it connects successfully.
  28408. @see createPipe, NamedPipe
  28409. */
  28410. bool connectToPipe (const String& pipeName,
  28411. const int pipeReceiveMessageTimeoutMs = -1);
  28412. /** Tries to create a new pipe for other processes to connect to.
  28413. This creates a pipe with the given name, so that other processes can use
  28414. connectToPipe() to connect to the other end.
  28415. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  28416. If another process is already using this pipe, this will fail and return false.
  28417. */
  28418. bool createPipe (const String& pipeName,
  28419. const int pipeReceiveMessageTimeoutMs = -1);
  28420. /** Disconnects and closes any currently-open sockets or pipes. */
  28421. void disconnect();
  28422. /** True if a socket or pipe is currently active. */
  28423. bool isConnected() const;
  28424. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  28425. StreamingSocket* getSocket() const throw() { return socket; }
  28426. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  28427. NamedPipe* getPipe() const throw() { return pipe; }
  28428. /** Returns the name of the machine at the other end of this connection.
  28429. This will return an empty string if the other machine isn't known for
  28430. some reason.
  28431. */
  28432. const String getConnectedHostName() const;
  28433. /** Tries to send a message to the other end of this connection.
  28434. This will fail if it's not connected, or if there's some kind of write error. If
  28435. it succeeds, the connection object at the other end will receive the message by
  28436. a callback to its messageReceived() method.
  28437. @see messageReceived
  28438. */
  28439. bool sendMessage (const MemoryBlock& message);
  28440. /** Called when the connection is first connected.
  28441. If the connection was created with the callbacksOnMessageThread flag set, then
  28442. this will be called on the message thread; otherwise it will be called on a server
  28443. thread.
  28444. */
  28445. virtual void connectionMade() = 0;
  28446. /** Called when the connection is broken.
  28447. If the connection was created with the callbacksOnMessageThread flag set, then
  28448. this will be called on the message thread; otherwise it will be called on a server
  28449. thread.
  28450. */
  28451. virtual void connectionLost() = 0;
  28452. /** Called when a message arrives.
  28453. When the object at the other end of this connection sends us a message with sendMessage(),
  28454. this callback is used to deliver it to us.
  28455. If the connection was created with the callbacksOnMessageThread flag set, then
  28456. this will be called on the message thread; otherwise it will be called on a server
  28457. thread.
  28458. @see sendMessage
  28459. */
  28460. virtual void messageReceived (const MemoryBlock& message) = 0;
  28461. juce_UseDebuggingNewOperator
  28462. private:
  28463. CriticalSection pipeAndSocketLock;
  28464. StreamingSocket* socket;
  28465. NamedPipe* pipe;
  28466. bool callbackConnectionState;
  28467. const bool useMessageThread;
  28468. const uint32 magicMessageHeader;
  28469. int pipeReceiveMessageTimeout;
  28470. friend class InterprocessConnectionServer;
  28471. void initialiseWithSocket (StreamingSocket* const socket_);
  28472. void initialiseWithPipe (NamedPipe* const pipe_);
  28473. void handleMessage (const Message& message);
  28474. void connectionMadeInt();
  28475. void connectionLostInt();
  28476. void deliverDataInt (const MemoryBlock& data);
  28477. bool readNextMessageInt();
  28478. void run();
  28479. InterprocessConnection (const InterprocessConnection&);
  28480. const InterprocessConnection& operator= (const InterprocessConnection&);
  28481. };
  28482. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  28483. /********* End of inlined file: juce_InterprocessConnection.h *********/
  28484. #endif
  28485. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28486. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  28487. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28488. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28489. /**
  28490. An object that waits for client sockets to connect to a port on this host, and
  28491. creates InterprocessConnection objects for each one.
  28492. To use this, create a class derived from it which implements the createConnectionObject()
  28493. method, so that it creates suitable connection objects for each client that tries
  28494. to connect.
  28495. @see InterprocessConnection
  28496. */
  28497. class JUCE_API InterprocessConnectionServer : private Thread
  28498. {
  28499. public:
  28500. /** Creates an uninitialised server object.
  28501. */
  28502. InterprocessConnectionServer();
  28503. /** Destructor. */
  28504. ~InterprocessConnectionServer();
  28505. /** Starts an internal thread which listens on the given port number.
  28506. While this is running, in another process tries to connect with the
  28507. InterprocessConnection::connectToSocket() method, this object will call
  28508. createConnectionObject() to create a connection to that client.
  28509. Use stop() to stop the thread running.
  28510. @see createConnectionObject, stop
  28511. */
  28512. bool beginWaitingForSocket (const int portNumber);
  28513. /** Terminates the listener thread, if it's active.
  28514. @see beginWaitingForSocket
  28515. */
  28516. void stop();
  28517. protected:
  28518. /** Creates a suitable connection object for a client process that wants to
  28519. connect to this one.
  28520. This will be called by the listener thread when a client process tries
  28521. to connect, and must return a new InterprocessConnection object that will
  28522. then run as this end of the connection.
  28523. @see InterprocessConnection
  28524. */
  28525. virtual InterprocessConnection* createConnectionObject() = 0;
  28526. public:
  28527. juce_UseDebuggingNewOperator
  28528. private:
  28529. StreamingSocket* volatile socket;
  28530. void run();
  28531. InterprocessConnectionServer (const InterprocessConnectionServer&);
  28532. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  28533. };
  28534. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  28535. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  28536. #endif
  28537. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  28538. #endif
  28539. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  28540. #endif
  28541. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28542. /********* Start of inlined file: juce_MessageManager.h *********/
  28543. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28544. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28545. class Component;
  28546. class MessageManagerLock;
  28547. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  28548. */
  28549. typedef void* (MessageCallbackFunction) (void* userData);
  28550. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  28551. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  28552. */
  28553. class JUCE_API MessageManager
  28554. {
  28555. public:
  28556. /** Returns the global instance of the MessageManager. */
  28557. static MessageManager* getInstance() throw();
  28558. /** Runs the event dispatch loop until a stop message is posted.
  28559. This method is only intended to be run by the application's startup routine,
  28560. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  28561. @see stopDispatchLoop
  28562. */
  28563. void runDispatchLoop();
  28564. /** Sends a signal that the dispatch loop should terminate.
  28565. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  28566. will be interrupted and will return.
  28567. @see runDispatchLoop
  28568. */
  28569. void stopDispatchLoop();
  28570. /** Returns true if the stopDispatchLoop() method has been called.
  28571. */
  28572. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  28573. /** Synchronously dispatches messages until a given time has elapsed.
  28574. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  28575. otherwise returns true.
  28576. */
  28577. bool runDispatchLoopUntil (int millisecondsToRunFor);
  28578. /** Calls a function using the message-thread.
  28579. This can be used by any thread to cause this function to be called-back
  28580. by the message thread. If it's the message-thread that's calling this method,
  28581. then the function will just be called; if another thread is calling, a message
  28582. will be posted to the queue, and this method will block until that message
  28583. is delivered, the function is called, and the result is returned.
  28584. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  28585. thread has a critical section locked, which an unrelated message callback then tries to lock
  28586. before the message thread gets round to processing this callback.
  28587. @param callback the function to call - its signature must be @code
  28588. void* myCallbackFunction (void*) @endcode
  28589. @param userData a user-defined pointer that will be passed to the function that gets called
  28590. @returns the value that the callback function returns.
  28591. @see MessageManagerLock
  28592. */
  28593. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  28594. void* userData);
  28595. /** Returns true if the caller-thread is the message thread. */
  28596. bool isThisTheMessageThread() const throw();
  28597. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  28598. (Best to ignore this method unless you really know what you're doing..)
  28599. @see getCurrentMessageThread
  28600. */
  28601. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  28602. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  28603. (Best to ignore this method unless you really know what you're doing..)
  28604. @see setCurrentMessageThread
  28605. */
  28606. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  28607. /** Returns true if the caller thread has currenltly got the message manager locked.
  28608. see the MessageManagerLock class for more info about this.
  28609. This will be true if the caller is the message thread, because that automatically
  28610. gains a lock while a message is being dispatched.
  28611. */
  28612. bool currentThreadHasLockedMessageManager() const throw();
  28613. /** Sends a message to all other JUCE applications that are running.
  28614. @param messageText the string that will be passed to the actionListenerCallback()
  28615. method of the broadcast listeners in the other app.
  28616. @see registerBroadcastListener, ActionListener
  28617. */
  28618. static void broadcastMessage (const String& messageText) throw();
  28619. /** Registers a listener to get told about broadcast messages.
  28620. The actionListenerCallback() callback's string parameter
  28621. is the message passed into broadcastMessage().
  28622. @see broadcastMessage
  28623. */
  28624. void registerBroadcastListener (ActionListener* listener) throw();
  28625. /** Deregisters a broadcast listener. */
  28626. void deregisterBroadcastListener (ActionListener* listener) throw();
  28627. /** @internal */
  28628. void deliverMessage (void*);
  28629. /** @internal */
  28630. void deliverBroadcastMessage (const String&);
  28631. /** @internal */
  28632. ~MessageManager() throw();
  28633. juce_UseDebuggingNewOperator
  28634. private:
  28635. MessageManager() throw();
  28636. friend class MessageListener;
  28637. friend class ChangeBroadcaster;
  28638. friend class ActionBroadcaster;
  28639. friend class CallbackMessage;
  28640. static MessageManager* instance;
  28641. SortedSet<const MessageListener*> messageListeners;
  28642. ActionListenerList* broadcastListeners;
  28643. friend class JUCEApplication;
  28644. bool quitMessagePosted, quitMessageReceived;
  28645. Thread::ThreadID messageThreadId;
  28646. VoidArray modalComponents;
  28647. static void* exitModalLoopCallback (void*);
  28648. void postMessageToQueue (Message* const message);
  28649. void postCallbackMessage (Message* const message);
  28650. static void doPlatformSpecificInitialisation();
  28651. static void doPlatformSpecificShutdown();
  28652. friend class MessageManagerLock;
  28653. Thread::ThreadID volatile threadWithLock;
  28654. CriticalSection lockingLock;
  28655. MessageManager (const MessageManager&);
  28656. const MessageManager& operator= (const MessageManager&);
  28657. };
  28658. /** Used to make sure that the calling thread has exclusive access to the message loop.
  28659. Because it's not thread-safe to call any of the Component or other UI classes
  28660. from threads other than the message thread, one of these objects can be used to
  28661. lock the message loop and allow this to be done. The message thread will be
  28662. suspended for the lifetime of the MessageManagerLock object, so create one on
  28663. the stack like this: @code
  28664. void MyThread::run()
  28665. {
  28666. someData = 1234;
  28667. const MessageManagerLock mmLock;
  28668. // the event loop will now be locked so it's safe to make a few calls..
  28669. myComponent->setBounds (newBounds);
  28670. myComponent->repaint();
  28671. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  28672. }
  28673. @endcode
  28674. Obviously be careful not to create one of these and leave it lying around, or
  28675. your app will grind to a halt!
  28676. Another caveat is that using this in conjunction with other CriticalSections
  28677. can create lots of interesting ways of producing a deadlock! In particular, if
  28678. your message thread calls stopThread() for a thread that uses these locks,
  28679. you'll get an (occasional) deadlock..
  28680. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  28681. */
  28682. class JUCE_API MessageManagerLock
  28683. {
  28684. public:
  28685. /** Tries to acquire a lock on the message manager.
  28686. The constructor attempts to gain a lock on the message loop, and the lock will be
  28687. kept for the lifetime of this object.
  28688. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  28689. this method will keep checking whether the thread has been given the
  28690. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  28691. without gaining the lock. If you pass a thread, you must check whether the lock was
  28692. successful by calling lockWasGained(). If this is false, your thread is being told to
  28693. die, so you should take evasive action.
  28694. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  28695. careful when doing this, because it's very easy to deadlock if your message thread
  28696. attempts to call stopThread() on a thread just as that thread attempts to get the
  28697. message lock.
  28698. If the calling thread already has the lock, nothing will be done, so it's safe and
  28699. quick to use these locks recursively.
  28700. E.g.
  28701. @code
  28702. void run()
  28703. {
  28704. ...
  28705. while (! threadShouldExit())
  28706. {
  28707. MessageManagerLock mml (Thread::getCurrentThread());
  28708. if (! mml.lockWasGained())
  28709. return; // another thread is trying to kill us!
  28710. ..do some locked stuff here..
  28711. }
  28712. ..and now the MM is now unlocked..
  28713. }
  28714. @endcode
  28715. */
  28716. MessageManagerLock (Thread* const threadToCheckForExitSignal = 0) throw();
  28717. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  28718. instead of a thread.
  28719. See the MessageManagerLock (Thread*) constructor for details on how this works.
  28720. */
  28721. MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw();
  28722. /** Releases the current thread's lock on the message manager.
  28723. Make sure this object is created and deleted by the same thread,
  28724. otherwise there are no guarantees what will happen!
  28725. */
  28726. ~MessageManagerLock() throw();
  28727. /** Returns true if the lock was successfully acquired.
  28728. (See the constructor that takes a Thread for more info).
  28729. */
  28730. bool lockWasGained() const throw() { return locked; }
  28731. private:
  28732. bool locked, needsUnlocking;
  28733. void* sharedEvents;
  28734. void init (Thread* const thread, ThreadPoolJob* const job) throw();
  28735. };
  28736. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  28737. /********* End of inlined file: juce_MessageManager.h *********/
  28738. #endif
  28739. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28740. /********* Start of inlined file: juce_MultiTimer.h *********/
  28741. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  28742. #define __JUCE_MULTITIMER_JUCEHEADER__
  28743. /**
  28744. A type of timer class that can run multiple timers with different frequencies,
  28745. all of which share a single callback.
  28746. This class is very similar to the Timer class, but allows you run multiple
  28747. separate timers, where each one has a unique ID number. The methods in this
  28748. class are exactly equivalent to those in Timer, but with the addition of
  28749. this ID number.
  28750. To use it, you need to create a subclass of MultiTimer, implementing the
  28751. timerCallback() method. Then you can start timers with startTimer(), and
  28752. each time the callback is triggered, it passes in the ID of the timer that
  28753. caused it.
  28754. @see Timer
  28755. */
  28756. class JUCE_API MultiTimer
  28757. {
  28758. protected:
  28759. /** Creates a MultiTimer.
  28760. When created, no timers are running, so use startTimer() to start things off.
  28761. */
  28762. MultiTimer() throw();
  28763. /** Creates a copy of another timer.
  28764. Note that this timer will not contain any running timers, even if the one you're
  28765. copying from was running.
  28766. */
  28767. MultiTimer (const MultiTimer& other) throw();
  28768. public:
  28769. /** Destructor. */
  28770. virtual ~MultiTimer();
  28771. /** The user-defined callback routine that actually gets called by each of the
  28772. timers that are running.
  28773. It's perfectly ok to call startTimer() or stopTimer() from within this
  28774. callback to change the subsequent intervals.
  28775. */
  28776. virtual void timerCallback (const int timerId) = 0;
  28777. /** Starts a timer and sets the length of interval required.
  28778. If the timer is already started, this will reset it, so the
  28779. time between calling this method and the next timer callback
  28780. will not be less than the interval length passed in.
  28781. @param timerId a unique Id number that identifies the timer to
  28782. start. This is the id that will be passed back
  28783. to the timerCallback() method when this timer is
  28784. triggered
  28785. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  28786. rounded up to 1)
  28787. */
  28788. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  28789. /** Stops a timer.
  28790. If a timer has been started with the given ID number, it will be cancelled.
  28791. No more callbacks will be made for the specified timer after this method returns.
  28792. If this is called from a different thread, any callbacks that may
  28793. be currently executing may be allowed to finish before the method
  28794. returns.
  28795. */
  28796. void stopTimer (const int timerId) throw();
  28797. /** Checks whether a timer has been started for a specified ID.
  28798. @returns true if a timer with the given ID is running.
  28799. */
  28800. bool isTimerRunning (const int timerId) const throw();
  28801. /** Returns the interval for a specified timer ID.
  28802. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  28803. is running for the ID number specified.
  28804. */
  28805. int getTimerInterval (const int timerId) const throw();
  28806. private:
  28807. CriticalSection timerListLock;
  28808. VoidArray timers;
  28809. const MultiTimer& operator= (const MultiTimer&);
  28810. };
  28811. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  28812. /********* End of inlined file: juce_MultiTimer.h *********/
  28813. #endif
  28814. #ifndef __JUCE_TIMER_JUCEHEADER__
  28815. #endif
  28816. #ifndef __JUCE_BRUSH_JUCEHEADER__
  28817. #endif
  28818. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28819. /********* Start of inlined file: juce_GradientBrush.h *********/
  28820. #ifndef __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28821. #define __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28822. /********* Start of inlined file: juce_ColourGradient.h *********/
  28823. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  28824. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  28825. /**
  28826. Structure used to define a colour gradient for painting areas.
  28827. @see GradientBrush
  28828. */
  28829. class JUCE_API ColourGradient
  28830. {
  28831. public:
  28832. /** Creates a gradient object.
  28833. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  28834. colour2 should be. In between them there's a gradient.
  28835. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28836. its centre.
  28837. The alpha transparencies of the colours are used, so note that
  28838. if you blend from transparent to a solid colour, the RGB of the transparent
  28839. colour will become visible in parts of the gradient. e.g. blending
  28840. from Colour::transparentBlack to Colours::white will produce a
  28841. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  28842. will be white all the way across.
  28843. @see ColourGradient
  28844. */
  28845. ColourGradient (const Colour& colour1,
  28846. const float x1,
  28847. const float y1,
  28848. const Colour& colour2,
  28849. const float x2,
  28850. const float y2,
  28851. const bool isRadial) throw();
  28852. /** Creates an uninitialised gradient.
  28853. If you use this constructor instead of the other one, be sure to set all the
  28854. object's public member variables before using it!
  28855. */
  28856. ColourGradient() throw();
  28857. /** Destructor */
  28858. ~ColourGradient() throw();
  28859. /** Removes any colours that have been added.
  28860. This will also remove any start and end colours, so the gradient won't work. You'll
  28861. need to add more colours with addColour().
  28862. */
  28863. void clearColours() throw();
  28864. /** Adds a colour at a point along the length of the gradient.
  28865. This allows the gradient to go through a spectrum of colours, instead of just a
  28866. start and end colour.
  28867. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  28868. of the distance along the line between the two points
  28869. at which the colour should occur.
  28870. @param colour the colour that should be used at this point
  28871. */
  28872. void addColour (const double proportionAlongGradient,
  28873. const Colour& colour) throw();
  28874. /** Multiplies the alpha value of all the colours by the given scale factor */
  28875. void multiplyOpacity (const float multiplier) throw();
  28876. /** Returns the number of colour-stops that have been added. */
  28877. int getNumColours() const throw();
  28878. /** Returns the position along the length of the gradient of the colour with this index.
  28879. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28880. */
  28881. double getColourPosition (const int index) const throw();
  28882. /** Returns the colour that was added with a given index.
  28883. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  28884. */
  28885. const Colour getColour (const int index) const throw();
  28886. /** Creates a set of interpolated premultiplied ARGB values.
  28887. The caller must delete the array that is returned using juce_free().
  28888. */
  28889. PixelARGB* createLookupTable (int& numEntries) const throw();
  28890. /** Returns true if all colours are opaque. */
  28891. bool isOpaque() const throw();
  28892. /** Returns true if all colours are completely transparent. */
  28893. bool isInvisible() const throw();
  28894. float x1;
  28895. float y1;
  28896. float x2;
  28897. float y2;
  28898. /** If true, the gradient should be filled circularly, centred around
  28899. (x1, y1), with (x2, y2) defining a point on the circumference.
  28900. If false, the gradient is linear between the two points.
  28901. */
  28902. bool isRadial;
  28903. /** A transform to apply to the resultant gradient shape */
  28904. AffineTransform transform;
  28905. juce_UseDebuggingNewOperator
  28906. private:
  28907. Array <uint32> colours;
  28908. };
  28909. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  28910. /********* End of inlined file: juce_ColourGradient.h *********/
  28911. /**
  28912. A Brush that fills areas with a colour gradient.
  28913. The gradient can either be linear or circular.
  28914. @see Brush, Graphics::setBrush, SolidColourBrush, ImageBrush
  28915. */
  28916. class JUCE_API GradientBrush : public Brush
  28917. {
  28918. public:
  28919. /** Creates a gradient brush, ready for use in Graphics::setBrush().
  28920. (x1, y1) is the location relative to the origin of the Graphics context,
  28921. at which the colour should be colour1. Likewise for (x2, y2) and colour2.
  28922. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  28923. its centre.
  28924. The alpha transparencies of the colours are used, so the brush
  28925. need not be completely opaque. Note that this means that if you
  28926. blend from transparent to a solid colour, the RGB of the transparent
  28927. colour will become visible in parts of the gradient. e.g. blending
  28928. from Colour::transparentBlack to Colours::white will produce a
  28929. grey colour, but Colour::transparentWhite to Colours::white will be
  28930. white all the way across.
  28931. @see ColourGradient
  28932. */
  28933. GradientBrush (const Colour& colour1,
  28934. const float x1,
  28935. const float y1,
  28936. const Colour& colour2,
  28937. const float x2,
  28938. const float y2,
  28939. const bool isRadial) throw();
  28940. /** Creates a gradient brush from a ColourGradient object.
  28941. */
  28942. GradientBrush (const ColourGradient& gradient) throw();
  28943. /** Destructor. */
  28944. ~GradientBrush() throw();
  28945. /** Returns the current gradient information */
  28946. const ColourGradient& getGradient() const throw() { return gradient; }
  28947. Brush* createCopy() const throw();
  28948. void applyTransform (const AffineTransform& transform) throw();
  28949. void multiplyOpacity (const float multiple) throw();
  28950. bool isInvisible() const throw();
  28951. void paintPath (LowLevelGraphicsContext& context,
  28952. const Path& path, const AffineTransform& transform) throw();
  28953. void paintRectangle (LowLevelGraphicsContext& context,
  28954. int x, int y, int w, int h) throw();
  28955. void paintAlphaChannel (LowLevelGraphicsContext& context,
  28956. const Image& alphaChannelImage, int imageX, int imageY,
  28957. int x, int y, int w, int h) throw();
  28958. juce_UseDebuggingNewOperator
  28959. protected:
  28960. ColourGradient gradient;
  28961. private:
  28962. GradientBrush (const GradientBrush&);
  28963. const GradientBrush& operator= (const GradientBrush&);
  28964. };
  28965. #endif // __JUCE_GRADIENTBRUSH_JUCEHEADER__
  28966. /********* End of inlined file: juce_GradientBrush.h *********/
  28967. #endif
  28968. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28969. /********* Start of inlined file: juce_ImageBrush.h *********/
  28970. #ifndef __JUCE_IMAGEBRUSH_JUCEHEADER__
  28971. #define __JUCE_IMAGEBRUSH_JUCEHEADER__
  28972. /********* Start of inlined file: juce_Image.h *********/
  28973. #ifndef __JUCE_IMAGE_JUCEHEADER__
  28974. #define __JUCE_IMAGE_JUCEHEADER__
  28975. /**
  28976. Holds a fixed-size bitmap.
  28977. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  28978. To draw into an image, create a Graphics object for it.
  28979. e.g. @code
  28980. // create a transparent 500x500 image..
  28981. Image myImage (Image::RGB, 500, 500, true);
  28982. Graphics g (myImage);
  28983. g.setColour (Colours::red);
  28984. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  28985. @endcode
  28986. Other useful ways to create an image are with the ImageCache class, or the
  28987. ImageFileFormat, which provides a way to load common image files.
  28988. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  28989. */
  28990. class JUCE_API Image
  28991. {
  28992. public:
  28993. enum PixelFormat
  28994. {
  28995. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  28996. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  28997. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  28998. };
  28999. /** Creates an in-memory image with a specified size and format.
  29000. @param format the number of colour channels in the image
  29001. @param imageWidth the desired width of the image, in pixels - this value must be
  29002. greater than zero (otherwise a width of 1 will be used)
  29003. @param imageHeight the desired width of the image, in pixels - this value must be
  29004. greater than zero (otherwise a height of 1 will be used)
  29005. @param clearImage if true, the image will initially be cleared to black or transparent
  29006. black. If false, the image may contain random data, and the
  29007. user will have to deal with this
  29008. */
  29009. Image (const PixelFormat format,
  29010. const int imageWidth,
  29011. const int imageHeight,
  29012. const bool clearImage);
  29013. /** Creates a copy of another image.
  29014. @see createCopy
  29015. */
  29016. Image (const Image& other);
  29017. /** Destructor. */
  29018. virtual ~Image();
  29019. /** Returns the image's width (in pixels). */
  29020. int getWidth() const throw() { return imageWidth; }
  29021. /** Returns the image's height (in pixels). */
  29022. int getHeight() const throw() { return imageHeight; }
  29023. /** Returns the image's pixel format. */
  29024. PixelFormat getFormat() const throw() { return format; }
  29025. /** True if the image's format is ARGB. */
  29026. bool isARGB() const throw() { return format == ARGB; }
  29027. /** True if the image's format is RGB. */
  29028. bool isRGB() const throw() { return format == RGB; }
  29029. /** True if the image contains an alpha-channel. */
  29030. bool hasAlphaChannel() const throw() { return format != RGB; }
  29031. /** Clears a section of the image with a given colour.
  29032. This won't do any alpha-blending - it just sets all pixels in the image to
  29033. the given colour (which may be non-opaque if the image has an alpha channel).
  29034. */
  29035. virtual void clear (int x, int y, int w, int h,
  29036. const Colour& colourToClearTo = Colour (0x00000000));
  29037. /** Returns a new image that's a copy of this one.
  29038. A new size for the copied image can be specified, or values less than
  29039. zero can be passed-in to use the image's existing dimensions.
  29040. It's up to the caller to delete the image when no longer needed.
  29041. */
  29042. virtual Image* createCopy (int newWidth = -1,
  29043. int newHeight = -1,
  29044. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  29045. /** Returns the colour of one of the pixels in the image.
  29046. If the co-ordinates given are beyond the image's boundaries, this will
  29047. return Colours::transparentBlack.
  29048. (0, 0) is the image's top-left corner.
  29049. @see getAlphaAt, setPixelAt, blendPixelAt
  29050. */
  29051. virtual const Colour getPixelAt (const int x, const int y) const;
  29052. /** Sets the colour of one of the image's pixels.
  29053. If the co-ordinates are beyond the image's boundaries, then nothing will
  29054. happen.
  29055. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  29056. just replace the existing pixel with the given one. The colour's opacity
  29057. will be ignored if this image doesn't have an alpha-channel.
  29058. (0, 0) is the image's top-left corner.
  29059. @see blendPixelAt
  29060. */
  29061. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  29062. /** Changes the opacity of a pixel.
  29063. This only has an effect if the image has an alpha channel and if the
  29064. given co-ordinates are inside the image's boundary.
  29065. The multiplier must be in the range 0 to 1.0, and the current alpha
  29066. at the given co-ordinates will be multiplied by this value.
  29067. @see getAlphaAt, setPixelAt
  29068. */
  29069. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  29070. /** Changes the overall opacity of the image.
  29071. This will multiply the alpha value of each pixel in the image by the given
  29072. amount (limiting the resulting alpha values between 0 and 255). This allows
  29073. you to make an image more or less transparent.
  29074. If the image doesn't have an alpha channel, this won't have any effect.
  29075. */
  29076. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  29077. /** Changes all the colours to be shades of grey, based on their current luminosity.
  29078. */
  29079. virtual void desaturate();
  29080. /** Locks some of the pixels in the image so they can be read and written to.
  29081. This returns a pointer to some memory containing the pixels in the given
  29082. rectangle. It also returns values for the line and pixel stride used within
  29083. the data. The format of the pixel data is the same as that of this image.
  29084. When you've finished reading and changing the data, you must call
  29085. releasePixelDataReadWrite() to give the pixels back to the image.
  29086. For images that are stored in memory, this method may just return a direct
  29087. pointer to the image's data, but other types of image may be stored elsewhere,
  29088. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  29089. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  29090. If you only need read-access to the pixel data, use lockPixelDataReadOnly()
  29091. instead.
  29092. @see releasePixelDataReadWrite, lockPixelDataReadOnly
  29093. */
  29094. virtual uint8* lockPixelDataReadWrite (int x, int y, int w, int h, int& lineStride, int& pixelStride);
  29095. /** Releases a block of memory that was locked with lockPixelDataReadWrite().
  29096. */
  29097. virtual void releasePixelDataReadWrite (void* sourceData);
  29098. /** Locks some of the pixels in the image so they can be read.
  29099. This returns a pointer to some memory containing the pixels in the given
  29100. rectangle. It also returns values for the line and pixel stride used within
  29101. the data. The format of the pixel data is the same as that of this image.
  29102. When you've finished reading the data, you must call releasePixelDataReadOnly()
  29103. to let the image free the memory if necessary.
  29104. For images that are stored in memory, this method may just return a direct
  29105. pointer to the image's data, but other types of image may be stored elsewhere,
  29106. e.g. in video memory, and if so, this lockPixelDataReadWrite() and
  29107. releasePixelDataReadWrite() may need to create a temporary copy in main memory.
  29108. If you only need to read and write the pixel data, use lockPixelDataReadWrite()
  29109. instead.
  29110. @see releasePixelDataReadOnly, lockPixelDataReadWrite
  29111. */
  29112. virtual const uint8* lockPixelDataReadOnly (int x, int y, int w, int h, int& lineStride, int& pixelStride) const;
  29113. /** Releases a block of memory that was locked with lockPixelDataReadOnly().
  29114. */
  29115. virtual void releasePixelDataReadOnly (const void* sourceData) const;
  29116. /** Copies some pixel values to a rectangle of the image.
  29117. The format of the pixel data must match that of the image itself, and the
  29118. rectangle supplied must be within the image's bounds.
  29119. */
  29120. virtual void setPixelData (int destX, int destY, int destW, int destH,
  29121. const uint8* sourcePixelData, int sourceLineStride);
  29122. /** Copies a section of the image to somewhere else within itself.
  29123. */
  29124. virtual void moveImageSection (int destX, int destY,
  29125. int sourceX, int sourceY,
  29126. int width, int height);
  29127. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  29128. of the image.
  29129. @param result the list that will have the area added to it
  29130. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  29131. above this level will be considered opaque
  29132. */
  29133. void createSolidAreaMask (RectangleList& result,
  29134. const float alphaThreshold = 0.5f) const;
  29135. juce_UseDebuggingNewOperator
  29136. /** Creates a context suitable for drawing onto this image.
  29137. Don't call this method directly! It's used internally by the Graphics class.
  29138. */
  29139. virtual LowLevelGraphicsContext* createLowLevelContext();
  29140. protected:
  29141. const PixelFormat format;
  29142. const int imageWidth, imageHeight;
  29143. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  29144. Image (const PixelFormat format,
  29145. const int imageWidth,
  29146. const int imageHeight);
  29147. int pixelStride, lineStride;
  29148. uint8* imageData;
  29149. private:
  29150. const Image& operator= (const Image&);
  29151. };
  29152. #endif // __JUCE_IMAGE_JUCEHEADER__
  29153. /********* End of inlined file: juce_Image.h *********/
  29154. /**
  29155. A Brush that fills areas with tiled repetitions of an image.
  29156. @see Brush, Graphics::setBrush, SolidColourBrush, GradientBrush
  29157. */
  29158. class JUCE_API ImageBrush : public Brush
  29159. {
  29160. public:
  29161. /* Creates an image brush, ready for use in Graphics::setBrush().
  29162. (x, y) is an anchor point for the top-left of the image
  29163. A reference to the image passed in will be kept, so don't delete
  29164. it within the lifetime of this object
  29165. */
  29166. ImageBrush (Image* const image,
  29167. const int anchorX,
  29168. const int anchorY,
  29169. const float opacity) throw();
  29170. /** Destructor. */
  29171. ~ImageBrush() throw();
  29172. /** Returns the image currently being used. */
  29173. Image* getImage() const throw() { return image; }
  29174. /** Returns the current anchor X position. */
  29175. int getAnchorX() const throw() { return anchorX; }
  29176. /** Returns the current anchor Y position. */
  29177. int getAnchorY() const throw() { return anchorY; }
  29178. /** Returns the current opacity. */
  29179. float getOpacity() const throw() { return opacity; }
  29180. Brush* createCopy() const throw();
  29181. void applyTransform (const AffineTransform& transform) throw();
  29182. void multiplyOpacity (const float multiple) throw();
  29183. bool isInvisible() const throw();
  29184. void paintPath (LowLevelGraphicsContext& context,
  29185. const Path& path, const AffineTransform& transform) throw();
  29186. void paintRectangle (LowLevelGraphicsContext& context,
  29187. int x, int y, int w, int h) throw();
  29188. void paintAlphaChannel (LowLevelGraphicsContext& context,
  29189. const Image& alphaChannelImage, int imageX, int imageY,
  29190. int x, int y, int w, int h) throw();
  29191. juce_UseDebuggingNewOperator
  29192. protected:
  29193. Image* image;
  29194. int anchorX, anchorY;
  29195. float opacity;
  29196. private:
  29197. ImageBrush (const ImageBrush&);
  29198. const ImageBrush& operator= (const ImageBrush&);
  29199. void getStartXY (int& x, int& y) const throw();
  29200. };
  29201. #endif // __JUCE_IMAGEBRUSH_JUCEHEADER__
  29202. /********* End of inlined file: juce_ImageBrush.h *********/
  29203. #endif
  29204. #ifndef __JUCE_SOLIDCOLOURBRUSH_JUCEHEADER__
  29205. #endif
  29206. #ifndef __JUCE_COLOUR_JUCEHEADER__
  29207. #endif
  29208. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  29209. #endif
  29210. #ifndef __JUCE_COLOURS_JUCEHEADER__
  29211. #endif
  29212. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  29213. #endif
  29214. #ifndef __JUCE_FONT_JUCEHEADER__
  29215. #endif
  29216. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29217. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  29218. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29219. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29220. /**
  29221. An glyph from a particular font, with a particular size, style,
  29222. typeface and position.
  29223. @see GlyphArrangement, Font
  29224. */
  29225. class JUCE_API PositionedGlyph
  29226. {
  29227. public:
  29228. /** Returns the character the glyph represents. */
  29229. juce_wchar getCharacter() const throw() { return glyphInfo->getCharacter(); }
  29230. /** Checks whether the glyph is actually empty. */
  29231. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (glyphInfo->getCharacter()); }
  29232. /** Returns the position of the glyph's left-hand edge. */
  29233. float getLeft() const throw() { return x; }
  29234. /** Returns the position of the glyph's right-hand edge. */
  29235. float getRight() const throw() { return x + w; }
  29236. /** Returns the y position of the glyph's baseline. */
  29237. float getBaselineY() const throw() { return y; }
  29238. /** Returns the y position of the top of the glyph. */
  29239. float getTop() const throw() { return y - fontAscent; }
  29240. /** Returns the y position of the bottom of the glyph. */
  29241. float getBottom() const throw() { return y + fontHeight - fontAscent; }
  29242. /** Shifts the glyph's position by a relative amount. */
  29243. void moveBy (const float deltaX,
  29244. const float deltaY) throw();
  29245. /** Draws the glyph into a graphics context. */
  29246. void draw (const Graphics& g) const throw();
  29247. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  29248. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29249. /** Returns the path for this glyph.
  29250. @param path the glyph's outline will be appended to this path
  29251. */
  29252. void createPath (Path& path) const throw();
  29253. /** Checks to see if a point lies within this glyph. */
  29254. bool hitTest (float x, float y) const throw();
  29255. juce_UseDebuggingNewOperator
  29256. private:
  29257. friend class GlyphArrangement;
  29258. float x, y, w;
  29259. float fontHeight, fontAscent, fontHorizontalScale;
  29260. bool isUnderlined;
  29261. const TypefaceGlyphInfo* glyphInfo;
  29262. PositionedGlyph() throw();
  29263. };
  29264. /**
  29265. A set of glyphs, each with a position.
  29266. You can create a GlyphArrangement, text to it and then draw it onto a
  29267. graphics context. It's used internally by the text methods in the
  29268. Graphics class, but can be used directly if more control is needed.
  29269. @see Font, PositionedGlyph
  29270. */
  29271. class JUCE_API GlyphArrangement
  29272. {
  29273. public:
  29274. /** Creates an empty arrangement. */
  29275. GlyphArrangement() throw();
  29276. /** Takes a copy of another arrangement. */
  29277. GlyphArrangement (const GlyphArrangement& other) throw();
  29278. /** Copies another arrangement onto this one.
  29279. To add another arrangement without clearing this one, use addGlyphArrangement().
  29280. */
  29281. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  29282. /** Destructor. */
  29283. ~GlyphArrangement() throw();
  29284. /** Returns the total number of glyphs in the arrangement. */
  29285. int getNumGlyphs() const throw() { return numGlyphs; }
  29286. /** Returns one of the glyphs from the arrangement.
  29287. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  29288. careful not to pass an out-of-range index here, as it
  29289. doesn't do any bounds-checking.
  29290. */
  29291. PositionedGlyph& getGlyph (const int index) const throw();
  29292. /** Clears all text from the arrangement and resets it.
  29293. */
  29294. void clear() throw();
  29295. /** Appends a line of text to the arrangement.
  29296. This will add the text as a single line, where x is the left-hand edge of the
  29297. first character, and y is the position for the text's baseline.
  29298. If the text contains new-lines or carriage-returns, this will ignore them - use
  29299. addJustifiedText() to add multi-line arrangements.
  29300. */
  29301. void addLineOfText (const Font& font,
  29302. const String& text,
  29303. const float x,
  29304. const float y) throw();
  29305. /** Adds a line of text, truncating it if it's wider than a specified size.
  29306. This is the same as addLineOfText(), but if the line's width exceeds the value
  29307. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  29308. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  29309. */
  29310. void addCurtailedLineOfText (const Font& font,
  29311. const String& text,
  29312. float x,
  29313. const float y,
  29314. const float maxWidthPixels,
  29315. const bool useEllipsis) throw();
  29316. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  29317. This will add text to the arrangement, breaking it into new lines either where there
  29318. is a new-line or carriage-return character in the text, or where a line's width
  29319. exceeds the value set in maxLineWidth.
  29320. Each line that is added will be laid out using the flags set in horizontalLayout, so
  29321. the lines can be left- or right-justified, or centred horizontally in the space
  29322. between x and (x + maxLineWidth).
  29323. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  29324. lines will be placed below it, separated by a distance of font.getHeight().
  29325. */
  29326. void addJustifiedText (const Font& font,
  29327. const String& text,
  29328. float x, float y,
  29329. const float maxLineWidth,
  29330. const Justification& horizontalLayout) throw();
  29331. /** Tries to fit some text withing a given space.
  29332. This does its best to make the given text readable within the specified rectangle,
  29333. so it useful for labelling things.
  29334. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  29335. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  29336. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  29337. it's been truncated.
  29338. A Justification parameter lets you specify how the text is laid out within the rectangle,
  29339. both horizontally and vertically.
  29340. @see Graphics::drawFittedText
  29341. */
  29342. void addFittedText (const Font& font,
  29343. const String& text,
  29344. float x, float y,
  29345. float width, float height,
  29346. const Justification& layout,
  29347. int maximumLinesToUse,
  29348. const float minimumHorizontalScale = 0.7f) throw();
  29349. /** Appends another glyph arrangement to this one. */
  29350. void addGlyphArrangement (const GlyphArrangement& other) throw();
  29351. /** Draws this glyph arrangement to a graphics context.
  29352. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  29353. method, which renders the glyphs as filled vectors.
  29354. */
  29355. void draw (const Graphics& g) const throw();
  29356. /** Draws this glyph arrangement to a graphics context.
  29357. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  29358. method for non-transformed arrangements.
  29359. */
  29360. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  29361. /** Converts the set of glyphs into a path.
  29362. @param path the glyphs' outlines will be appended to this path
  29363. */
  29364. void createPath (Path& path) const throw();
  29365. /** Looks for a glyph that contains the given co-ordinate.
  29366. @returns the index of the glyph, or -1 if none were found.
  29367. */
  29368. int findGlyphIndexAt (float x, float y) const throw();
  29369. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  29370. @param startIndex the first glyph to test
  29371. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  29372. startIndex will be included
  29373. @param left on return, the leftmost co-ordinate of the rectangle
  29374. @param top on return, the top co-ordinate of the rectangle
  29375. @param right on return, the rightmost co-ordinate of the rectangle
  29376. @param bottom on return, the bottom co-ordinate of the rectangle
  29377. @param includeWhitespace if true, the extent of any whitespace characters will also
  29378. be taken into account
  29379. */
  29380. void getBoundingBox (int startIndex,
  29381. int numGlyphs,
  29382. float& left,
  29383. float& top,
  29384. float& right,
  29385. float& bottom,
  29386. const bool includeWhitespace) const throw();
  29387. /** Shifts a set of glyphs by a given amount.
  29388. @param startIndex the first glyph to transform
  29389. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  29390. startIndex will be used
  29391. @param deltaX the amount to add to their x-positions
  29392. @param deltaY the amount to add to their y-positions
  29393. */
  29394. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  29395. const float deltaX,
  29396. const float deltaY) throw();
  29397. /** Removes a set of glyphs from the arrangement.
  29398. @param startIndex the first glyph to remove
  29399. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  29400. startIndex will be deleted
  29401. */
  29402. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  29403. /** Expands or compresses a set of glyphs horizontally.
  29404. @param startIndex the first glyph to transform
  29405. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  29406. startIndex will be used
  29407. @param horizontalScaleFactor how much to scale their horizontal width by
  29408. */
  29409. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  29410. const float horizontalScaleFactor) throw();
  29411. /** Justifies a set of glyphs within a given space.
  29412. This moves the glyphs as a block so that the whole thing is located within the
  29413. given rectangle with the specified layout.
  29414. If the Justification::horizontallyJustified flag is specified, each line will
  29415. be stretched out to fill the specified width.
  29416. */
  29417. void justifyGlyphs (const int startIndex, const int numGlyphs,
  29418. const float x,
  29419. const float y,
  29420. const float width,
  29421. const float height,
  29422. const Justification& justification) throw();
  29423. juce_UseDebuggingNewOperator
  29424. private:
  29425. int numGlyphs, numAllocated;
  29426. PositionedGlyph* glyphs;
  29427. void ensureNumGlyphsAllocated (int minGlyphs) throw();
  29428. void removeLast() throw();
  29429. void appendEllipsis (const Font& font, const float maxXPixels) throw();
  29430. void incGlyphRefCount (const int index) const throw();
  29431. void decGlyphRefCount (const int index) const throw();
  29432. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  29433. };
  29434. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  29435. /********* End of inlined file: juce_GlyphArrangement.h *********/
  29436. #endif
  29437. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29438. /********* Start of inlined file: juce_TextLayout.h *********/
  29439. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  29440. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  29441. class Graphics;
  29442. /**
  29443. A laid-out arrangement of text.
  29444. You can add text in different fonts to a TextLayout object, then call its
  29445. layout() method to word-wrap it into lines. The layout can then be drawn
  29446. using a graphics context.
  29447. It's handy if you've got a message to display, because you can format it,
  29448. measure the extent of the layout, and then create a suitably-sized window
  29449. to show it in.
  29450. @see Font, Graphics::drawFittedText, GlyphArrangement
  29451. */
  29452. class JUCE_API TextLayout
  29453. {
  29454. public:
  29455. /** Creates an empty text layout.
  29456. Text can then be appended using the appendText() method.
  29457. */
  29458. TextLayout() throw();
  29459. /** Creates a copy of another layout object. */
  29460. TextLayout (const TextLayout& other) throw();
  29461. /** Creates a text layout from an initial string and font. */
  29462. TextLayout (const String& text, const Font& font) throw();
  29463. /** Destructor. */
  29464. ~TextLayout() throw();
  29465. /** Copies another layout onto this one. */
  29466. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  29467. /** Clears the layout, removing all its text. */
  29468. void clear() throw();
  29469. /** Adds a string to the end of the arrangement.
  29470. The string will be broken onto new lines wherever it contains
  29471. carriage-returns or linefeeds. After adding it, you can call layout()
  29472. to wrap long lines into a paragraph and justify it.
  29473. */
  29474. void appendText (const String& textToAppend,
  29475. const Font& fontToUse) throw();
  29476. /** Replaces all the text with a new string.
  29477. This is equivalent to calling clear() followed by appendText().
  29478. */
  29479. void setText (const String& newText,
  29480. const Font& fontToUse) throw();
  29481. /** Breaks the text up to form a paragraph with the given width.
  29482. @param maximumWidth any text wider than this will be split
  29483. across multiple lines
  29484. @param justification how the lines are to be laid-out horizontally
  29485. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  29486. width that keeps all the lines of text at a
  29487. similar length - this is good when you're displaying
  29488. a short message and don't want it to get split
  29489. onto two lines with only a couple of words on
  29490. the second line, which looks untidy.
  29491. */
  29492. void layout (int maximumWidth,
  29493. const Justification& justification,
  29494. const bool attemptToBalanceLineLengths) throw();
  29495. /** Returns the overall width of the entire text layout. */
  29496. int getWidth() const throw();
  29497. /** Returns the overall height of the entire text layout. */
  29498. int getHeight() const throw();
  29499. /** Returns the total number of lines of text. */
  29500. int getNumLines() const throw() { return totalLines; }
  29501. /** Returns the width of a particular line of text.
  29502. @param lineNumber the line, from 0 to (getNumLines() - 1)
  29503. */
  29504. int getLineWidth (const int lineNumber) const throw();
  29505. /** Renders the text at a specified position using a graphics context.
  29506. */
  29507. void draw (Graphics& g,
  29508. const int topLeftX,
  29509. const int topLeftY) const throw();
  29510. /** Renders the text within a specified rectangle using a graphics context.
  29511. The justification flags dictate how the block of text should be positioned
  29512. within the rectangle.
  29513. */
  29514. void drawWithin (Graphics& g,
  29515. int x, int y, int w, int h,
  29516. const Justification& layoutFlags) const throw();
  29517. juce_UseDebuggingNewOperator
  29518. private:
  29519. VoidArray tokens;
  29520. int totalLines;
  29521. };
  29522. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  29523. /********* End of inlined file: juce_TextLayout.h *********/
  29524. #endif
  29525. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  29526. #endif
  29527. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29528. /********* Start of inlined file: juce_EdgeTable.h *********/
  29529. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  29530. #define __JUCE_EDGETABLE_JUCEHEADER__
  29531. class Path;
  29532. static const int juce_edgeTableDefaultEdgesPerLine = 10;
  29533. /**
  29534. A table of horizontal scan-line segments - used for rasterising Paths.
  29535. @see Path, Graphics
  29536. */
  29537. class JUCE_API EdgeTable
  29538. {
  29539. public:
  29540. /** Indicates the quality at which the edge table should be generated.
  29541. Higher values will have better quality anti-aliasing, but will take
  29542. longer to generate the edge table and to render it.
  29543. */
  29544. enum OversamplingLevel
  29545. {
  29546. Oversampling_none = 0, /**< No vertical anti-aliasing at all. */
  29547. Oversampling_4times = 2, /**< Anti-aliased with 4 levels of grey - good enough for normal use. */
  29548. Oversampling_16times = 4, /**< Anti-aliased with 16 levels of grey - very good quality. */
  29549. Oversampling_32times = 5, /**< Anti-aliased with 32 levels of grey - very good quality but slower. */
  29550. Oversampling_256times = 8 /**< Anti-aliased with 256 levels of grey - best quality, but too slow for
  29551. normal user-interface use. */
  29552. };
  29553. /** Creates an empty edge table ready to have paths added.
  29554. A table is created with a fixed vertical size, and only sections of paths
  29555. which lie within their range will be added to the table.
  29556. @param topY the lowest y co-ordinate that the table can contain
  29557. @param height the number of horizontal lines it can contain
  29558. @param verticalOversampling the amount of oversampling used for anti-aliasing
  29559. @param expectedEdgesPerLine used to optimise the table's internal data usage - it's not
  29560. worth changing this except for very special purposes
  29561. */
  29562. EdgeTable (const int topY,
  29563. const int height,
  29564. const OversamplingLevel verticalOversampling = Oversampling_4times,
  29565. const int expectedEdgesPerLine = juce_edgeTableDefaultEdgesPerLine) throw();
  29566. /** Creates a copy of another edge table. */
  29567. EdgeTable (const EdgeTable& other) throw();
  29568. /** Copies from another edge table. */
  29569. const EdgeTable& operator= (const EdgeTable& other) throw();
  29570. /** Destructor. */
  29571. ~EdgeTable() throw();
  29572. /** Adds edges to the table for a path.
  29573. This will add horizontal lines to the edge table for any parts of the path
  29574. which lie within the vertical bounds for which this table was created.
  29575. @param path the path to add
  29576. @param transform an optional transform to apply to the path while it's
  29577. being added
  29578. */
  29579. void addPath (const Path& path,
  29580. const AffineTransform& transform) throw();
  29581. /** Reduces the amount of space the table has allocated.
  29582. This will shrink the table down to use as little memory as possible - useful for
  29583. read-only tables that get stored and re-used for rendering.
  29584. */
  29585. void optimiseTable() throw();
  29586. /** Iterates the lines in the table, for rendering.
  29587. This function will iterate each line in the table, and call a user-defined class
  29588. to render each pixel or continuous line of pixels that the table contains.
  29589. @param iterationCallback this templated class must contain the following methods:
  29590. @code
  29591. inline void setEdgeTableYPos (int y);
  29592. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  29593. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  29594. @endcode
  29595. (these don't necessarily have to be 'const', but it might help it go faster)
  29596. @param clipLeft the left-hand edge of the rectangle which should be iterated
  29597. @param clipTop the top edge of the rectangle which should be iterated
  29598. @param clipRight the right-hand edge of the rectangle which should be iterated
  29599. @param clipBottom the bottom edge of the rectangle which should be iterated
  29600. @param subPixelXOffset a fraction of 1 pixel by which to shift the table rightwards, in the range 0 to 255
  29601. */
  29602. template <class EdgeTableIterationCallback>
  29603. void iterate (EdgeTableIterationCallback& iterationCallback,
  29604. const int clipLeft,
  29605. int clipTop,
  29606. const int clipRight,
  29607. int clipBottom,
  29608. const int subPixelXOffset) const
  29609. {
  29610. if (clipTop < top)
  29611. clipTop = top;
  29612. if (clipBottom > top + height)
  29613. clipBottom = top + height;
  29614. const int* singleLine = table + lineStrideElements
  29615. * ((clipTop - top) << (int) oversampling);
  29616. int mergedLineAllocation = 128;
  29617. MemoryBlock temp (mergedLineAllocation * (2 * sizeof (int)));
  29618. int* mergedLine = (int*) temp.getData();
  29619. const int timesOverSampling = 1 << (int) oversampling;
  29620. for (int y = clipTop; y < clipBottom; ++y)
  29621. {
  29622. int numMergedPoints = 0;
  29623. // sort all the oversampled lines into a single merged line ready to draw..
  29624. for (int over = timesOverSampling; --over >= 0;)
  29625. {
  29626. const int* l = singleLine;
  29627. singleLine += lineStrideElements;
  29628. int num = *l;
  29629. jassert (num >= 0);
  29630. if (num > 0)
  29631. {
  29632. if (numMergedPoints + num >= mergedLineAllocation)
  29633. {
  29634. mergedLineAllocation = (numMergedPoints + num + 0x100) & ~0xff;
  29635. temp.setSize (mergedLineAllocation * (2 * sizeof (int)), false);
  29636. mergedLine = (int*) temp.getData();
  29637. }
  29638. while (--num >= 0)
  29639. {
  29640. const int x = *++l;
  29641. const int winding = *++l;
  29642. int n = numMergedPoints << 1;
  29643. while (n > 0)
  29644. {
  29645. const int cx = mergedLine [n - 2];
  29646. if (cx <= x)
  29647. break;
  29648. mergedLine [n] = cx;
  29649. --n;
  29650. mergedLine [n + 2] = mergedLine [n];
  29651. --n;
  29652. }
  29653. mergedLine [n] = x;
  29654. mergedLine [n + 1] = winding;
  29655. ++numMergedPoints;
  29656. }
  29657. }
  29658. }
  29659. if (--numMergedPoints > 0)
  29660. {
  29661. const int* line = mergedLine;
  29662. int x = subPixelXOffset + *line;
  29663. int level = *++line;
  29664. int levelAccumulator = 0;
  29665. iterationCallback.setEdgeTableYPos (y);
  29666. while (--numMergedPoints >= 0)
  29667. {
  29668. const int endX = subPixelXOffset + *++line;
  29669. jassert (endX >= x);
  29670. const int absLevel = abs (level);
  29671. int endOfRun = (endX >> 8);
  29672. if (endOfRun == (x >> 8))
  29673. {
  29674. // small segment within the same pixel, so just save it for the next
  29675. // time round..
  29676. levelAccumulator += (endX - x) * absLevel;
  29677. }
  29678. else
  29679. {
  29680. // plot the fist pixel of this segment, including any accumulated
  29681. // levels from smaller segments that haven't been drawn yet
  29682. levelAccumulator += (0xff - (x & 0xff)) * absLevel;
  29683. levelAccumulator >>= 8;
  29684. if (levelAccumulator > 0xff)
  29685. levelAccumulator = 0xff;
  29686. x >>= 8;
  29687. if (x >= clipRight)
  29688. {
  29689. levelAccumulator = 0;
  29690. break;
  29691. }
  29692. if (x >= clipLeft && x < clipRight && levelAccumulator > 0)
  29693. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29694. if (++x >= clipRight)
  29695. {
  29696. levelAccumulator = 0;
  29697. break;
  29698. }
  29699. // if there's a segment of solid pixels, do it all in one go..
  29700. if (absLevel > 0 && endOfRun > x)
  29701. {
  29702. if (x < clipLeft)
  29703. x = clipLeft;
  29704. if (endOfRun > clipRight)
  29705. endOfRun = clipRight;
  29706. const int numPix = endOfRun - x;
  29707. if (numPix > 0)
  29708. iterationCallback.handleEdgeTableLine (x, numPix,
  29709. jmin (absLevel, 0xff));
  29710. }
  29711. // save the bit at the end to be drawn next time round the loop.
  29712. levelAccumulator = (endX & 0xff) * absLevel;
  29713. }
  29714. level += *++line;
  29715. x = endX;
  29716. }
  29717. if (levelAccumulator > 0)
  29718. {
  29719. levelAccumulator >>= 8;
  29720. if (levelAccumulator > 0xff)
  29721. levelAccumulator = 0xff;
  29722. x >>= 8;
  29723. if (x >= clipLeft && x < clipRight)
  29724. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  29725. }
  29726. }
  29727. }
  29728. }
  29729. juce_UseDebuggingNewOperator
  29730. private:
  29731. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  29732. int* table;
  29733. int top, height, maxEdgesPerLine, lineStrideElements;
  29734. OversamplingLevel oversampling;
  29735. // this will assume that the y co-ord is within bounds, and will avoid checking
  29736. // this for speed.
  29737. void addEdgePoint (const int x, const int y, const int winding) throw();
  29738. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  29739. };
  29740. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  29741. /********* End of inlined file: juce_EdgeTable.h *********/
  29742. #endif
  29743. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  29744. #endif
  29745. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  29746. #endif
  29747. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29748. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  29749. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29750. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29751. /**
  29752. Interface class for graphics context objects, used internally by the Graphics class.
  29753. Users are not supposed to create instances of this class directly - do your drawing
  29754. via the Graphics object instead.
  29755. It's a base class for different types of graphics context, that may perform software-based
  29756. or OS-accelerated rendering.
  29757. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  29758. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  29759. context.
  29760. */
  29761. class JUCE_API LowLevelGraphicsContext
  29762. {
  29763. protected:
  29764. LowLevelGraphicsContext();
  29765. public:
  29766. virtual ~LowLevelGraphicsContext();
  29767. /** Returns true if this device is vector-based, e.g. a printer. */
  29768. virtual bool isVectorDevice() const = 0;
  29769. /** Moves the origin to a new position.
  29770. The co-ords are relative to the current origin, and indicate the new position
  29771. of (0, 0).
  29772. */
  29773. virtual void setOrigin (int x, int y) = 0;
  29774. /** Cliping co-ords are relative to the origin. */
  29775. virtual bool reduceClipRegion (int x, int y, int w, int h) = 0;
  29776. /** Cliping co-ords are relative to the origin. */
  29777. virtual bool reduceClipRegion (const RectangleList& clipRegion) = 0;
  29778. /** Cliping co-ords are relative to the origin. */
  29779. virtual void excludeClipRegion (int x, int y, int w, int h) = 0;
  29780. virtual void saveState() = 0;
  29781. virtual void restoreState() = 0;
  29782. virtual bool clipRegionIntersects (int x, int y, int w, int h) = 0;
  29783. virtual const Rectangle getClipBounds() const = 0;
  29784. virtual bool isClipEmpty() const = 0;
  29785. virtual void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents) = 0;
  29786. virtual void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient) = 0;
  29787. virtual void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality) = 0;
  29788. virtual void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality) = 0;
  29789. virtual void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29790. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality) = 0;
  29791. virtual void fillAlphaChannelWithColour (const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour) = 0;
  29792. virtual void fillAlphaChannelWithGradient (const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient) = 0;
  29793. virtual void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29794. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha) = 0;
  29795. virtual void blendImage (const Image& sourceImage,
  29796. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29797. float alpha) = 0;
  29798. virtual void blendImageRescaling (const Image& sourceImage,
  29799. int destX, int destY, int destW, int destH,
  29800. int sourceX, int sourceY, int sourceW, int sourceH,
  29801. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29802. virtual void blendImageWarping (const Image& sourceImage,
  29803. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29804. const AffineTransform& transform,
  29805. float alpha, const Graphics::ResamplingQuality quality) = 0;
  29806. virtual void drawLine (double x1, double y1, double x2, double y2, const Colour& colour) = 0;
  29807. virtual void drawVerticalLine (const int x, double top, double bottom, const Colour& col) = 0;
  29808. virtual void drawHorizontalLine (const int y, double left, double right, const Colour& col) = 0;
  29809. };
  29810. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  29811. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  29812. #endif
  29813. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29814. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29815. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29816. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29817. /**
  29818. An implementation of LowLevelGraphicsContext that turns the drawing operations
  29819. into a PostScript document.
  29820. */
  29821. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  29822. {
  29823. public:
  29824. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  29825. const String& documentTitle,
  29826. const int totalWidth,
  29827. const int totalHeight);
  29828. ~LowLevelGraphicsPostScriptRenderer();
  29829. bool isVectorDevice() const;
  29830. void setOrigin (int x, int y);
  29831. bool reduceClipRegion (int x, int y, int w, int h);
  29832. bool reduceClipRegion (const RectangleList& clipRegion);
  29833. void excludeClipRegion (int x, int y, int w, int h);
  29834. void saveState();
  29835. void restoreState();
  29836. bool clipRegionIntersects (int x, int y, int w, int h);
  29837. const Rectangle getClipBounds() const;
  29838. bool isClipEmpty() const;
  29839. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29840. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29841. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29842. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29843. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29844. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29845. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29846. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29847. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29848. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29849. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29850. int sourceX, int sourceY, float alpha);
  29851. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29852. int sourceX, int sourceY, int sourceW, int sourceH,
  29853. float alpha, const Graphics::ResamplingQuality quality);
  29854. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29855. const AffineTransform& transform,
  29856. float alpha, const Graphics::ResamplingQuality quality);
  29857. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29858. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29859. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29860. juce_UseDebuggingNewOperator
  29861. protected:
  29862. OutputStream& out;
  29863. RectangleList* clip;
  29864. int totalWidth, totalHeight, xOffset, yOffset;
  29865. bool needToClip;
  29866. Colour lastColour;
  29867. struct SavedState
  29868. {
  29869. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29870. ~SavedState();
  29871. RectangleList* clip;
  29872. const int xOffset, yOffset;
  29873. private:
  29874. SavedState (const SavedState&);
  29875. const SavedState& operator= (const SavedState&);
  29876. };
  29877. OwnedArray <SavedState> stateStack;
  29878. void writeClip();
  29879. void writeColour (const Colour& colour);
  29880. void writePath (const Path& path) const;
  29881. void writeXY (const float x, const float y) const;
  29882. void writeTransform (const AffineTransform& trans) const;
  29883. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  29884. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  29885. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  29886. };
  29887. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  29888. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  29889. #endif
  29890. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29891. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29892. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29893. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29894. /**
  29895. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  29896. its rendering in memory.
  29897. User code is not supposed to create instances of this class directly - do all your
  29898. rendering via the Graphics class instead.
  29899. */
  29900. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  29901. {
  29902. public:
  29903. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  29904. ~LowLevelGraphicsSoftwareRenderer();
  29905. bool isVectorDevice() const;
  29906. void setOrigin (int x, int y);
  29907. bool reduceClipRegion (int x, int y, int w, int h);
  29908. bool reduceClipRegion (const RectangleList& clipRegion);
  29909. void excludeClipRegion (int x, int y, int w, int h);
  29910. void saveState();
  29911. void restoreState();
  29912. bool clipRegionIntersects (int x, int y, int w, int h);
  29913. const Rectangle getClipBounds() const;
  29914. bool isClipEmpty() const;
  29915. void fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29916. void fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient);
  29917. void fillPathWithColour (const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29918. void fillPathWithGradient (const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29919. void fillPathWithImage (const Path& path, const AffineTransform& transform,
  29920. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29921. void fillAlphaChannelWithColour (const Image& alphaImage, int imageX, int imageY, const Colour& colour);
  29922. void fillAlphaChannelWithGradient (const Image& alphaImage, int imageX, int imageY, const ColourGradient& gradient);
  29923. void fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  29924. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29925. void blendImage (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29926. int sourceX, int sourceY, float alpha);
  29927. void blendImageRescaling (const Image& sourceImage, int destX, int destY, int destW, int destH,
  29928. int sourceX, int sourceY, int sourceW, int sourceH,
  29929. float alpha, const Graphics::ResamplingQuality quality);
  29930. void blendImageWarping (const Image& sourceImage, int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29931. const AffineTransform& transform,
  29932. float alpha, const Graphics::ResamplingQuality quality);
  29933. void drawLine (double x1, double y1, double x2, double y2, const Colour& colour);
  29934. void drawVerticalLine (const int x, double top, double bottom, const Colour& col);
  29935. void drawHorizontalLine (const int x, double top, double bottom, const Colour& col);
  29936. RectangleList* getRawClipRegion() throw() { return clip; }
  29937. juce_UseDebuggingNewOperator
  29938. protected:
  29939. Image& image;
  29940. RectangleList* clip;
  29941. int xOffset, yOffset;
  29942. struct SavedState
  29943. {
  29944. SavedState (RectangleList* const clip, const int xOffset, const int yOffset);
  29945. ~SavedState();
  29946. RectangleList* clip;
  29947. const int xOffset, yOffset;
  29948. private:
  29949. SavedState (const SavedState&);
  29950. const SavedState& operator= (const SavedState&);
  29951. };
  29952. OwnedArray <SavedState> stateStack;
  29953. void drawVertical (const int x, const double top, const double bottom, const Colour& col);
  29954. void drawHorizontal (const int y, const double top, const double bottom, const Colour& col);
  29955. bool getPathBounds (int clipX, int clipY, int clipW, int clipH,
  29956. const Path& path, const AffineTransform& transform,
  29957. int& x, int& y, int& w, int& h) const;
  29958. void clippedFillRectWithColour (const Rectangle& clipRect, int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents);
  29959. void clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const Colour& colour, EdgeTable::OversamplingLevel quality);
  29960. void clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality);
  29961. void clippedFillPathWithImage (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& transform,
  29962. const Image& image, int imageX, int imageY, float alpha, EdgeTable::OversamplingLevel quality);
  29963. void clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const Colour& colour);
  29964. void clippedFillAlphaChannelWithGradient (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY, const ColourGradient& gradient);
  29965. void clippedFillAlphaChannelWithImage (int clipX, int clipY, int clipW, int clipH, const Image& alphaImage, int alphaImageX, int alphaImageY,
  29966. const Image& fillerImage, int fillerImageX, int fillerImageY, float alpha);
  29967. void clippedBlendImage (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29968. int destX, int destY, int destW, int destH, int sourceX, int sourceY,
  29969. float alpha);
  29970. void clippedBlendImageWarping (int clipX, int clipY, int clipW, int clipH, const Image& sourceImage,
  29971. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  29972. const AffineTransform& transform,
  29973. float alpha, const Graphics::ResamplingQuality quality);
  29974. void clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour);
  29975. void clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29976. void clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH, const int x, double top, double bottom, const Colour& col);
  29977. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  29978. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  29979. };
  29980. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  29981. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  29982. #endif
  29983. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  29984. #endif
  29985. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  29986. #endif
  29987. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  29988. #endif
  29989. #ifndef __JUCE_LINE_JUCEHEADER__
  29990. #endif
  29991. #ifndef __JUCE_PATH_JUCEHEADER__
  29992. #endif
  29993. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29994. /********* Start of inlined file: juce_PathIterator.h *********/
  29995. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  29996. #define __JUCE_PATHITERATOR_JUCEHEADER__
  29997. /**
  29998. Flattens a Path object into a series of straight-line sections.
  29999. Use one of these to iterate through a Path object, and it will convert
  30000. all the curves into line sections so it's easy to render or perform
  30001. geometric operations on.
  30002. @see Path
  30003. */
  30004. class JUCE_API PathFlatteningIterator
  30005. {
  30006. public:
  30007. /** Creates a PathFlatteningIterator.
  30008. After creation, use the next() method to initialise the fields in the
  30009. object with the first line's position.
  30010. @param path the path to iterate along
  30011. @param transform a transform to apply to each point in the path being iterated
  30012. @param tolerence the amount by which the curves are allowed to deviate from the
  30013. lines into which they are being broken down - a higher tolerence
  30014. is a bit faster, but less smooth.
  30015. */
  30016. PathFlatteningIterator (const Path& path,
  30017. const AffineTransform& transform = AffineTransform::identity,
  30018. float tolerence = 9.0f) throw();
  30019. /** Destructor. */
  30020. ~PathFlatteningIterator() throw();
  30021. /** Fetches the next line segment from the path.
  30022. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  30023. so that they describe the new line segment.
  30024. @returns false when there are no more lines to fetch.
  30025. */
  30026. bool next() throw();
  30027. /** The x position of the start of the current line segment. */
  30028. float x1;
  30029. /** The y position of the start of the current line segment. */
  30030. float y1;
  30031. /** The x position of the end of the current line segment. */
  30032. float x2;
  30033. /** The y position of the end of the current line segment. */
  30034. float y2;
  30035. /** Indicates whether the current line segment is closing a sub-path.
  30036. If the current line is the one that connects the end of a sub-path
  30037. back to the start again, this will be true.
  30038. */
  30039. bool closesSubPath;
  30040. /** The index of the current line within the current sub-path.
  30041. E.g. you can use this to see whether the line is the first one in the
  30042. subpath by seeing if it's 0.
  30043. */
  30044. int subPathIndex;
  30045. /** Returns true if the current segment is the last in the current sub-path. */
  30046. bool isLastInSubpath() const throw() { return stackPos == stackBase
  30047. && (index >= path.numElements
  30048. || points [index] == Path::moveMarker); }
  30049. juce_UseDebuggingNewOperator
  30050. private:
  30051. const Path& path;
  30052. const AffineTransform transform;
  30053. float* points;
  30054. float tolerence, subPathCloseX, subPathCloseY;
  30055. bool isIdentityTransform;
  30056. float* stackBase;
  30057. float* stackPos;
  30058. int index, stackSize;
  30059. PathFlatteningIterator (const PathFlatteningIterator&);
  30060. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  30061. };
  30062. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  30063. /********* End of inlined file: juce_PathIterator.h *********/
  30064. #endif
  30065. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  30066. #endif
  30067. #ifndef __JUCE_POINT_JUCEHEADER__
  30068. #endif
  30069. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30070. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  30071. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30072. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30073. /**
  30074. A rectangle whose co-ordinates can be defined in terms of absolute or
  30075. proportional distances.
  30076. Designed mainly for storing component positions, this gives you a lot of
  30077. control over how each co-ordinate is stored, either as an absolute position,
  30078. or as a proportion of the size of a parent rectangle.
  30079. It also allows you to define the anchor points by which the rectangle is
  30080. positioned, so for example you could specify that the top right of the
  30081. rectangle should be an absolute distance from its parent's bottom-right corner.
  30082. This object can be stored as a string, which takes the form "x y w h", including
  30083. symbols like '%' and letters to indicate the anchor point. See its toString()
  30084. method for more info.
  30085. Example usage:
  30086. @code
  30087. class MyComponent
  30088. {
  30089. void resized()
  30090. {
  30091. // this will set the child component's x to be 20% of our width, its y
  30092. // to be 30, its width to be 150, and its height to be 50% of our
  30093. // height..
  30094. const PositionedRectangle pos1 ("20% 30 150 50%");
  30095. pos1.applyToComponent (*myChildComponent1);
  30096. // this will inset the child component with a gap of 10 pixels
  30097. // around each of its edges..
  30098. const PositionedRectangle pos2 ("10 10 20M 20M");
  30099. pos2.applyToComponent (*myChildComponent2);
  30100. }
  30101. };
  30102. @endcode
  30103. */
  30104. class JUCE_API PositionedRectangle
  30105. {
  30106. public:
  30107. /** Creates an empty rectangle with all co-ordinates set to zero.
  30108. The default anchor point is top-left; the default
  30109. */
  30110. PositionedRectangle() throw();
  30111. /** Initialises a PositionedRectangle from a saved string version.
  30112. The string must be in the format generated by toString().
  30113. */
  30114. PositionedRectangle (const String& stringVersion) throw();
  30115. /** Creates a copy of another PositionedRectangle. */
  30116. PositionedRectangle (const PositionedRectangle& other) throw();
  30117. /** Copies another PositionedRectangle. */
  30118. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  30119. /** Destructor. */
  30120. ~PositionedRectangle() throw();
  30121. /** Returns a string version of this position, from which it can later be
  30122. re-generated.
  30123. The format is four co-ordinates, "x y w h".
  30124. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  30125. - If a co-ordinate is proportional to its parent's width or height, it is stored
  30126. as a percentage, e.g. "80%".
  30127. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  30128. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  30129. the parent's right-hand edge.
  30130. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  30131. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  30132. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  30133. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  30134. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  30135. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  30136. has "c" appended to it. So "-50Rc" would mean that this component's
  30137. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  30138. this component's centre should be placed 40% across the parent's width.
  30139. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  30140. the number has "M" appended to it.
  30141. To reload a stored string, use the constructor that takes a string parameter.
  30142. */
  30143. const String toString() const throw();
  30144. /** Calculates the absolute position, given the size of the space that
  30145. it should go in.
  30146. This will work out any proportional distances and sizes relative to the
  30147. target rectangle, and will return the absolute position.
  30148. @see applyToComponent
  30149. */
  30150. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  30151. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  30152. */
  30153. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  30154. double& x,
  30155. double& y,
  30156. double& width,
  30157. double& height) const throw();
  30158. /** This sets the bounds of the given component to this position.
  30159. This is equivalent to writing:
  30160. @code
  30161. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  30162. @endcode
  30163. @see getRectangle, updateFromComponent
  30164. */
  30165. void applyToComponent (Component& comp) const throw();
  30166. /** Updates this object's co-ordinates to match the given rectangle.
  30167. This will set all co-ordinates based on the given rectangle, re-calculating
  30168. any proportional distances, and using the current anchor points.
  30169. So for example if the x co-ordinate mode is currently proportional, this will
  30170. re-calculate x based on the rectangle's relative position within the target
  30171. rectangle's width.
  30172. If the target rectangle's width or height are zero then it may not be possible
  30173. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  30174. will not be changed.
  30175. */
  30176. void updateFrom (const Rectangle& newPosition,
  30177. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30178. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  30179. */
  30180. void updateFromDouble (const double x, const double y,
  30181. const double width, const double height,
  30182. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30183. /** Updates this object's co-ordinates to match the bounds of this component.
  30184. This is equivalent to calling updateFrom() with the component's bounds and
  30185. it parent size.
  30186. If the component doesn't currently have a parent, then proportional co-ordinates
  30187. might not be updated because it would need to know the parent's size to do the
  30188. maths for this.
  30189. */
  30190. void updateFromComponent (const Component& comp) throw();
  30191. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  30192. enum AnchorPoint
  30193. {
  30194. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  30195. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  30196. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  30197. };
  30198. /** Specifies how an x or y co-ordinate should be interpreted. */
  30199. enum PositionMode
  30200. {
  30201. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  30202. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  30203. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  30204. 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. */
  30205. };
  30206. /** Specifies how the width or height should be interpreted. */
  30207. enum SizeMode
  30208. {
  30209. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  30210. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  30211. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  30212. };
  30213. /** Sets all options for all co-ordinates.
  30214. This requires a reference rectangle to be specified, because if you're changing any
  30215. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  30216. the co-ordinates, and will need to know the parent size so it can calculate this.
  30217. */
  30218. void setModes (const AnchorPoint xAnchorMode,
  30219. const PositionMode xPositionMode,
  30220. const AnchorPoint yAnchorMode,
  30221. const PositionMode yPositionMode,
  30222. const SizeMode widthMode,
  30223. const SizeMode heightMode,
  30224. const Rectangle& targetSpaceToBeRelativeTo) throw();
  30225. /** Returns the anchoring mode for the x co-ordinate.
  30226. To change any of the modes, use setModes().
  30227. */
  30228. AnchorPoint getAnchorPointX() const throw();
  30229. /** Returns the positioning mode for the x co-ordinate.
  30230. To change any of the modes, use setModes().
  30231. */
  30232. PositionMode getPositionModeX() const throw();
  30233. /** Returns the raw x co-ordinate.
  30234. If the x position mode is absolute, then this will be the absolute value. If it's
  30235. proportional, then this will be a fractional proportion, where 1.0 means the full
  30236. width of the parent space.
  30237. */
  30238. double getX() const throw() { return x; }
  30239. /** Sets the raw value of the x co-ordinate.
  30240. See getX() for the meaning of this value.
  30241. */
  30242. void setX (const double newX) throw() { x = newX; }
  30243. /** Returns the anchoring mode for the y co-ordinate.
  30244. To change any of the modes, use setModes().
  30245. */
  30246. AnchorPoint getAnchorPointY() const throw();
  30247. /** Returns the positioning mode for the y co-ordinate.
  30248. To change any of the modes, use setModes().
  30249. */
  30250. PositionMode getPositionModeY() const throw();
  30251. /** Returns the raw y co-ordinate.
  30252. If the y position mode is absolute, then this will be the absolute value. If it's
  30253. proportional, then this will be a fractional proportion, where 1.0 means the full
  30254. height of the parent space.
  30255. */
  30256. double getY() const throw() { return y; }
  30257. /** Sets the raw value of the y co-ordinate.
  30258. See getY() for the meaning of this value.
  30259. */
  30260. void setY (const double newY) throw() { y = newY; }
  30261. /** Returns the mode used to calculate the width.
  30262. To change any of the modes, use setModes().
  30263. */
  30264. SizeMode getWidthMode() const throw();
  30265. /** Returns the raw width value.
  30266. If the width mode is absolute, then this will be the absolute value. If the mode is
  30267. proportional, then this will be a fractional proportion, where 1.0 means the full
  30268. width of the parent space.
  30269. */
  30270. double getWidth() const throw() { return w; }
  30271. /** Sets the raw width value.
  30272. See getWidth() for the details about what this value means.
  30273. */
  30274. void setWidth (const double newWidth) throw() { w = newWidth; }
  30275. /** Returns the mode used to calculate the height.
  30276. To change any of the modes, use setModes().
  30277. */
  30278. SizeMode getHeightMode() const throw();
  30279. /** Returns the raw height value.
  30280. If the height mode is absolute, then this will be the absolute value. If the mode is
  30281. proportional, then this will be a fractional proportion, where 1.0 means the full
  30282. height of the parent space.
  30283. */
  30284. double getHeight() const throw() { return h; }
  30285. /** Sets the raw height value.
  30286. See getHeight() for the details about what this value means.
  30287. */
  30288. void setHeight (const double newHeight) throw() { h = newHeight; }
  30289. /** If the size and position are constance, and wouldn't be affected by changes
  30290. in the parent's size, then this will return true.
  30291. */
  30292. bool isPositionAbsolute() const throw();
  30293. /** Compares two objects. */
  30294. const bool operator== (const PositionedRectangle& other) const throw();
  30295. /** Compares two objects. */
  30296. const bool operator!= (const PositionedRectangle& other) const throw();
  30297. juce_UseDebuggingNewOperator
  30298. private:
  30299. double x, y, w, h;
  30300. uint8 xMode, yMode, wMode, hMode;
  30301. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  30302. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  30303. void decodePosString (const String& s, uint8& mode, double& value) throw();
  30304. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  30305. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  30306. const uint8 xMode, const uint8 wMode,
  30307. const int parentPos, const int parentSize) const throw();
  30308. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  30309. const uint8 xMode, const uint8 wMode,
  30310. const int parentPos, const int parentSize) const throw();
  30311. };
  30312. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  30313. /********* End of inlined file: juce_PositionedRectangle.h *********/
  30314. #endif
  30315. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  30316. #endif
  30317. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  30318. #endif
  30319. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  30320. /********* Start of inlined file: juce_CameraDevice.h *********/
  30321. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  30322. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  30323. #if JUCE_USE_CAMERA
  30324. /**
  30325. Receives callbacks with images from a CameraDevice.
  30326. @see CameraDevice::addListener
  30327. */
  30328. class CameraImageListener
  30329. {
  30330. public:
  30331. CameraImageListener() {}
  30332. virtual ~CameraImageListener() {}
  30333. /** This method is called when a new image arrives.
  30334. This may be called by any thread, so be careful about thread-safety,
  30335. and make sure that you process the data as quickly as possible to
  30336. avoid glitching!
  30337. */
  30338. virtual void imageReceived (Image& image) = 0;
  30339. };
  30340. /**
  30341. Controls any camera capture devices that might be available.
  30342. Use getAvailableDevices() to list the devices that are attached to the
  30343. system, then call openDevice to open one for use. Once you have a CameraDevice
  30344. object, you can get a viewer component from it, and use its methods to
  30345. stream to a file or capture still-frames.
  30346. */
  30347. class JUCE_API CameraDevice
  30348. {
  30349. public:
  30350. /** Destructor. */
  30351. virtual ~CameraDevice();
  30352. /** Returns a list of the available cameras on this machine.
  30353. You can open one of these devices by calling openDevice().
  30354. */
  30355. static const StringArray getAvailableDevices();
  30356. /** Opens a camera device.
  30357. The index parameter indicates which of the items returned by getAvailableDevices()
  30358. to open.
  30359. The size constraints allow the method to choose between different resolutions if
  30360. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  30361. then these will be ignored.
  30362. */
  30363. static CameraDevice* openDevice (int deviceIndex,
  30364. int minWidth = 128, int minHeight = 64,
  30365. int maxWidth = 1024, int maxHeight = 768);
  30366. /** Returns the name of this device */
  30367. const String getName() const throw() { return name; }
  30368. /** Creates a component that can be used to display a preview of the
  30369. video from this camera.
  30370. */
  30371. Component* createViewerComponent();
  30372. /** Starts recording video to the specified file.
  30373. You should use getFileExtension() to find out the correct extension to
  30374. use for your filename.
  30375. If the file exists, it will be deleted before the recording starts.
  30376. This method may not start recording instantly, so if you need to know the
  30377. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  30378. after the recording has finished.
  30379. */
  30380. void startRecordingToFile (const File& file);
  30381. /** Stops recording, after a call to startRecordingToFile().
  30382. */
  30383. void stopRecording();
  30384. /** Returns the file extension that should be used for the files
  30385. that you pass to startRecordingToFile().
  30386. This may be platform-specific, e.g. ".mov" or ".avi".
  30387. */
  30388. static const String getFileExtension();
  30389. /** After calling stopRecording(), this method can be called to return the timestamp
  30390. of the first frame that was written to the file.
  30391. */
  30392. const Time getTimeOfFirstRecordedFrame() const;
  30393. /** Adds a listener to receive images from the camera.
  30394. Be very careful not to delete the listener without first removing it by calling
  30395. removeListener().
  30396. */
  30397. void addListener (CameraImageListener* listenerToAdd);
  30398. /** Removes a listener that was previously added with addListener().
  30399. */
  30400. void removeListener (CameraImageListener* listenerToRemove);
  30401. juce_UseDebuggingNewOperator
  30402. protected:
  30403. /** @internal */
  30404. CameraDevice (const String& name, int index);
  30405. private:
  30406. void* internal;
  30407. bool isRecording;
  30408. String name;
  30409. CameraDevice (const CameraDevice&);
  30410. const CameraDevice& operator= (const CameraDevice&);
  30411. };
  30412. #endif
  30413. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  30414. /********* End of inlined file: juce_CameraDevice.h *********/
  30415. #endif
  30416. #ifndef __JUCE_IMAGE_JUCEHEADER__
  30417. #endif
  30418. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30419. /********* Start of inlined file: juce_ImageCache.h *********/
  30420. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  30421. #define __JUCE_IMAGECACHE_JUCEHEADER__
  30422. /**
  30423. A global cache of images that have been loaded from files or memory.
  30424. If you're loading an image and may need to use the image in more than one
  30425. place, this is used to allow the same image to be shared rather than loading
  30426. multiple copies into memory.
  30427. Another advantage is that after images are released, they will be kept in
  30428. memory for a few seconds before it is actually deleted, so if you're repeatedly
  30429. loading/deleting the same image, it'll reduce the chances of having to reload it
  30430. each time.
  30431. @see Image, ImageFileFormat
  30432. */
  30433. class JUCE_API ImageCache : private DeletedAtShutdown,
  30434. private Timer
  30435. {
  30436. public:
  30437. /** Loads an image from a file, (or just returns the image if it's already cached).
  30438. If the cache already contains an image that was loaded from this file,
  30439. that image will be returned. Otherwise, this method will try to load the
  30440. file, add it to the cache, and return it.
  30441. It's very important not to delete the image that is returned - instead use
  30442. the ImageCache::release() method.
  30443. Also, remember that the image returned is shared, so drawing into it might
  30444. affect other things that are using it!
  30445. @param file the file to try to load
  30446. @returns the image, or null if it there was an error loading it
  30447. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30448. */
  30449. static Image* getFromFile (const File& file);
  30450. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  30451. If the cache already contains an image that was loaded from this block of memory,
  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 imageData the block of memory containing the image data
  30459. @param dataSize the data size in bytes
  30460. @returns the image, or null if it there was an error loading it
  30461. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  30462. */
  30463. static Image* getFromMemory (const void* imageData,
  30464. const int dataSize);
  30465. /** Releases an image that was previously created by the ImageCache.
  30466. If an image has been returned by the getFromFile() or getFromMemory() methods,
  30467. it mustn't be deleted directly, but should be released with this method
  30468. instead.
  30469. @see getFromFile, getFromMemory
  30470. */
  30471. static void release (Image* const imageToRelease);
  30472. /** Checks whether an image is in the cache or not.
  30473. @returns true if the image is currently in the cache
  30474. */
  30475. static bool isImageInCache (Image* const imageToLookFor);
  30476. /** Increments the reference-count for a cached image.
  30477. If the image isn't in the cache, this method won't do anything.
  30478. */
  30479. static void incReferenceCount (Image* const image);
  30480. /** Checks the cache for an image with a particular hashcode.
  30481. If there's an image in the cache with this hashcode, it will be returned,
  30482. otherwise it will return zero.
  30483. If an image is returned, it must be released with the release() method
  30484. when no longer needed, to maintain the correct reference counts.
  30485. @param hashCode the hash code that would have been associated with the
  30486. image by addImageToCache()
  30487. @see addImageToCache
  30488. */
  30489. static Image* getFromHashCode (const int64 hashCode);
  30490. /** Adds an image to the cache with a user-defined hash-code.
  30491. After calling this, responsibilty for deleting the image will be taken
  30492. by the ImageCache.
  30493. The image will be initially be given a reference count of 1, so call
  30494. the release() method to delete it.
  30495. @param image the image to add
  30496. @param hashCode the hash-code to associate with it
  30497. @see getFromHashCode
  30498. */
  30499. static void addImageToCache (Image* const image,
  30500. const int64 hashCode);
  30501. /** Changes the amount of time before an unused image will be removed from the cache.
  30502. By default this is about 5 seconds.
  30503. */
  30504. static void setCacheTimeout (const int millisecs);
  30505. juce_UseDebuggingNewOperator
  30506. private:
  30507. CriticalSection lock;
  30508. VoidArray images;
  30509. ImageCache() throw();
  30510. ImageCache (const ImageCache&);
  30511. const ImageCache& operator= (const ImageCache&);
  30512. ~ImageCache();
  30513. void timerCallback();
  30514. };
  30515. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  30516. /********* End of inlined file: juce_ImageCache.h *********/
  30517. #endif
  30518. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30519. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  30520. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30521. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30522. /**
  30523. Represents a filter kernel to use in convoluting an image.
  30524. @see Image::applyConvolution
  30525. */
  30526. class JUCE_API ImageConvolutionKernel
  30527. {
  30528. public:
  30529. /** Creates an empty convulution kernel.
  30530. @param size the length of each dimension of the kernel, so e.g. if the size
  30531. is 5, it will create a 5x5 kernel
  30532. */
  30533. ImageConvolutionKernel (const int size) throw();
  30534. /** Destructor. */
  30535. ~ImageConvolutionKernel() throw();
  30536. /** Resets all values in the kernel to zero.
  30537. */
  30538. void clear() throw();
  30539. /** Sets the value of a specific cell in the kernel.
  30540. The x and y parameters must be in the range 0 < x < getKernelSize().
  30541. @see setOverallSum
  30542. */
  30543. void setKernelValue (const int x,
  30544. const int y,
  30545. const float value) throw();
  30546. /** Rescales all values in the kernel to make the total add up to a fixed value.
  30547. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  30548. */
  30549. void setOverallSum (const float desiredTotalSum) throw();
  30550. /** Multiplies all values in the kernel by a value. */
  30551. void rescaleAllValues (const float multiplier) throw();
  30552. /** Intialises the kernel for a gaussian blur.
  30553. @param blurRadius this may be larger or smaller than the kernel's actual
  30554. size but this will obviously be wasteful or clip at the
  30555. edges. Ideally the kernel should be just larger than
  30556. (blurRadius * 2).
  30557. */
  30558. void createGaussianBlur (const float blurRadius) throw();
  30559. /** Returns the size of the kernel.
  30560. E.g. if it's a 3x3 kernel, this returns 3.
  30561. */
  30562. int getKernelSize() const throw() { return size; }
  30563. /** Returns a 2-dimensional array of the kernel's values.
  30564. The size of each dimension of the array will be getKernelSize().
  30565. */
  30566. float** getValues() const throw() { return values; }
  30567. /** Applies the kernel to an image.
  30568. @param destImage the image that will receive the resultant convoluted pixels.
  30569. @param sourceImage an optional source image to read from - if this is 0, then the
  30570. destination image will be used as the source. If an image is
  30571. specified, it must be exactly the same size and type as the destination
  30572. image.
  30573. @param x the region of the image to apply the filter to
  30574. @param y the region of the image to apply the filter to
  30575. @param width the region of the image to apply the filter to
  30576. @param height the region of the image to apply the filter to
  30577. */
  30578. void applyToImage (Image& destImage,
  30579. const Image* sourceImage,
  30580. int x,
  30581. int y,
  30582. int width,
  30583. int height) const;
  30584. juce_UseDebuggingNewOperator
  30585. private:
  30586. float** values;
  30587. int size;
  30588. // no reason not to implement these one day..
  30589. ImageConvolutionKernel (const ImageConvolutionKernel&);
  30590. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  30591. };
  30592. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  30593. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  30594. #endif
  30595. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30596. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  30597. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30598. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30599. /**
  30600. Base-class for codecs that can read and write image file formats such
  30601. as PNG, JPEG, etc.
  30602. This class also contains static methods to make it easy to load images
  30603. from files, streams or from memory.
  30604. @see Image, ImageCache
  30605. */
  30606. class JUCE_API ImageFileFormat
  30607. {
  30608. protected:
  30609. /** Creates an ImageFormat. */
  30610. ImageFileFormat() throw() {}
  30611. public:
  30612. /** Destructor. */
  30613. virtual ~ImageFileFormat() throw() {}
  30614. /** Returns a description of this file format.
  30615. E.g. "JPEG", "PNG"
  30616. */
  30617. virtual const String getFormatName() = 0;
  30618. /** Returns true if the given stream seems to contain data that this format
  30619. understands.
  30620. The format class should only read the first few bytes of the stream and sniff
  30621. for header bytes that it understands.
  30622. @see decodeImage
  30623. */
  30624. virtual bool canUnderstand (InputStream& input) = 0;
  30625. /** Tries to decode and return an image from the given stream.
  30626. This will be called for an image format after calling its canUnderStand() method
  30627. to see if it can handle the stream.
  30628. @param input the stream to read the data from. The stream will be positioned
  30629. at the start of the image data (but this may not necessarily
  30630. be position 0)
  30631. @returns the image that was decoded, or 0 if it fails. It's the
  30632. caller's responsibility to delete this image when no longer needed.
  30633. @see loadFrom
  30634. */
  30635. virtual Image* decodeImage (InputStream& input) = 0;
  30636. /** Attempts to write an image to a stream.
  30637. To specify extra information like encoding quality, there will be appropriate parameters
  30638. in the subclasses of the specific file types.
  30639. @returns true if it nothing went wrong.
  30640. */
  30641. virtual bool writeImageToStream (const Image& sourceImage,
  30642. OutputStream& destStream) = 0;
  30643. /** Tries the built-in decoders to see if it can find one to read this stream.
  30644. There are currently built-in decoders for PNG, JPEG and GIF formats.
  30645. The object that is returned should not be deleted by the caller.
  30646. @see canUnderstand, decodeImage, loadFrom
  30647. */
  30648. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  30649. /** Tries to load an image from a stream.
  30650. This will use the findImageFormatForStream() method to locate a suitable
  30651. codec, and use that to load the image.
  30652. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30653. caller's responsibility to delete this image when no longer needed.
  30654. */
  30655. static Image* loadFrom (InputStream& input);
  30656. /** Tries to load an image from a file.
  30657. This will use the findImageFormatForStream() method to locate a suitable
  30658. codec, and use that to load the image.
  30659. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30660. caller's responsibility to delete this image when no longer needed.
  30661. */
  30662. static Image* loadFrom (const File& file);
  30663. /** Tries to load an image from a block of raw image data.
  30664. This will use the findImageFormatForStream() method to locate a suitable
  30665. codec, and use that to load the image.
  30666. @returns the image that was decoded, or 0 if it fails to load one. It's the
  30667. caller's responsibility to delete this image when no longer needed.
  30668. */
  30669. static Image* loadFrom (const void* rawData,
  30670. const int numBytesOfData);
  30671. };
  30672. /**
  30673. A type of ImageFileFormat for reading and writing PNG files.
  30674. @see ImageFileFormat, JPEGImageFormat
  30675. */
  30676. class JUCE_API PNGImageFormat : public ImageFileFormat
  30677. {
  30678. public:
  30679. PNGImageFormat() throw();
  30680. ~PNGImageFormat() throw();
  30681. const String getFormatName();
  30682. bool canUnderstand (InputStream& input);
  30683. Image* decodeImage (InputStream& input);
  30684. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30685. };
  30686. /**
  30687. A type of ImageFileFormat for reading and writing JPEG files.
  30688. @see ImageFileFormat, PNGImageFormat
  30689. */
  30690. class JUCE_API JPEGImageFormat : public ImageFileFormat
  30691. {
  30692. public:
  30693. JPEGImageFormat() throw();
  30694. ~JPEGImageFormat() throw();
  30695. /** Specifies the quality to be used when writing a JPEG file.
  30696. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  30697. any negative value is "default" quality
  30698. */
  30699. void setQuality (const float newQuality);
  30700. const String getFormatName();
  30701. bool canUnderstand (InputStream& input);
  30702. Image* decodeImage (InputStream& input);
  30703. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  30704. private:
  30705. float quality;
  30706. };
  30707. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  30708. /********* End of inlined file: juce_ImageFileFormat.h *********/
  30709. #endif
  30710. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30711. /********* Start of inlined file: juce_DrawableComposite.h *********/
  30712. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30713. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30714. /********* Start of inlined file: juce_Drawable.h *********/
  30715. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30716. #define __JUCE_DRAWABLE_JUCEHEADER__
  30717. /**
  30718. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  30719. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30720. */
  30721. class JUCE_API Drawable
  30722. {
  30723. protected:
  30724. /** The base class can't be instantiated directly.
  30725. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30726. */
  30727. Drawable();
  30728. public:
  30729. /** Destructor. */
  30730. virtual ~Drawable();
  30731. /** Creates a deep copy of this Drawable object.
  30732. Use this to create a new copy of this and any sub-objects in the tree.
  30733. */
  30734. virtual Drawable* createCopy() const = 0;
  30735. /** Renders this Drawable object.
  30736. @see drawWithin
  30737. */
  30738. void draw (Graphics& g,
  30739. const AffineTransform& transform = AffineTransform::identity) const;
  30740. /** Renders the Drawable at a given offset within the Graphics context.
  30741. The co-ordinates passed-in are used to translate the object relative to its own
  30742. origin before drawing it - this is basically a quick way of saying:
  30743. @code
  30744. draw (g, AffineTransform::translation (x, y)).
  30745. @endcode
  30746. */
  30747. void drawAt (Graphics& g,
  30748. const float x,
  30749. const float y) const;
  30750. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  30751. changing its aspect-ratio.
  30752. The object can placed arbitrarily within the rectangle based on a Justification type,
  30753. and can either be made as big as possible, or just reduced to fit.
  30754. @param g the graphics context to render onto
  30755. @param destX top-left of the target rectangle to fit it into
  30756. @param destY top-left of the target rectangle to fit it into
  30757. @param destWidth size of the target rectangle to fit the image into
  30758. @param destHeight size of the target rectangle to fit the image into
  30759. @param placement defines the alignment and rescaling to use to fit
  30760. this object within the target rectangle.
  30761. */
  30762. void drawWithin (Graphics& g,
  30763. const int destX,
  30764. const int destY,
  30765. const int destWidth,
  30766. const int destHeight,
  30767. const RectanglePlacement& placement) const;
  30768. /** Holds the information needed when telling a drawable to render itself.
  30769. @see Drawable::draw
  30770. */
  30771. class RenderingContext
  30772. {
  30773. public:
  30774. RenderingContext (Graphics& g, const AffineTransform& transform, const float opacity) throw();
  30775. Graphics& g;
  30776. AffineTransform transform;
  30777. float opacity;
  30778. private:
  30779. const RenderingContext& operator= (const RenderingContext&);
  30780. };
  30781. /** Renders this Drawable object.
  30782. @see draw
  30783. */
  30784. virtual void render (const RenderingContext& context) const = 0;
  30785. /** Returns the smallest rectangle that can contain this Drawable object.
  30786. Co-ordinates are relative to the object's own origin.
  30787. */
  30788. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  30789. /** Returns true if the given point is somewhere inside this Drawable.
  30790. Co-ordinates are relative to the object's own origin.
  30791. */
  30792. virtual bool hitTest (float x, float y) const = 0;
  30793. /** Returns the name given to this drawable.
  30794. @see setName
  30795. */
  30796. const String& getName() const throw() { return name; }
  30797. /** Assigns a name to this drawable. */
  30798. void setName (const String& newName) throw() { name = newName; }
  30799. /** Tries to turn some kind of image file into a drawable.
  30800. The data could be an image that the ImageFileFormat class understands, or it
  30801. could be SVG.
  30802. */
  30803. static Drawable* createFromImageData (const void* data, const int numBytes);
  30804. /** Tries to turn a stream containing some kind of image data into a drawable.
  30805. The data could be an image that the ImageFileFormat class understands, or it
  30806. could be SVG.
  30807. */
  30808. static Drawable* createFromImageDataStream (InputStream& dataSource);
  30809. /** Tries to turn a file containing some kind of image data into a drawable.
  30810. The data could be an image that the ImageFileFormat class understands, or it
  30811. could be SVG.
  30812. */
  30813. static Drawable* createFromImageFile (const File& file);
  30814. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  30815. into a Drawable tree.
  30816. The object returned must be deleted by the caller. If something goes wrong
  30817. while parsing, it may return 0.
  30818. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  30819. implementation, but it can return the basic vector objects.
  30820. */
  30821. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30822. /**
  30823. */
  30824. static Drawable* readFromBinaryStream (InputStream& input);
  30825. /**
  30826. */
  30827. bool writeToBinaryStream (OutputStream& output) const;
  30828. /**
  30829. */
  30830. static Drawable* readFromXml (const XmlElement& xml);
  30831. /**
  30832. */
  30833. XmlElement* createXml() const;
  30834. /** @internal */
  30835. virtual bool readBinary (InputStream& input) = 0;
  30836. /** @internal */
  30837. virtual bool writeBinary (OutputStream& output) const = 0;
  30838. /** @internal */
  30839. virtual bool readXml (const XmlElement& xml) = 0;
  30840. /** @internal */
  30841. virtual void writeXml (XmlElement& xml) const = 0;
  30842. juce_UseDebuggingNewOperator
  30843. private:
  30844. Drawable (const Drawable&);
  30845. const Drawable& operator= (const Drawable&);
  30846. String name;
  30847. };
  30848. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30849. /********* End of inlined file: juce_Drawable.h *********/
  30850. /**
  30851. A drawable object which acts as a container for a set of other Drawables.
  30852. @see Drawable
  30853. */
  30854. class JUCE_API DrawableComposite : public Drawable
  30855. {
  30856. public:
  30857. /** Creates a composite Drawable.
  30858. */
  30859. DrawableComposite();
  30860. /** Destructor. */
  30861. virtual ~DrawableComposite();
  30862. /** Adds a new sub-drawable to this one.
  30863. This passes in a Drawable pointer for this object to look after. To add a copy
  30864. of a drawable, use the form of this method that takes a Drawable reference instead.
  30865. @param drawable the object to add - this will be deleted automatically
  30866. when no longer needed, so the caller mustn't keep any
  30867. pointers to it.
  30868. @param transform the transform to apply to this drawable when it's being
  30869. drawn
  30870. @param index where to insert it in the list of drawables. 0 is the back,
  30871. -1 is the front, or any value from 0 and getNumDrawables()
  30872. can be used
  30873. @see removeDrawable
  30874. */
  30875. void insertDrawable (Drawable* drawable,
  30876. const AffineTransform& transform = AffineTransform::identity,
  30877. const int index = -1);
  30878. /** Adds a new sub-drawable to this one.
  30879. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  30880. for this object to look after, use the form of this method that takes a Drawable
  30881. pointer instead.
  30882. @param drawable the object to add - an internal copy will be made of this object
  30883. @param transform the transform to apply to this drawable when it's being
  30884. drawn
  30885. @param index where to insert it in the list of drawables. 0 is the back,
  30886. -1 is the front, or any value from 0 and getNumDrawables()
  30887. can be used
  30888. @see removeDrawable
  30889. */
  30890. void insertDrawable (const Drawable& drawable,
  30891. const AffineTransform& transform = AffineTransform::identity,
  30892. const int index = -1);
  30893. /** Deletes one of the Drawable objects.
  30894. @param index the index of the drawable to delete, between 0
  30895. and (getNumDrawables() - 1).
  30896. @param deleteDrawable if this is true, the drawable that is removed will also
  30897. be deleted. If false, it'll just be removed.
  30898. @see insertDrawable, getNumDrawables
  30899. */
  30900. void removeDrawable (const int index, const bool deleteDrawable = true);
  30901. /** Returns the number of drawables contained inside this one.
  30902. @see getDrawable
  30903. */
  30904. int getNumDrawables() const throw() { return drawables.size(); }
  30905. /** Returns one of the drawables that are contained in this one.
  30906. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  30907. to find it.
  30908. The pointer returned is managed by this object and will be deleted when no longer
  30909. needed, so be careful what you do with it.
  30910. @see getNumDrawables
  30911. */
  30912. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  30913. /** Returns the transform that applies to one of the drawables that are contained in this one.
  30914. The pointer returned is managed by this object and will be deleted when no longer
  30915. needed, so be careful what you do with it.
  30916. @see getNumDrawables
  30917. */
  30918. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  30919. /** Brings one of the Drawables to the front.
  30920. @param index the index of the drawable to move, between 0
  30921. and (getNumDrawables() - 1).
  30922. @see insertDrawable, getNumDrawables
  30923. */
  30924. void bringToFront (const int index);
  30925. /** @internal */
  30926. void render (const Drawable::RenderingContext& context) const;
  30927. /** @internal */
  30928. void getBounds (float& x, float& y, float& width, float& height) const;
  30929. /** @internal */
  30930. bool hitTest (float x, float y) const;
  30931. /** @internal */
  30932. Drawable* createCopy() const;
  30933. /** @internal */
  30934. bool readBinary (InputStream& input);
  30935. /** @internal */
  30936. bool writeBinary (OutputStream& output) const;
  30937. /** @internal */
  30938. bool readXml (const XmlElement& xml);
  30939. /** @internal */
  30940. void writeXml (XmlElement& xml) const;
  30941. juce_UseDebuggingNewOperator
  30942. private:
  30943. OwnedArray <Drawable> drawables;
  30944. OwnedArray <AffineTransform> transforms;
  30945. DrawableComposite (const DrawableComposite&);
  30946. const DrawableComposite& operator= (const DrawableComposite&);
  30947. };
  30948. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  30949. /********* End of inlined file: juce_DrawableComposite.h *********/
  30950. #endif
  30951. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30952. #endif
  30953. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30954. /********* Start of inlined file: juce_DrawableImage.h *********/
  30955. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30956. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  30957. /**
  30958. A drawable object which is a bitmap image.
  30959. @see Drawable
  30960. */
  30961. class JUCE_API DrawableImage : public Drawable
  30962. {
  30963. public:
  30964. DrawableImage();
  30965. /** Destructor. */
  30966. virtual ~DrawableImage();
  30967. /** Sets the image that this drawable will render.
  30968. An internal copy is made of the image passed-in. If you want to provide an
  30969. image that this object can take charge of without needing to create a copy,
  30970. use the other setImage() method.
  30971. */
  30972. void setImage (const Image& imageToCopy);
  30973. /** Sets the image that this drawable will render.
  30974. An internal copy of this will not be made, so the caller mustn't delete
  30975. the image while it's still being used by this object.
  30976. A good way to use this is with the ImageCache - if you create an image
  30977. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  30978. it'll be released neatly with its reference count being decreased.
  30979. @param imageToUse the image to render
  30980. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  30981. then the image will be deleted when this object no longer
  30982. needs it - unless the image was created by the ImageCache,
  30983. in which case it will be released with ImageCache::release().
  30984. */
  30985. void setImage (Image* imageToUse,
  30986. const bool releaseWhenNotNeeded);
  30987. /** Returns the current image. */
  30988. Image* getImage() const throw() { return image; }
  30989. /** Clears (and possibly deletes) the currently set image. */
  30990. void clearImage();
  30991. /** Sets the opacity to use when drawing the image. */
  30992. void setOpacity (const float newOpacity);
  30993. /** Returns the image's opacity. */
  30994. float getOpacity() const throw() { return opacity; }
  30995. /** Sets a colour to draw over the image's alpha channel.
  30996. By default this is transparent so isn't drawn, but if you set a non-transparent
  30997. colour here, then it will be overlaid on the image, using the image's alpha
  30998. channel as a mask.
  30999. This is handy for doing things like darkening or lightening an image by overlaying
  31000. it with semi-transparent black or white.
  31001. */
  31002. void setOverlayColour (const Colour& newOverlayColour);
  31003. /** Returns the overlay colour. */
  31004. const Colour& getOverlayColour() const throw() { return overlayColour; }
  31005. /** @internal */
  31006. void render (const Drawable::RenderingContext& context) const;
  31007. /** @internal */
  31008. void getBounds (float& x, float& y, float& width, float& height) const;
  31009. /** @internal */
  31010. bool hitTest (float x, float y) const;
  31011. /** @internal */
  31012. Drawable* createCopy() const;
  31013. /** @internal */
  31014. bool readBinary (InputStream& input);
  31015. /** @internal */
  31016. bool writeBinary (OutputStream& output) const;
  31017. /** @internal */
  31018. bool readXml (const XmlElement& xml);
  31019. /** @internal */
  31020. void writeXml (XmlElement& xml) const;
  31021. juce_UseDebuggingNewOperator
  31022. private:
  31023. Image* image;
  31024. bool canDeleteImage;
  31025. float opacity;
  31026. Colour overlayColour;
  31027. DrawableImage (const DrawableImage&);
  31028. const DrawableImage& operator= (const DrawableImage&);
  31029. };
  31030. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  31031. /********* End of inlined file: juce_DrawableImage.h *********/
  31032. #endif
  31033. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  31034. /********* Start of inlined file: juce_DrawablePath.h *********/
  31035. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  31036. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  31037. /**
  31038. A drawable object which renders a filled or outlined shape.
  31039. @see Drawable
  31040. */
  31041. class JUCE_API DrawablePath : public Drawable
  31042. {
  31043. public:
  31044. /** Creates a DrawablePath.
  31045. */
  31046. DrawablePath();
  31047. /** Destructor. */
  31048. virtual ~DrawablePath();
  31049. /** Changes the path that will be drawn.
  31050. @see setSolidFill, setOutline
  31051. */
  31052. void setPath (const Path& newPath);
  31053. /** Returns the current path. */
  31054. const Path& getPath() const throw() { return path; }
  31055. /** Sets a colour to fill the path with.
  31056. This colour is used to fill the path - if you don't want the path to be
  31057. filled (e.g. if you're just drawing an outline), set this colour to be
  31058. transparent.
  31059. @see setPath, setOutline
  31060. */
  31061. void setSolidFill (const Colour& newColour);
  31062. /** Sets a custom brush to use to fill the path.
  31063. @see setSolidFill
  31064. */
  31065. void setFillBrush (const Brush& newBrush);
  31066. /** Returns the brush currently being used to fill the shape. */
  31067. Brush* getCurrentBrush() const throw() { return fillBrush; }
  31068. /** Changes the properties of the outline that will be drawn around the path.
  31069. If the thickness value is 0, no outline will be drawn. If one is drawn, the
  31070. colour passed-in here will be used for it.
  31071. @see setPath, setSolidFill
  31072. */
  31073. void setOutline (const float thickness,
  31074. const Colour& outlineColour);
  31075. /** Changes the properties of the outline that will be drawn around the path.
  31076. If the stroke type has 0 thickness, no outline will be drawn.
  31077. @see setPath, setSolidFill
  31078. */
  31079. void setOutline (const PathStrokeType& strokeType,
  31080. const Brush& strokeBrush);
  31081. /** Returns the current outline style. */
  31082. const PathStrokeType& getOutlineStroke() const throw() { return strokeType; }
  31083. /** Returns the brush currently being used to draw the outline. */
  31084. Brush* getOutlineBrush() const throw() { return strokeBrush; }
  31085. /** @internal */
  31086. void render (const Drawable::RenderingContext& context) const;
  31087. /** @internal */
  31088. void getBounds (float& x, float& y, float& width, float& height) const;
  31089. /** @internal */
  31090. bool hitTest (float x, float y) const;
  31091. /** @internal */
  31092. Drawable* createCopy() const;
  31093. /** @internal */
  31094. bool readBinary (InputStream& input);
  31095. /** @internal */
  31096. bool writeBinary (OutputStream& output) const;
  31097. /** @internal */
  31098. bool readXml (const XmlElement& xml);
  31099. /** @internal */
  31100. void writeXml (XmlElement& xml) const;
  31101. juce_UseDebuggingNewOperator
  31102. private:
  31103. Path path, outline;
  31104. Brush* fillBrush;
  31105. Brush* strokeBrush;
  31106. PathStrokeType strokeType;
  31107. void updateOutline();
  31108. DrawablePath (const DrawablePath&);
  31109. const DrawablePath& operator= (const DrawablePath&);
  31110. };
  31111. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  31112. /********* End of inlined file: juce_DrawablePath.h *********/
  31113. #endif
  31114. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  31115. /********* Start of inlined file: juce_DrawableText.h *********/
  31116. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  31117. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  31118. /**
  31119. A drawable object which renders a line of text.
  31120. @see Drawable
  31121. */
  31122. class JUCE_API DrawableText : public Drawable
  31123. {
  31124. public:
  31125. /** Creates a DrawableText object. */
  31126. DrawableText();
  31127. /** Destructor. */
  31128. virtual ~DrawableText();
  31129. /** Sets the block of text to render */
  31130. void setText (const GlyphArrangement& newText);
  31131. /** Sets a single line of text to render.
  31132. This is a convenient method of adding a single line - for
  31133. more complex text, use the setText() that takes a
  31134. GlyphArrangement instead.
  31135. */
  31136. void setText (const String& newText, const Font& fontToUse);
  31137. /** Returns the text arrangement that was set with setText(). */
  31138. const GlyphArrangement& getText() const throw() { return text; }
  31139. /** Sets the colour of the text. */
  31140. void setColour (const Colour& newColour);
  31141. /** Returns the current text colour. */
  31142. const Colour& getColour() const throw() { return colour; }
  31143. /** @internal */
  31144. void render (const Drawable::RenderingContext& context) const;
  31145. /** @internal */
  31146. void getBounds (float& x, float& y, float& width, float& height) const;
  31147. /** @internal */
  31148. bool hitTest (float x, float y) const;
  31149. /** @internal */
  31150. Drawable* createCopy() const;
  31151. /** @internal */
  31152. bool readBinary (InputStream& input);
  31153. /** @internal */
  31154. bool writeBinary (OutputStream& output) const;
  31155. /** @internal */
  31156. bool readXml (const XmlElement& xml);
  31157. /** @internal */
  31158. void writeXml (XmlElement& xml) const;
  31159. juce_UseDebuggingNewOperator
  31160. private:
  31161. GlyphArrangement text;
  31162. Colour colour;
  31163. DrawableText (const DrawableText&);
  31164. const DrawableText& operator= (const DrawableText&);
  31165. };
  31166. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  31167. /********* End of inlined file: juce_DrawableText.h *********/
  31168. #endif
  31169. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  31170. #endif
  31171. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  31172. #endif
  31173. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  31174. #endif
  31175. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  31176. #endif
  31177. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31178. /********* Start of inlined file: juce_ArrowButton.h *********/
  31179. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31180. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31181. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  31182. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31183. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31184. /**
  31185. An effect filter that adds a drop-shadow behind the image's content.
  31186. (This will only work on images/components that aren't opaque, of course).
  31187. When added to a component, this effect will draw a soft-edged
  31188. shadow based on what gets drawn inside it. The shadow will also
  31189. be applied to the component's children.
  31190. For speed, this doesn't use a proper gaussian blur, but cheats by
  31191. using a simple bilinear filter. If you need a really high-quality
  31192. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31193. @see Component::setComponentEffect
  31194. */
  31195. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31196. {
  31197. public:
  31198. /** Creates a default drop-shadow effect.
  31199. To customise the shadow's appearance, use the setShadowProperties()
  31200. method.
  31201. */
  31202. DropShadowEffect();
  31203. /** Destructor. */
  31204. ~DropShadowEffect();
  31205. /** Sets up parameters affecting the shadow's appearance.
  31206. @param newRadius the (approximate) radius of the blur used
  31207. @param newOpacity the opacity with which the shadow is rendered
  31208. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  31209. component's contents
  31210. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  31211. component's contents
  31212. */
  31213. void setShadowProperties (const float newRadius,
  31214. const float newOpacity,
  31215. const int newShadowOffsetX,
  31216. const int newShadowOffsetY);
  31217. /** @internal */
  31218. void applyEffect (Image& sourceImage, Graphics& destContext);
  31219. juce_UseDebuggingNewOperator
  31220. private:
  31221. int offsetX, offsetY;
  31222. float radius, opacity;
  31223. };
  31224. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31225. /********* End of inlined file: juce_DropShadowEffect.h *********/
  31226. /**
  31227. A button with an arrow in it.
  31228. @see Button
  31229. */
  31230. class JUCE_API ArrowButton : public Button
  31231. {
  31232. public:
  31233. /** Creates an ArrowButton.
  31234. @param buttonName the name to give the button
  31235. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31236. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31237. @param arrowColour the colour to use for the arrow
  31238. */
  31239. ArrowButton (const String& buttonName,
  31240. float arrowDirection,
  31241. const Colour& arrowColour);
  31242. /** Destructor. */
  31243. ~ArrowButton();
  31244. juce_UseDebuggingNewOperator
  31245. protected:
  31246. /** @internal */
  31247. void paintButton (Graphics& g,
  31248. bool isMouseOverButton,
  31249. bool isButtonDown);
  31250. /** @internal */
  31251. void buttonStateChanged();
  31252. private:
  31253. Colour colour;
  31254. DropShadowEffect shadow;
  31255. Path path;
  31256. int offset;
  31257. ArrowButton (const ArrowButton&);
  31258. const ArrowButton& operator= (const ArrowButton&);
  31259. };
  31260. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  31261. /********* End of inlined file: juce_ArrowButton.h *********/
  31262. #endif
  31263. #ifndef __JUCE_BUTTON_JUCEHEADER__
  31264. #endif
  31265. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31266. /********* Start of inlined file: juce_DrawableButton.h *********/
  31267. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31268. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31269. /**
  31270. A button that displays a Drawable.
  31271. Up to three Drawable objects can be given to this button, to represent the
  31272. 'normal', 'over' and 'down' states.
  31273. @see Button
  31274. */
  31275. class JUCE_API DrawableButton : public Button
  31276. {
  31277. public:
  31278. enum ButtonStyle
  31279. {
  31280. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  31281. ImageRaw, /**< The button will just display the images in their normal size and position.
  31282. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  31283. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  31284. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  31285. };
  31286. /** Creates a DrawableButton.
  31287. After creating one of these, use setImages() to specify the drawables to use.
  31288. @param buttonName the name to give the component
  31289. @param buttonStyle the layout to use
  31290. @see ButtonStyle, setButtonStyle, setImages
  31291. */
  31292. DrawableButton (const String& buttonName,
  31293. const ButtonStyle buttonStyle);
  31294. /** Destructor. */
  31295. ~DrawableButton();
  31296. /** Sets up the images to draw for the various button states.
  31297. The button will keep its own internal copies of these drawables.
  31298. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  31299. will be made of the object passed-in if it is non-zero.
  31300. @param overImage the thing to draw for the button's 'over' state - if this is
  31301. zero, the button's normal image will be used when the mouse is
  31302. over it. An internal copy will be made of the object passed-in
  31303. if it is non-zero.
  31304. @param downImage the thing to draw for the button's 'down' state - if this is
  31305. zero, the 'over' image will be used instead (or the normal image
  31306. as a last resort). An internal copy will be made of the object
  31307. passed-in if it is non-zero.
  31308. @param disabledImage an image to draw when the button is disabled. If this is zero,
  31309. the normal image will be drawn with a reduced opacity instead.
  31310. An internal copy will be made of the object passed-in if it is
  31311. non-zero.
  31312. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  31313. state is 'on'. If this is 0, the normal image is used instead
  31314. @param overImageOn same as the overImage, but this is used when the button's toggle
  31315. state is 'on'. If this is 0, the normalImageOn is drawn instead
  31316. @param downImageOn same as the downImage, but this is used when the button's toggle
  31317. state is 'on'. If this is 0, the overImageOn is drawn instead
  31318. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  31319. state is 'on'. If this is 0, the normal image will be drawn instead
  31320. with a reduced opacity
  31321. */
  31322. void setImages (const Drawable* normalImage,
  31323. const Drawable* overImage = 0,
  31324. const Drawable* downImage = 0,
  31325. const Drawable* disabledImage = 0,
  31326. const Drawable* normalImageOn = 0,
  31327. const Drawable* overImageOn = 0,
  31328. const Drawable* downImageOn = 0,
  31329. const Drawable* disabledImageOn = 0);
  31330. /** Changes the button's style.
  31331. @see ButtonStyle
  31332. */
  31333. void setButtonStyle (const ButtonStyle newStyle);
  31334. /** Changes the button's background colours.
  31335. The toggledOffColour is the colour to use when the button's toggle state
  31336. is off, and toggledOnColour when it's on.
  31337. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  31338. used to fill the background of the component.
  31339. For an ImageOnButtonBackground style, the colour is used to draw the
  31340. button's lozenge shape and exactly how the colour's used will depend
  31341. on the LookAndFeel.
  31342. */
  31343. void setBackgroundColours (const Colour& toggledOffColour,
  31344. const Colour& toggledOnColour);
  31345. /** Returns the current background colour being used.
  31346. @see setBackgroundColour
  31347. */
  31348. const Colour& getBackgroundColour() const throw();
  31349. /** Gives the button an optional amount of space around the edge of the drawable.
  31350. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  31351. ones on a button background. If the button is too small for the given gap, a
  31352. smaller gap will be used.
  31353. By default there's a gap of about 3 pixels.
  31354. */
  31355. void setEdgeIndent (const int numPixelsIndent);
  31356. /** Returns the image that the button is currently displaying. */
  31357. const Drawable* getCurrentImage() const throw();
  31358. const Drawable* getNormalImage() const throw();
  31359. const Drawable* getOverImage() const throw();
  31360. const Drawable* getDownImage() const throw();
  31361. juce_UseDebuggingNewOperator
  31362. protected:
  31363. /** @internal */
  31364. void paintButton (Graphics& g,
  31365. bool isMouseOverButton,
  31366. bool isButtonDown);
  31367. private:
  31368. ButtonStyle style;
  31369. Drawable* normalImage;
  31370. Drawable* overImage;
  31371. Drawable* downImage;
  31372. Drawable* disabledImage;
  31373. Drawable* normalImageOn;
  31374. Drawable* overImageOn;
  31375. Drawable* downImageOn;
  31376. Drawable* disabledImageOn;
  31377. Colour backgroundOff, backgroundOn;
  31378. int edgeIndent;
  31379. void deleteImages();
  31380. DrawableButton (const DrawableButton&);
  31381. const DrawableButton& operator= (const DrawableButton&);
  31382. };
  31383. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31384. /********* End of inlined file: juce_DrawableButton.h *********/
  31385. #endif
  31386. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31387. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  31388. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31389. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31390. /**
  31391. A button showing an underlined weblink, that will launch the link
  31392. when it's clicked.
  31393. @see Button
  31394. */
  31395. class JUCE_API HyperlinkButton : public Button
  31396. {
  31397. public:
  31398. /** Creates a HyperlinkButton.
  31399. @param linkText the text that will be displayed in the button - this is
  31400. also set as the Component's name, but the text can be
  31401. changed later with the Button::getButtonText() method
  31402. @param linkURL the URL to launch when the user clicks the button
  31403. */
  31404. HyperlinkButton (const String& linkText,
  31405. const URL& linkURL);
  31406. /** Destructor. */
  31407. ~HyperlinkButton();
  31408. /** Changes the font to use for the text.
  31409. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  31410. to match the size of the component.
  31411. */
  31412. void setFont (const Font& newFont,
  31413. const bool resizeToMatchComponentHeight,
  31414. const Justification& justificationType = Justification::horizontallyCentred);
  31415. /** A set of colour IDs to use to change the colour of various aspects of the link.
  31416. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31417. methods.
  31418. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31419. */
  31420. enum ColourIds
  31421. {
  31422. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  31423. };
  31424. /** Changes the URL that the button will trigger. */
  31425. void setURL (const URL& newURL) throw();
  31426. /** Returns the URL that the button will trigger. */
  31427. const URL& getURL() const throw() { return url; }
  31428. /** Resizes the button horizontally to fit snugly around the text.
  31429. This won't affect the button's height.
  31430. */
  31431. void changeWidthToFitText();
  31432. juce_UseDebuggingNewOperator
  31433. protected:
  31434. /** @internal */
  31435. void clicked();
  31436. /** @internal */
  31437. void colourChanged();
  31438. /** @internal */
  31439. void paintButton (Graphics& g,
  31440. bool isMouseOverButton,
  31441. bool isButtonDown);
  31442. private:
  31443. URL url;
  31444. Font font;
  31445. bool resizeFont;
  31446. Justification justification;
  31447. const Font getFontToUse() const;
  31448. HyperlinkButton (const HyperlinkButton&);
  31449. const HyperlinkButton& operator= (const HyperlinkButton&);
  31450. };
  31451. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  31452. /********* End of inlined file: juce_HyperlinkButton.h *********/
  31453. #endif
  31454. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  31455. /********* Start of inlined file: juce_ImageButton.h *********/
  31456. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  31457. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  31458. /**
  31459. As the title suggests, this is a button containing an image.
  31460. The colour and transparency of the image can be set to vary when the
  31461. button state changes.
  31462. @see Button, ShapeButton, TextButton
  31463. */
  31464. class JUCE_API ImageButton : public Button
  31465. {
  31466. public:
  31467. /** Creates an ImageButton.
  31468. Use setImage() to specify the image to use. The colours and opacities that
  31469. are specified here can be changed later using setDrawingOptions().
  31470. @param name the name to give the component
  31471. */
  31472. ImageButton (const String& name);
  31473. /** Destructor. */
  31474. ~ImageButton();
  31475. /** Sets up the images to draw in various states.
  31476. Important! Bear in mind that if you pass the same image in for more than one of
  31477. these parameters, this button will delete it (or release from the ImageCache)
  31478. multiple times!
  31479. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  31480. resized to the same dimensions as the normal image
  31481. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  31482. button when the button's size changes
  31483. @param preserveImageProportions if true then any rescaling of the image to fit
  31484. the button will keep the image's x and y proportions
  31485. correct - i.e. it won't distort its shape, although
  31486. this might create gaps around the edges
  31487. @param normalImage the image to use when the button is in its normal state. The
  31488. image passed in will be deleted (or released if it
  31489. was created by the ImageCache class) when the
  31490. button no longer needs it.
  31491. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  31492. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  31493. normal image - if this colour is transparent, no overlay
  31494. will be drawn. The overlay will be drawn over the top of the
  31495. image, so you can basically add a solid or semi-transparent
  31496. colour to the image to brighten or darken it
  31497. @param overImage the image to use when the mouse is over the button. If
  31498. you want to use the same image as was set in the normalImage
  31499. parameter, this value can be 0. As for normalImage, it
  31500. will be deleted or released by the button when no longer
  31501. needed
  31502. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  31503. is over the button
  31504. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  31505. image when the mouse is over - if this colour is transparent,
  31506. no overlay will be drawn
  31507. @param downImage an image to use when the button is pressed down. If set
  31508. to zero, the 'over' image will be drawn instead (or the
  31509. normal image if there isn't an 'over' image either). This
  31510. image will be deleted or released by the button when no
  31511. longer needed
  31512. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  31513. is pressed
  31514. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  31515. image when the button is pressed down - if this colour is
  31516. transparent, no overlay will be drawn
  31517. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  31518. whenever it's inside the button's bounding rectangle. If
  31519. set to values higher than 0, the mouse will only be
  31520. considered to be over the image when the value of the
  31521. image's alpha channel at that position is greater than
  31522. this level.
  31523. */
  31524. void setImages (const bool resizeButtonNowToFitThisImage,
  31525. const bool rescaleImagesWhenButtonSizeChanges,
  31526. const bool preserveImageProportions,
  31527. Image* const normalImage,
  31528. const float imageOpacityWhenNormal,
  31529. const Colour& overlayColourWhenNormal,
  31530. Image* const overImage,
  31531. const float imageOpacityWhenOver,
  31532. const Colour& overlayColourWhenOver,
  31533. Image* const downImage,
  31534. const float imageOpacityWhenDown,
  31535. const Colour& overlayColourWhenDown,
  31536. const float hitTestAlphaThreshold = 0.0f);
  31537. /** Returns the currently set 'normal' image. */
  31538. Image* getNormalImage() const throw();
  31539. /** Returns the image that's drawn when the mouse is over the button.
  31540. If an 'over' image has been set, this will return it; otherwise it'll
  31541. just return the normal image.
  31542. */
  31543. Image* getOverImage() const throw();
  31544. /** Returns the image that's drawn when the button is held down.
  31545. If a 'down' image has been set, this will return it; otherwise it'll
  31546. return the 'over' image or normal image, depending on what's available.
  31547. */
  31548. Image* getDownImage() const throw();
  31549. juce_UseDebuggingNewOperator
  31550. protected:
  31551. /** @internal */
  31552. bool hitTest (int x, int y);
  31553. /** @internal */
  31554. void paintButton (Graphics& g,
  31555. bool isMouseOverButton,
  31556. bool isButtonDown);
  31557. private:
  31558. bool scaleImageToFit, preserveProportions;
  31559. unsigned char alphaThreshold;
  31560. int imageX, imageY, imageW, imageH;
  31561. Image* normalImage;
  31562. Image* overImage;
  31563. Image* downImage;
  31564. float normalOpacity, overOpacity, downOpacity;
  31565. Colour normalOverlay, overOverlay, downOverlay;
  31566. Image* getCurrentImage() const;
  31567. void deleteImages();
  31568. ImageButton (const ImageButton&);
  31569. const ImageButton& operator= (const ImageButton&);
  31570. };
  31571. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  31572. /********* End of inlined file: juce_ImageButton.h *********/
  31573. #endif
  31574. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31575. /********* Start of inlined file: juce_ShapeButton.h *********/
  31576. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  31577. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  31578. /**
  31579. A button that contains a filled shape.
  31580. @see Button, ImageButton, TextButton, ArrowButton
  31581. */
  31582. class JUCE_API ShapeButton : public Button
  31583. {
  31584. public:
  31585. /** Creates a ShapeButton.
  31586. @param name a name to give the component - see Component::setName()
  31587. @param normalColour the colour to fill the shape with when the mouse isn't over
  31588. @param overColour the colour to use when the mouse is over the shape
  31589. @param downColour the colour to use when the button is in the pressed-down state
  31590. */
  31591. ShapeButton (const String& name,
  31592. const Colour& normalColour,
  31593. const Colour& overColour,
  31594. const Colour& downColour);
  31595. /** Destructor. */
  31596. ~ShapeButton();
  31597. /** Sets the shape to use.
  31598. @param newShape the shape to use
  31599. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  31600. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  31601. the button is resized
  31602. @param hasDropShadow if true, the button will be given a drop-shadow effect
  31603. */
  31604. void setShape (const Path& newShape,
  31605. const bool resizeNowToFitThisShape,
  31606. const bool maintainShapeProportions,
  31607. const bool hasDropShadow);
  31608. /** Set the colours to use for drawing the shape.
  31609. @param normalColour the colour to fill the shape with when the mouse isn't over
  31610. @param overColour the colour to use when the mouse is over the shape
  31611. @param downColour the colour to use when the button is in the pressed-down state
  31612. */
  31613. void setColours (const Colour& normalColour,
  31614. const Colour& overColour,
  31615. const Colour& downColour);
  31616. /** Sets up an outline to draw around the shape.
  31617. @param outlineColour the colour to use
  31618. @param outlineStrokeWidth the thickness of line to draw
  31619. */
  31620. void setOutline (const Colour& outlineColour,
  31621. const float outlineStrokeWidth);
  31622. juce_UseDebuggingNewOperator
  31623. protected:
  31624. /** @internal */
  31625. void paintButton (Graphics& g,
  31626. bool isMouseOverButton,
  31627. bool isButtonDown);
  31628. private:
  31629. Colour normalColour, overColour, downColour, outlineColour;
  31630. DropShadowEffect shadow;
  31631. Path shape;
  31632. bool maintainShapeProportions;
  31633. float outlineWidth;
  31634. ShapeButton (const ShapeButton&);
  31635. const ShapeButton& operator= (const ShapeButton&);
  31636. };
  31637. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  31638. /********* End of inlined file: juce_ShapeButton.h *********/
  31639. #endif
  31640. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  31641. #endif
  31642. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31643. /********* Start of inlined file: juce_ToggleButton.h *********/
  31644. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31645. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31646. /**
  31647. A button that can be toggled on/off.
  31648. All buttons can be toggle buttons, but this lets you create one of the
  31649. standard ones which has a tick-box and a text label next to it.
  31650. @see Button, DrawableButton, TextButton
  31651. */
  31652. class JUCE_API ToggleButton : public Button
  31653. {
  31654. public:
  31655. /** Creates a ToggleButton.
  31656. @param buttonText the text to put in the button (the component's name is also
  31657. initially set to this string, but these can be changed later
  31658. using the setName() and setButtonText() methods)
  31659. */
  31660. ToggleButton (const String& buttonText);
  31661. /** Destructor. */
  31662. ~ToggleButton();
  31663. /** Resizes the button to fit neatly around its current text.
  31664. The button's height won't be affected, only its width.
  31665. */
  31666. void changeWidthToFitText();
  31667. /** A set of colour IDs to use to change the colour of various aspects of the button.
  31668. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31669. methods.
  31670. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31671. */
  31672. enum ColourIds
  31673. {
  31674. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  31675. };
  31676. juce_UseDebuggingNewOperator
  31677. protected:
  31678. /** @internal */
  31679. void paintButton (Graphics& g,
  31680. bool isMouseOverButton,
  31681. bool isButtonDown);
  31682. /** @internal */
  31683. void colourChanged();
  31684. private:
  31685. ToggleButton (const ToggleButton&);
  31686. const ToggleButton& operator= (const ToggleButton&);
  31687. };
  31688. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  31689. /********* End of inlined file: juce_ToggleButton.h *********/
  31690. #endif
  31691. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31692. /********* Start of inlined file: juce_ToolbarButton.h *********/
  31693. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31694. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31695. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  31696. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31697. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31698. /********* Start of inlined file: juce_Toolbar.h *********/
  31699. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  31700. #define __JUCE_TOOLBAR_JUCEHEADER__
  31701. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  31702. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31703. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31704. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  31705. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31706. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31707. /**
  31708. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  31709. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  31710. derive your component from this class, and make sure that it is somewhere inside a
  31711. DragAndDropContainer component.
  31712. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31713. the operating system onto your component, you don't need any of these classes: instead
  31714. see the FileDragAndDropTarget class.
  31715. @see DragAndDropContainer, FileDragAndDropTarget
  31716. */
  31717. class JUCE_API DragAndDropTarget
  31718. {
  31719. public:
  31720. /** Destructor. */
  31721. virtual ~DragAndDropTarget() {}
  31722. /** Callback to check whether this target is interested in the type of object being
  31723. dragged.
  31724. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31725. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31726. @returns true if this component wants to receive the other callbacks regarging this
  31727. type of object; if it returns false, no other callbacks will be made.
  31728. */
  31729. virtual bool isInterestedInDragSource (const String& sourceDescription,
  31730. Component* sourceComponent) = 0;
  31731. /** Callback to indicate that something is being dragged over this component.
  31732. This gets called when the user moves the mouse into this component while dragging
  31733. something.
  31734. Use this callback as a trigger to make your component repaint itself to give the
  31735. user feedback about whether the item can be dropped here or not.
  31736. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31737. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31738. @param x the mouse x position, relative to this component
  31739. @param y the mouse y position, relative to this component
  31740. @see itemDragExit
  31741. */
  31742. virtual void itemDragEnter (const String& sourceDescription,
  31743. Component* sourceComponent,
  31744. int x,
  31745. int y);
  31746. /** Callback to indicate that the user is dragging something over this component.
  31747. This gets called when the user moves the mouse over this component while dragging
  31748. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  31749. this lets you know what happens in-between.
  31750. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31751. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31752. @param x the mouse x position, relative to this component
  31753. @param y the mouse y position, relative to this component
  31754. */
  31755. virtual void itemDragMove (const String& sourceDescription,
  31756. Component* sourceComponent,
  31757. int x,
  31758. int y);
  31759. /** Callback to indicate that something has been dragged off the edge of this component.
  31760. This gets called when the user moves the mouse out of this component while dragging
  31761. something.
  31762. If you've used itemDragEnter() to repaint your component and give feedback, use this
  31763. as a signal to repaint it in its normal state.
  31764. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31765. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31766. @see itemDragEnter
  31767. */
  31768. virtual void itemDragExit (const String& sourceDescription,
  31769. Component* sourceComponent);
  31770. /** Callback to indicate that the user has dropped something onto this component.
  31771. When the user drops an item this get called, and you can use the description to
  31772. work out whether your object wants to deal with it or not.
  31773. Note that after this is called, the itemDragExit method may not be called, so you should
  31774. clean up in here if there's anything you need to do when the drag finishes.
  31775. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  31776. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  31777. @param x the mouse x position, relative to this component
  31778. @param y the mouse y position, relative to this component
  31779. */
  31780. virtual void itemDropped (const String& sourceDescription,
  31781. Component* sourceComponent,
  31782. int x,
  31783. int y) = 0;
  31784. /** Overriding this allows the target to tell the drag container whether to
  31785. draw the drag image while the cursor is over it.
  31786. By default it returns true, but if you return false, then the normal drag
  31787. image will not be shown when the cursor is over this target.
  31788. */
  31789. virtual bool shouldDrawDragImageWhenOver();
  31790. };
  31791. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  31792. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  31793. /**
  31794. Enables drag-and-drop behaviour for a component and all its sub-components.
  31795. For a component to be able to make or receive drag-and-drop events, one of its parent
  31796. components must derive from this class. It's probably best for the top-level
  31797. component to implement it.
  31798. Then to start a drag operation, any sub-component can just call the startDragging()
  31799. method, and this object will take over, tracking the mouse and sending appropriate
  31800. callbacks to any child components derived from DragAndDropTarget which the mouse
  31801. moves over.
  31802. Note: If all that you need to do is to respond to files being drag-and-dropped from
  31803. the operating system onto your component, you don't need any of these classes: you can do this
  31804. simply by overriding Component::filesDropped().
  31805. @see DragAndDropTarget
  31806. */
  31807. class JUCE_API DragAndDropContainer
  31808. {
  31809. public:
  31810. /** Creates a DragAndDropContainer.
  31811. The object that derives from this class must also be a Component.
  31812. */
  31813. DragAndDropContainer();
  31814. /** Destructor. */
  31815. virtual ~DragAndDropContainer();
  31816. /** Begins a drag-and-drop operation.
  31817. This starts a drag-and-drop operation - call it when the user drags the
  31818. mouse in your drag-source component, and this object will track mouse
  31819. movements until the user lets go of the mouse button, and will send
  31820. appropriate messages to DragAndDropTarget objects that the mouse moves
  31821. over.
  31822. findParentDragContainerFor() is a handy method to call to find the
  31823. drag container to use for a component.
  31824. @param sourceDescription a string to use as the description of the thing being
  31825. dragged - this will be passed to the objects that might be
  31826. dropped-onto so they can decide if they want to handle it or
  31827. not
  31828. @param sourceComponent the component that is being dragged
  31829. @param dragImage the image to drag around underneath the mouse. If this is
  31830. zero, a snapshot of the sourceComponent will be used instead. An
  31831. image passed-in will be deleted by this object when no longer
  31832. needed.
  31833. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  31834. window, and can be dragged to DragAndDropTargets that are the
  31835. children of components other than this one.
  31836. */
  31837. void startDragging (const String& sourceDescription,
  31838. Component* sourceComponent,
  31839. Image* dragImage = 0,
  31840. const bool allowDraggingToOtherJuceWindows = false);
  31841. /** Returns true if something is currently being dragged. */
  31842. bool isDragAndDropActive() const;
  31843. /** Returns the description of the thing that's currently being dragged.
  31844. If nothing's being dragged, this will return an empty string, otherwise it's the
  31845. string that was passed into startDragging().
  31846. @see startDragging
  31847. */
  31848. const String getCurrentDragDescription() const;
  31849. /** Utility to find the DragAndDropContainer for a given Component.
  31850. This will search up this component's parent hierarchy looking for the first
  31851. parent component which is a DragAndDropContainer.
  31852. It's useful when a component wants to call startDragging but doesn't know
  31853. the DragAndDropContainer it should to use.
  31854. Obviously this may return 0 if it doesn't find a suitable component.
  31855. */
  31856. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  31857. /** This performs a synchronous drag-and-drop of a set of files to some external
  31858. application.
  31859. You can call this function in response to a mouseDrag callback, and it will
  31860. block, running its own internal message loop and tracking the mouse, while it
  31861. uses a native operating system drag-and-drop operation to move or copy some
  31862. files to another application.
  31863. @param files a list of filenames to drag
  31864. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  31865. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  31866. @returns true if the files were successfully dropped somewhere, or false if it
  31867. was interrupted
  31868. @see performExternalDragDropOfText
  31869. */
  31870. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  31871. /** This performs a synchronous drag-and-drop of a block of text to some external
  31872. application.
  31873. You can call this function in response to a mouseDrag callback, and it will
  31874. block, running its own internal message loop and tracking the mouse, while it
  31875. uses a native operating system drag-and-drop operation to move or copy some
  31876. text to another application.
  31877. @param text the text to copy
  31878. @returns true if the text was successfully dropped somewhere, or false if it
  31879. was interrupted
  31880. @see performExternalDragDropOfFiles
  31881. */
  31882. static bool performExternalDragDropOfText (const String& text);
  31883. juce_UseDebuggingNewOperator
  31884. protected:
  31885. /** Override this if you want to be able to perform an external drag a set of files
  31886. when the user drags outside of this container component.
  31887. This method will be called when a drag operation moves outside the Juce-based window,
  31888. and if you want it to then perform a file drag-and-drop, add the filenames you want
  31889. to the array passed in, and return true.
  31890. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  31891. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  31892. @param files on return, the filenames you want to drag
  31893. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  31894. it must make a copy of them (see the performExternalDragDropOfFiles()
  31895. method)
  31896. @see performExternalDragDropOfFiles
  31897. */
  31898. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  31899. Component* dragSourceComponent,
  31900. StringArray& files,
  31901. bool& canMoveFiles);
  31902. private:
  31903. friend class DragImageComponent;
  31904. Component* dragImageComponent;
  31905. String currentDragDesc;
  31906. };
  31907. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  31908. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  31909. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  31910. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31911. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31912. /**
  31913. Animates a set of components, moving it to a new position.
  31914. To use this, create a ComponentAnimator, and use its animateComponent() method
  31915. to tell it to move components to destination positions. Any number of
  31916. components can be animated by one ComponentAnimator object (if you've got a
  31917. lot of components to move, it's much more efficient to share a single animator
  31918. than to have many animators running at once).
  31919. You'll need to make sure the animator object isn't deleted before it finishes
  31920. moving the components.
  31921. The class is a ChangeBroadcaster and sends a notification when any components
  31922. start or finish being animated.
  31923. */
  31924. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  31925. private Timer
  31926. {
  31927. public:
  31928. /** Creates a ComponentAnimator. */
  31929. ComponentAnimator();
  31930. /** Destructor. */
  31931. ~ComponentAnimator();
  31932. /** Starts a component moving from its current position to a specified position.
  31933. If the component is already in the middle of an animation, that will be abandoned,
  31934. and a new animation will begin, moving the component from its current location.
  31935. The start and end speed parameters let you apply some acceleration to the component's
  31936. movement.
  31937. @param component the component to move
  31938. @param finalPosition the destination position and size to move it to
  31939. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  31940. to arrive at its destination
  31941. @param startSpeed a value to indicate the relative start speed of the
  31942. animation. If this is 0, the component will start
  31943. by accelerating from rest; higher values mean that it
  31944. will have an initial speed greater than zero. If the
  31945. value if greater than 1, it will decelerate towards the
  31946. middle of its journey. To move the component at a constant
  31947. rate for its entire animation, set both the start and
  31948. end speeds to 1.0
  31949. @param endSpeed a relative speed at which the component should be moving
  31950. when the animation finishes. If this is 0, the component
  31951. will decelerate to a standstill at its final position; higher
  31952. values mean the component will still be moving when it stops.
  31953. To move the component at a constant rate for its entire
  31954. animation, set both the start and end speeds to 1.0
  31955. */
  31956. void animateComponent (Component* const component,
  31957. const Rectangle& finalPosition,
  31958. const int millisecondsToSpendMoving,
  31959. const double startSpeed = 1.0,
  31960. const double endSpeed = 1.0);
  31961. /** Stops a component if it's currently being animated.
  31962. If moveComponentToItsFinalPosition is true, then the component will
  31963. be immediately moved to its destination position and size. If false, it will be
  31964. left in whatever location it currently occupies.
  31965. */
  31966. void cancelAnimation (Component* const component,
  31967. const bool moveComponentToItsFinalPosition);
  31968. /** Clears all of the active animations.
  31969. If moveComponentsToTheirFinalPositions is true, all the components will
  31970. be immediately set to their final positions. If false, they will be
  31971. left in whatever locations they currently occupy.
  31972. */
  31973. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  31974. /** Returns the destination position for a component.
  31975. If the component is being animated, this will return the target position that
  31976. was specified when animateComponent() was called.
  31977. If the specified component isn't currently being animated, this method will just
  31978. return its current position.
  31979. */
  31980. const Rectangle getComponentDestination (Component* const component);
  31981. /** Returns true if the specified component is currently being animated.
  31982. */
  31983. bool isAnimating (Component* component) const;
  31984. juce_UseDebuggingNewOperator
  31985. private:
  31986. VoidArray tasks;
  31987. uint32 lastTime;
  31988. void* findTaskFor (Component* const component) const;
  31989. void timerCallback();
  31990. };
  31991. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  31992. /********* End of inlined file: juce_ComponentAnimator.h *********/
  31993. class ToolbarItemComponent;
  31994. class ToolbarItemFactory;
  31995. class MissingItemsComponent;
  31996. /**
  31997. A toolbar component.
  31998. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  31999. and looks after their order and layout.
  32000. Items (icon buttons or other custom components) are added to a toolbar using a
  32001. ToolbarItemFactory - each type of item is given a unique ID number, and a
  32002. toolbar might contain more than one instance of a particular item type.
  32003. Toolbars can be interactively customised, allowing the user to drag the items
  32004. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  32005. component as a source of new items.
  32006. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  32007. */
  32008. class JUCE_API Toolbar : public Component,
  32009. public DragAndDropContainer,
  32010. public DragAndDropTarget,
  32011. private ButtonListener
  32012. {
  32013. public:
  32014. /** Creates an empty toolbar component.
  32015. To add some icons or other components to your toolbar, you'll need to
  32016. create a ToolbarItemFactory class that can create a suitable set of
  32017. ToolbarItemComponents.
  32018. @see ToolbarItemFactory, ToolbarItemComponents
  32019. */
  32020. Toolbar();
  32021. /** Destructor.
  32022. Any items on the bar will be deleted when the toolbar is deleted.
  32023. */
  32024. ~Toolbar();
  32025. /** Changes the bar's orientation.
  32026. @see isVertical
  32027. */
  32028. void setVertical (const bool shouldBeVertical);
  32029. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  32030. You can change the bar's orientation with setVertical().
  32031. */
  32032. bool isVertical() const throw() { return vertical; }
  32033. /** Returns the depth of the bar.
  32034. If the bar is horizontal, this will return its height; if it's vertical, it
  32035. will return its width.
  32036. @see getLength
  32037. */
  32038. int getThickness() const throw();
  32039. /** Returns the length of the bar.
  32040. If the bar is horizontal, this will return its width; if it's vertical, it
  32041. will return its height.
  32042. @see getThickness
  32043. */
  32044. int getLength() const throw();
  32045. /** Deletes all items from the bar.
  32046. */
  32047. void clear();
  32048. /** Adds an item to the toolbar.
  32049. The factory's ToolbarItemFactory::createItem() will be called by this method
  32050. to create the component that will actually be added to the bar.
  32051. The new item will be inserted at the specified index (if the index is -1, it
  32052. will be added to the right-hand or bottom end of the bar).
  32053. Once added, the component will be automatically deleted by this object when it
  32054. is no longer needed.
  32055. @see ToolbarItemFactory
  32056. */
  32057. void addItem (ToolbarItemFactory& factory,
  32058. const int itemId,
  32059. const int insertIndex = -1);
  32060. /** Deletes one of the items from the bar.
  32061. */
  32062. void removeToolbarItem (const int itemIndex);
  32063. /** Returns the number of items currently on the toolbar.
  32064. @see getItemId, getItemComponent
  32065. */
  32066. int getNumItems() const throw();
  32067. /** Returns the ID of the item with the given index.
  32068. If the index is less than zero or greater than the number of items,
  32069. this will return 0.
  32070. @see getNumItems
  32071. */
  32072. int getItemId (const int itemIndex) const throw();
  32073. /** Returns the component being used for the item with the given index.
  32074. If the index is less than zero or greater than the number of items,
  32075. this will return 0.
  32076. @see getNumItems
  32077. */
  32078. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  32079. /** Clears this toolbar and adds to it the default set of items that the specified
  32080. factory creates.
  32081. @see ToolbarItemFactory::getDefaultItemSet
  32082. */
  32083. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  32084. /** Options for the way items should be displayed.
  32085. @see setStyle, getStyle
  32086. */
  32087. enum ToolbarItemStyle
  32088. {
  32089. iconsOnly, /**< Means that the toolbar should just contain icons. */
  32090. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  32091. textOnly /**< Means that the toolbar only display text labels for each item. */
  32092. };
  32093. /** Returns the toolbar's current style.
  32094. @see ToolbarItemStyle, setStyle
  32095. */
  32096. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32097. /** Changes the toolbar's current style.
  32098. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  32099. */
  32100. void setStyle (const ToolbarItemStyle& newStyle);
  32101. /** Flags used by the showCustomisationDialog() method. */
  32102. enum CustomisationFlags
  32103. {
  32104. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  32105. show the "icons only" option on its choice of toolbar styles. */
  32106. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  32107. show the "icons with text" option on its choice of toolbar styles. */
  32108. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  32109. show the "text only" option on its choice of toolbar styles. */
  32110. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  32111. show a button to reset the toolbar to its default set of items. */
  32112. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  32113. };
  32114. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  32115. The dialog contains a ToolbarItemPalette and various controls for editing other
  32116. aspects of the toolbar. This method will block and run the dialog box modally,
  32117. returning when the user closes it.
  32118. The factory is used to determine the set of items that will be shown on the
  32119. palette.
  32120. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  32121. enum.
  32122. @see ToolbarItemPalette
  32123. */
  32124. void showCustomisationDialog (ToolbarItemFactory& factory,
  32125. const int optionFlags = allCustomisationOptionsEnabled);
  32126. /** Turns on or off the toolbar's editing mode, in which its items can be
  32127. rearranged by the user.
  32128. (In most cases it's easier just to use showCustomisationDialog() instead of
  32129. trying to enable editing directly).
  32130. @see ToolbarItemPalette
  32131. */
  32132. void setEditingActive (const bool editingEnabled);
  32133. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  32134. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32135. methods.
  32136. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32137. */
  32138. enum ColourIds
  32139. {
  32140. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  32141. more control over this, override LookAndFeel::paintToolbarBackground(). */
  32142. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  32143. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  32144. over them. */
  32145. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  32146. held down on them. */
  32147. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  32148. when the style is set to iconsWithText or textOnly. */
  32149. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  32150. the customisation dialog is active and the mouse moves over them. */
  32151. };
  32152. /** Returns a string that represents the toolbar's current set of items.
  32153. This lets you later restore the same item layout using restoreFromString().
  32154. @see restoreFromString
  32155. */
  32156. const String toString() const;
  32157. /** Restores a set of items that was previously stored in a string by the toString()
  32158. method.
  32159. The factory object is used to create any item components that are needed.
  32160. @see toString
  32161. */
  32162. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  32163. const String& savedVersion);
  32164. /** @internal */
  32165. void paint (Graphics& g);
  32166. /** @internal */
  32167. void resized();
  32168. /** @internal */
  32169. void buttonClicked (Button*);
  32170. /** @internal */
  32171. void mouseDown (const MouseEvent&);
  32172. /** @internal */
  32173. bool isInterestedInDragSource (const String&, Component*);
  32174. /** @internal */
  32175. void itemDragMove (const String&, Component*, int, int);
  32176. /** @internal */
  32177. void itemDragExit (const String&, Component*);
  32178. /** @internal */
  32179. void itemDropped (const String&, Component*, int, int);
  32180. /** @internal */
  32181. void updateAllItemPositions (const bool animate);
  32182. /** @internal */
  32183. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  32184. juce_UseDebuggingNewOperator
  32185. private:
  32186. Button* missingItemsButton;
  32187. bool vertical, isEditingActive;
  32188. ToolbarItemStyle toolbarStyle;
  32189. ComponentAnimator animator;
  32190. friend class MissingItemsComponent;
  32191. Array <ToolbarItemComponent*> items;
  32192. friend class ItemDragAndDropOverlayComponent;
  32193. static const tchar* const toolbarDragDescriptor;
  32194. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  32195. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  32196. Toolbar (const Toolbar&);
  32197. const Toolbar& operator= (const Toolbar&);
  32198. };
  32199. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  32200. /********* End of inlined file: juce_Toolbar.h *********/
  32201. class ItemDragAndDropOverlayComponent;
  32202. /**
  32203. A component that can be used as one of the items in a Toolbar.
  32204. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  32205. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  32206. class for further info about creating them.
  32207. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  32208. components too. To do this, set the value of isBeingUsedAsAButton to false when
  32209. calling the constructor, and override contentAreaChanged(), in which you can position
  32210. any sub-components you need to add.
  32211. To add basic buttons without writing a special subclass, have a look at the
  32212. ToolbarButton class.
  32213. @see ToolbarButton, Toolbar, ToolbarItemFactory
  32214. */
  32215. class JUCE_API ToolbarItemComponent : public Button
  32216. {
  32217. public:
  32218. /** Constructor.
  32219. @param itemId the ID of the type of toolbar item which this represents
  32220. @param labelText the text to display if the toolbar's style is set to
  32221. Toolbar::iconsWithText or Toolbar::textOnly
  32222. @param isBeingUsedAsAButton set this to false if you don't want the button
  32223. to draw itself with button over/down states when the mouse
  32224. moves over it or clicks
  32225. */
  32226. ToolbarItemComponent (const int itemId,
  32227. const String& labelText,
  32228. const bool isBeingUsedAsAButton);
  32229. /** Destructor. */
  32230. ~ToolbarItemComponent();
  32231. /** Returns the item type ID that this component represents.
  32232. This value is in the constructor.
  32233. */
  32234. int getItemId() const throw() { return itemId; }
  32235. /** Returns the toolbar that contains this component, or 0 if it's not currently
  32236. inside one.
  32237. */
  32238. Toolbar* getToolbar() const;
  32239. /** Returns true if this component is currently inside a toolbar which is vertical.
  32240. @see Toolbar::isVertical
  32241. */
  32242. bool isToolbarVertical() const;
  32243. /** Returns the current style setting of this item.
  32244. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  32245. @see setStyle, Toolbar::getStyle
  32246. */
  32247. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32248. /** Changes the current style setting of this item.
  32249. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  32250. by the toolbar that holds this item.
  32251. @see setStyle, Toolbar::setStyle
  32252. */
  32253. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  32254. /** Returns the area of the component that should be used to display the button image or
  32255. other contents of the item.
  32256. This content area may change when the item's style changes, and may leave a space around the
  32257. edge of the component where the text label can be shown.
  32258. @see contentAreaChanged
  32259. */
  32260. const Rectangle getContentArea() const throw() { return contentArea; }
  32261. /** This method must return the size criteria for this item, based on a given toolbar
  32262. size and orientation.
  32263. The preferredSize, minSize and maxSize values must all be set by your implementation
  32264. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  32265. toolbar, they refer to the item's height.
  32266. The preferredSize is the size that the component would like to be, and this must be
  32267. between the min and max sizes. For a fixed-size item, simply set all three variables to
  32268. the same value.
  32269. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  32270. Toolbar::getThickness().
  32271. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  32272. vertically.
  32273. */
  32274. virtual bool getToolbarItemSizes (int toolbarThickness,
  32275. bool isToolbarVertical,
  32276. int& preferredSize,
  32277. int& minSize,
  32278. int& maxSize) = 0;
  32279. /** Your subclass should use this method to draw its content area.
  32280. The graphics object that is passed-in will have been clipped and had its origin
  32281. moved to fit the content area as specified get getContentArea(). The width and height
  32282. parameters are the width and height of the content area.
  32283. If the component you're writing isn't a button, you can just do nothing in this method.
  32284. */
  32285. virtual void paintButtonArea (Graphics& g,
  32286. int width, int height,
  32287. bool isMouseOver, bool isMouseDown) = 0;
  32288. /** Callback to indicate that the content area of this item has changed.
  32289. This might be because the component was resized, or because the style changed and
  32290. the space needed for the text label is different.
  32291. See getContentArea() for a description of what the area is.
  32292. */
  32293. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  32294. /** Editing modes.
  32295. These are used by setEditingMode(), but will be rarely needed in user code.
  32296. */
  32297. enum ToolbarEditingMode
  32298. {
  32299. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  32300. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  32301. customisation mode, and the items can be dragged around. */
  32302. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  32303. dragged onto a toolbar to add it to that bar.*/
  32304. };
  32305. /** Changes the editing mode of this component.
  32306. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32307. and is unlikely to be of much use in end-user-code.
  32308. */
  32309. void setEditingMode (const ToolbarEditingMode newMode);
  32310. /** Returns the current editing mode of this component.
  32311. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32312. and is unlikely to be of much use in end-user-code.
  32313. */
  32314. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  32315. /** @internal */
  32316. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  32317. /** @internal */
  32318. void resized();
  32319. juce_UseDebuggingNewOperator
  32320. private:
  32321. friend class Toolbar;
  32322. friend class ItemDragAndDropOverlayComponent;
  32323. const int itemId;
  32324. ToolbarEditingMode mode;
  32325. Toolbar::ToolbarItemStyle toolbarStyle;
  32326. Component* overlayComp;
  32327. int dragOffsetX, dragOffsetY;
  32328. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  32329. Rectangle contentArea;
  32330. ToolbarItemComponent (const ToolbarItemComponent&);
  32331. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  32332. };
  32333. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32334. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  32335. /**
  32336. A type of button designed to go on a toolbar.
  32337. This simple button can have two Drawable objects specified - one for normal
  32338. use and another one (optionally) for the button's "on" state if it's a
  32339. toggle button.
  32340. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  32341. */
  32342. class JUCE_API ToolbarButton : public ToolbarItemComponent
  32343. {
  32344. public:
  32345. /** Creates a ToolbarButton.
  32346. @param itemId the ID for this toolbar item type. This is passed through to the
  32347. ToolbarItemComponent constructor
  32348. @param labelText the text to display on the button (if the toolbar is using a style
  32349. that shows text labels). This is passed through to the
  32350. ToolbarItemComponent constructor
  32351. @param normalImage a drawable object that the button should use as its icon. The object
  32352. that is passed-in here will be kept by this object and will be
  32353. deleted when no longer needed or when this button is deleted.
  32354. @param toggledOnImage a drawable object that the button can use as its icon if the button
  32355. is in a toggled-on state (see the Button::getToggleState() method). If
  32356. 0 is passed-in here, then the normal image will be used instead, regardless
  32357. of the toggle state. The object that is passed-in here will be kept by
  32358. this object and will be deleted when no longer needed or when this button
  32359. is deleted.
  32360. */
  32361. ToolbarButton (const int itemId,
  32362. const String& labelText,
  32363. Drawable* const normalImage,
  32364. Drawable* const toggledOnImage);
  32365. /** Destructor. */
  32366. ~ToolbarButton();
  32367. /** @internal */
  32368. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  32369. int& minSize, int& maxSize);
  32370. /** @internal */
  32371. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  32372. /** @internal */
  32373. void contentAreaChanged (const Rectangle& newBounds);
  32374. juce_UseDebuggingNewOperator
  32375. private:
  32376. Drawable* const normalImage;
  32377. Drawable* const toggledOnImage;
  32378. ToolbarButton (const ToolbarButton&);
  32379. const ToolbarButton& operator= (const ToolbarButton&);
  32380. };
  32381. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32382. /********* End of inlined file: juce_ToolbarButton.h *********/
  32383. #endif
  32384. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  32385. #endif
  32386. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  32387. /********* Start of inlined file: juce_GlowEffect.h *********/
  32388. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  32389. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  32390. /**
  32391. A component effect that adds a coloured blur around the component's contents.
  32392. (This will only work on non-opaque components).
  32393. @see Component::setComponentEffect, DropShadowEffect
  32394. */
  32395. class JUCE_API GlowEffect : public ImageEffectFilter
  32396. {
  32397. public:
  32398. /** Creates a default 'glow' effect.
  32399. To customise its appearance, use the setGlowProperties() method.
  32400. */
  32401. GlowEffect();
  32402. /** Destructor. */
  32403. ~GlowEffect();
  32404. /** Sets the glow's radius and colour.
  32405. The radius is how large the blur should be, and the colour is
  32406. used to render it (for a less intense glow, lower the colour's
  32407. opacity).
  32408. */
  32409. void setGlowProperties (const float newRadius,
  32410. const Colour& newColour);
  32411. /** @internal */
  32412. void applyEffect (Image& sourceImage, Graphics& destContext);
  32413. juce_UseDebuggingNewOperator
  32414. private:
  32415. float radius;
  32416. Colour colour;
  32417. };
  32418. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  32419. /********* End of inlined file: juce_GlowEffect.h *********/
  32420. #endif
  32421. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  32422. #endif
  32423. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32424. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  32425. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32426. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32427. /**
  32428. An effect filter that reduces the image's opacity.
  32429. This can be used to make a component (and its child components) more
  32430. transparent.
  32431. @see Component::setComponentEffect
  32432. */
  32433. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  32434. {
  32435. public:
  32436. /** Creates the effect object.
  32437. The opacity of the component to which the effect is applied will be
  32438. scaled by the given factor (in the range 0 to 1.0f).
  32439. */
  32440. ReduceOpacityEffect (const float opacity = 1.0f);
  32441. /** Destructor. */
  32442. ~ReduceOpacityEffect();
  32443. /** Sets how much to scale the component's opacity.
  32444. @param newOpacity should be between 0 and 1.0f
  32445. */
  32446. void setOpacity (const float newOpacity);
  32447. /** @internal */
  32448. void applyEffect (Image& sourceImage, Graphics& destContext);
  32449. juce_UseDebuggingNewOperator
  32450. private:
  32451. float opacity;
  32452. };
  32453. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  32454. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  32455. #endif
  32456. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  32457. #endif
  32458. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32459. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  32460. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32461. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  32462. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  32463. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32464. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32465. /**
  32466. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  32467. command in a ApplicationCommandManager.
  32468. Normally, you won't actually create a KeyPressMappingSet directly, because
  32469. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  32470. you'd create yourself an ApplicationCommandManager, and call its
  32471. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  32472. KeyPressMappingSet.
  32473. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  32474. to the top-level component for which you want to handle keystrokes. So for example:
  32475. @code
  32476. class MyMainWindow : public Component
  32477. {
  32478. ApplicationCommandManager* myCommandManager;
  32479. public:
  32480. MyMainWindow()
  32481. {
  32482. myCommandManager = new ApplicationCommandManager();
  32483. // first, make sure the command manager has registered all the commands that its
  32484. // targets can perform..
  32485. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  32486. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  32487. // this will use the command manager to initialise the KeyPressMappingSet with
  32488. // the default keypresses that were specified when the targets added their commands
  32489. // to the manager.
  32490. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  32491. // having set up the default key-mappings, you might now want to load the last set
  32492. // of mappings that the user configured.
  32493. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  32494. // Now tell our top-level window to send any keypresses that arrive to the
  32495. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  32496. addKeyListener (myCommandManager->getKeyMappings());
  32497. }
  32498. ...
  32499. }
  32500. @endcode
  32501. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  32502. register to be told when a command or mapping is added, removed, etc.
  32503. There's also a UI component called KeyMappingEditorComponent that can be used
  32504. to easily edit the key mappings.
  32505. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  32506. */
  32507. class JUCE_API KeyPressMappingSet : public KeyListener,
  32508. public ChangeBroadcaster,
  32509. public FocusChangeListener
  32510. {
  32511. public:
  32512. /** Creates a KeyPressMappingSet for a given command manager.
  32513. Normally, you won't actually create a KeyPressMappingSet directly, because
  32514. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  32515. best thing to do is to create your ApplicationCommandManager, and use the
  32516. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  32517. When a suitable keypress happens, the manager's invoke() method will be
  32518. used to invoke the appropriate command.
  32519. @see ApplicationCommandManager
  32520. */
  32521. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  32522. /** Creates an copy of a KeyPressMappingSet. */
  32523. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  32524. /** Destructor. */
  32525. ~KeyPressMappingSet();
  32526. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  32527. /** Returns a list of keypresses that are assigned to a particular command.
  32528. @param commandID the command's ID
  32529. */
  32530. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  32531. /** Assigns a keypress to a command.
  32532. If the keypress is already assigned to a different command, it will first be
  32533. removed from that command, to avoid it triggering multiple functions.
  32534. @param commandID the ID of the command that you want to add a keypress to. If
  32535. this is 0, the keypress will be removed from anything that it
  32536. was previously assigned to, but not re-assigned
  32537. @param newKeyPress the new key-press
  32538. @param insertIndex if this is less than zero, the key will be appended to the
  32539. end of the list of keypresses; otherwise the new keypress will
  32540. be inserted into the existing list at this index
  32541. */
  32542. void addKeyPress (const CommandID commandID,
  32543. const KeyPress& newKeyPress,
  32544. int insertIndex = -1) throw();
  32545. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  32546. @see resetToDefaultMapping
  32547. */
  32548. void resetToDefaultMappings() throw();
  32549. /** Resets all key-mappings to the defaults for a particular command.
  32550. @see resetToDefaultMappings
  32551. */
  32552. void resetToDefaultMapping (const CommandID commandID) throw();
  32553. /** Removes all keypresses that are assigned to any commands. */
  32554. void clearAllKeyPresses() throw();
  32555. /** Removes all keypresses that are assigned to a particular command. */
  32556. void clearAllKeyPresses (const CommandID commandID) throw();
  32557. /** Removes one of the keypresses that are assigned to a command.
  32558. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  32559. which the keyPressIndex refers.
  32560. */
  32561. void removeKeyPress (const CommandID commandID,
  32562. const int keyPressIndex) throw();
  32563. /** Removes a keypress from any command that it may be assigned to.
  32564. */
  32565. void removeKeyPress (const KeyPress& keypress) throw();
  32566. /** Returns true if the given command is linked to this key. */
  32567. bool containsMapping (const CommandID commandID,
  32568. const KeyPress& keyPress) const throw();
  32569. /** Looks for a command that corresponds to a keypress.
  32570. @returns the UID of the command or 0 if none was found
  32571. */
  32572. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  32573. /** Tries to recreate the mappings from a previously stored state.
  32574. The XML passed in must have been created by the createXml() method.
  32575. If the stored state makes any reference to commands that aren't
  32576. currently available, these will be ignored.
  32577. If the set of mappings being loaded was a set of differences (using createXml (true)),
  32578. then this will call resetToDefaultMappings() and then merge the saved mappings
  32579. on top. If the saved set was created with createXml (false), then this method
  32580. will first clear all existing mappings and load the saved ones as a complete set.
  32581. @returns true if it manages to load the XML correctly
  32582. @see createXml
  32583. */
  32584. bool restoreFromXml (const XmlElement& xmlVersion);
  32585. /** Creates an XML representation of the current mappings.
  32586. This will produce a lump of XML that can be later reloaded using
  32587. restoreFromXml() to recreate the current mapping state.
  32588. The object that is returned must be deleted by the caller.
  32589. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  32590. will be saved into the XML. If it's true, then the XML will
  32591. only store the differences between the current mappings and
  32592. the default mappings you'd get from calling resetToDefaultMappings().
  32593. The advantage of saving a set of differences from the default is that
  32594. if you change the default mappings (in a new version of your app, for
  32595. example), then these will be merged into a user's saved preferences.
  32596. @see restoreFromXml
  32597. */
  32598. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  32599. /** @internal */
  32600. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  32601. /** @internal */
  32602. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  32603. /** @internal */
  32604. void globalFocusChanged (Component* focusedComponent);
  32605. juce_UseDebuggingNewOperator
  32606. private:
  32607. ApplicationCommandManager* commandManager;
  32608. struct CommandMapping
  32609. {
  32610. CommandID commandID;
  32611. Array <KeyPress> keypresses;
  32612. bool wantsKeyUpDownCallbacks;
  32613. };
  32614. OwnedArray <CommandMapping> mappings;
  32615. struct KeyPressTime
  32616. {
  32617. KeyPress key;
  32618. uint32 timeWhenPressed;
  32619. };
  32620. OwnedArray <KeyPressTime> keysDown;
  32621. void handleMessage (const Message& message);
  32622. void invokeCommand (const CommandID commandID,
  32623. const KeyPress& keyPress,
  32624. const bool isKeyDown,
  32625. const int millisecsSinceKeyPressed,
  32626. Component* const originatingComponent) const;
  32627. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  32628. };
  32629. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  32630. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  32631. /********* Start of inlined file: juce_TreeView.h *********/
  32632. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  32633. #define __JUCE_TREEVIEW_JUCEHEADER__
  32634. class TreeView;
  32635. /**
  32636. An item in a treeview.
  32637. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  32638. own sub-items.
  32639. To implement an item that contains sub-items, override the itemOpennessChanged()
  32640. method so that when it is opened, it adds the new sub-items to itself using the
  32641. addSubItem method. Depending on the nature of the item it might choose to only
  32642. do this the first time it's opened, or it might want to refresh itself each time.
  32643. It also has the option of deleting its sub-items when it is closed, or leaving them
  32644. in place.
  32645. */
  32646. class JUCE_API TreeViewItem
  32647. {
  32648. public:
  32649. /** Constructor. */
  32650. TreeViewItem();
  32651. /** Destructor. */
  32652. virtual ~TreeViewItem();
  32653. /** Returns the number of sub-items that have been added to this item.
  32654. Note that this doesn't mean much if the node isn't open.
  32655. @see getSubItem, mightContainSubItems, addSubItem
  32656. */
  32657. int getNumSubItems() const throw();
  32658. /** Returns one of the item's sub-items.
  32659. Remember that the object returned might get deleted at any time when its parent
  32660. item is closed or refreshed, depending on the nature of the items you're using.
  32661. @see getNumSubItems
  32662. */
  32663. TreeViewItem* getSubItem (const int index) const throw();
  32664. /** Removes any sub-items. */
  32665. void clearSubItems();
  32666. /** Adds a sub-item.
  32667. @param newItem the object to add to the item's sub-item list. Once added, these can be
  32668. found using getSubItem(). When the items are later removed with
  32669. removeSubItem() (or when this item is deleted), they will be deleted.
  32670. @param insertPosition the index which the new item should have when it's added. If this
  32671. value is less than 0, the item will be added to the end of the list.
  32672. */
  32673. void addSubItem (TreeViewItem* const newItem,
  32674. const int insertPosition = -1);
  32675. /** Removes one of the sub-items.
  32676. @param index the item to remove
  32677. @param deleteItem if true, the item that is removed will also be deleted.
  32678. */
  32679. void removeSubItem (const int index,
  32680. const bool deleteItem = true);
  32681. /** Returns the TreeView to which this item belongs. */
  32682. TreeView* getOwnerView() const throw() { return ownerView; }
  32683. /** Returns the item within which this item is contained. */
  32684. TreeViewItem* getParentItem() const throw() { return parentItem; }
  32685. /** True if this item is currently open in the treeview. */
  32686. bool isOpen() const throw();
  32687. /** Opens or closes the item.
  32688. When opened or closed, the item's itemOpennessChanged() method will be called,
  32689. and a subclass should use this callback to create and add any sub-items that
  32690. it needs to.
  32691. @see itemOpennessChanged, mightContainSubItems
  32692. */
  32693. void setOpen (const bool shouldBeOpen);
  32694. /** True if this item is currently selected.
  32695. Use this when painting the node, to decide whether to draw it as selected or not.
  32696. */
  32697. bool isSelected() const throw();
  32698. /** Selects or deselects the item.
  32699. This will cause a callback to itemSelectionChanged()
  32700. */
  32701. void setSelected (const bool shouldBeSelected,
  32702. const bool deselectOtherItemsFirst);
  32703. /** Returns the rectangle that this item occupies.
  32704. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  32705. top-left of the TreeView comp, so this will depend on the scroll-position of
  32706. the tree. If false, it is relative to the top-left of the topmost item in the
  32707. tree (so this would be unaffected by scrolling the view).
  32708. */
  32709. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  32710. /** Sends a signal to the treeview to make it refresh itself.
  32711. Call this if your items have changed and you want the tree to update to reflect
  32712. this.
  32713. */
  32714. void treeHasChanged() const throw();
  32715. /** Sends a repaint message to redraw just this item.
  32716. Note that you should only call this if you want to repaint a superficial change. If
  32717. you're altering the tree's nodes, you should instead call treeHasChanged().
  32718. */
  32719. void repaintItem() const;
  32720. /** Returns the row number of this item in the tree.
  32721. The row number of an item will change according to which items are open.
  32722. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  32723. */
  32724. int getRowNumberInTree() const throw();
  32725. /** Returns true if all the item's parent nodes are open.
  32726. This is useful to check whether the item might actually be visible or not.
  32727. */
  32728. bool areAllParentsOpen() const throw();
  32729. /** Changes whether lines are drawn to connect any sub-items to this item.
  32730. By default, line-drawing is turned on.
  32731. */
  32732. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  32733. /** Tells the tree whether this item can potentially be opened.
  32734. If your item could contain sub-items, this should return true; if it returns
  32735. false then the tree will not try to open the item. This determines whether or
  32736. not the item will be drawn with a 'plus' button next to it.
  32737. */
  32738. virtual bool mightContainSubItems() = 0;
  32739. /** Returns a string to uniquely identify this item.
  32740. If you're planning on using the TreeView::getOpennessState() method, then
  32741. these strings will be used to identify which nodes are open. The string
  32742. should be unique amongst the item's sibling items, but it's ok for there
  32743. to be duplicates at other levels of the tree.
  32744. If you're not going to store the state, then it's ok not to bother implementing
  32745. this method.
  32746. */
  32747. virtual const String getUniqueName() const;
  32748. /** Called when an item is opened or closed.
  32749. When setOpen() is called and the item has specified that it might
  32750. have sub-items with the mightContainSubItems() method, this method
  32751. is called to let the item create or manage its sub-items.
  32752. So when this is called with isNowOpen set to true (i.e. when the item is being
  32753. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  32754. refresh its sub-item list.
  32755. When this is called with isNowOpen set to false, the subclass might want
  32756. to use clearSubItems() to save on space, or it might choose to leave them,
  32757. depending on the nature of the tree.
  32758. You could also use this callback as a trigger to start a background process
  32759. which asynchronously creates sub-items and adds them, if that's more
  32760. appropriate for the task in hand.
  32761. @see mightContainSubItems
  32762. */
  32763. virtual void itemOpennessChanged (bool isNowOpen);
  32764. /** Must return the width required by this item.
  32765. If your item needs to have a particular width in pixels, return that value; if
  32766. you'd rather have it just fill whatever space is available in the treeview,
  32767. return -1.
  32768. If all your items return -1, no horizontal scrollbar will be shown, but if any
  32769. items have fixed widths and extend beyond the width of the treeview, a
  32770. scrollbar will appear.
  32771. Each item can be a different width, but if they change width, you should call
  32772. treeHasChanged() to update the tree.
  32773. */
  32774. virtual int getItemWidth() const { return -1; }
  32775. /** Must return the height required by this item.
  32776. This is the height in pixels that the item will take up. Items in the tree
  32777. can be different heights, but if they change height, you should call
  32778. treeHasChanged() to update the tree.
  32779. */
  32780. virtual int getItemHeight() const { return 20; }
  32781. /** You can override this method to return false if you don't want to allow the
  32782. user to select this item.
  32783. */
  32784. virtual bool canBeSelected() const { return true; }
  32785. /** Creates a component that will be used to represent this item.
  32786. You don't have to implement this method - if it returns 0 then no component
  32787. will be used for the item, and you can just draw it using the paintItem()
  32788. callback. But if you do return a component, it will be positioned in the
  32789. treeview so that it can be used to represent this item.
  32790. The component returned will be managed by the treeview, so always return
  32791. a new component, and don't keep a reference to it, as the treeview will
  32792. delete it later when it goes off the screen or is no longer needed. Also
  32793. bear in mind that if the component keeps a reference to the item that
  32794. created it, that item could be deleted before the component. Its position
  32795. and size will be completely managed by the tree, so don't attempt to move it
  32796. around.
  32797. Something you may want to do with your component is to give it a pointer to
  32798. the TreeView that created it. This is perfectly safe, and there's no danger
  32799. of it becoming a dangling pointer because the TreeView will always delete
  32800. the component before it is itself deleted.
  32801. As long as you stick to these rules you can return whatever kind of
  32802. component you like. It's most useful if you're doing things like drag-and-drop
  32803. of items, or want to use a Label component to edit item names, etc.
  32804. */
  32805. virtual Component* createItemComponent() { return 0; }
  32806. /** Draws the item's contents.
  32807. You can choose to either implement this method and draw each item, or you
  32808. can use createItemComponent() to create a component that will represent the
  32809. item.
  32810. If all you need in your tree is to be able to draw the items and detect when
  32811. the user selects or double-clicks one of them, it's probably enough to
  32812. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  32813. complicated interactions, you may need to use createItemComponent() instead.
  32814. @param g the graphics context to draw into
  32815. @param width the width of the area available for drawing
  32816. @param height the height of the area available for drawing
  32817. */
  32818. virtual void paintItem (Graphics& g, int width, int height);
  32819. /** Draws the item's open/close button.
  32820. If you don't implement this method, the default behaviour is to
  32821. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  32822. it for custom effects.
  32823. */
  32824. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  32825. /** Called when the user clicks on this item.
  32826. If you're using createItemComponent() to create a custom component for the
  32827. item, the mouse-clicks might not make it through to the treeview, but this
  32828. is how you find out about clicks when just drawing each item individually.
  32829. The associated mouse-event details are passed in, so you can find out about
  32830. which button, where it was, etc.
  32831. @see itemDoubleClicked
  32832. */
  32833. virtual void itemClicked (const MouseEvent& e);
  32834. /** Called when the user double-clicks on this item.
  32835. If you're using createItemComponent() to create a custom component for the
  32836. item, the mouse-clicks might not make it through to the treeview, but this
  32837. is how you find out about clicks when just drawing each item individually.
  32838. The associated mouse-event details are passed in, so you can find out about
  32839. which button, where it was, etc.
  32840. If not overridden, the base class method here will open or close the item as
  32841. if the 'plus' button had been clicked.
  32842. @see itemClicked
  32843. */
  32844. virtual void itemDoubleClicked (const MouseEvent& e);
  32845. /** Called when the item is selected or deselected.
  32846. Use this if you want to do something special when the item's selectedness
  32847. changes. By default it'll get repainted when this happens.
  32848. */
  32849. virtual void itemSelectionChanged (bool isNowSelected);
  32850. /** The item can return a tool tip string here if it wants to.
  32851. @see TooltipClient
  32852. */
  32853. virtual const String getTooltip();
  32854. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  32855. If this returns a non-empty name then when the user drags an item, the treeview will
  32856. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  32857. a drag-and-drop operation, using this string as the source description, with the treeview
  32858. itself as the source component.
  32859. If you need more complex drag-and-drop behaviour, you can use custom components for
  32860. the items, and use those to trigger the drag.
  32861. @see DragAndDropContainer::startDragging
  32862. */
  32863. virtual const String getDragSourceDescription();
  32864. /** Sets a flag to indicate that the item wants to be allowed
  32865. to draw all the way across to the left edge of the treeview.
  32866. By default this is false, which means that when the paintItem()
  32867. method is called, its graphics context is clipped to only allow
  32868. drawing within the item's rectangle. If this flag is set to true,
  32869. then the graphics context isn't clipped on its left side, so it
  32870. can draw all the way across to the left margin. Note that the
  32871. context will still have its origin in the same place though, so
  32872. the coordinates of anything to its left will be negative. It's
  32873. mostly useful if you want to draw a wider bar behind the
  32874. highlighted item.
  32875. */
  32876. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  32877. juce_UseDebuggingNewOperator
  32878. private:
  32879. TreeView* ownerView;
  32880. TreeViewItem* parentItem;
  32881. OwnedArray <TreeViewItem> subItems;
  32882. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  32883. int uid;
  32884. bool selected : 1;
  32885. bool redrawNeeded : 1;
  32886. bool drawLinesInside : 1;
  32887. bool drawsInLeftMargin : 1;
  32888. unsigned int openness : 2;
  32889. friend class TreeView;
  32890. friend class TreeViewContentComponent;
  32891. void updatePositions (int newY);
  32892. int getIndentX() const throw();
  32893. void setOwnerView (TreeView* const newOwner) throw();
  32894. void paintRecursively (Graphics& g, int width);
  32895. TreeViewItem* findItemRecursively (int y) throw();
  32896. TreeViewItem* getDeepestOpenParentItem() throw();
  32897. void restoreFromXml (const XmlElement& e);
  32898. XmlElement* createXmlOpenness() const;
  32899. bool isLastOfSiblings() const throw();
  32900. TreeViewItem* getTopLevelItem() throw();
  32901. int getNumRows() const throw();
  32902. TreeViewItem* getItemOnRow (int index) throw();
  32903. void deselectAllRecursively();
  32904. int countSelectedItemsRecursively() const throw();
  32905. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  32906. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  32907. TreeViewItem (const TreeViewItem&);
  32908. const TreeViewItem& operator= (const TreeViewItem&);
  32909. };
  32910. /**
  32911. A tree-view component.
  32912. Use one of these to hold and display a structure of TreeViewItem objects.
  32913. */
  32914. class JUCE_API TreeView : public Component,
  32915. public SettableTooltipClient,
  32916. private AsyncUpdater
  32917. {
  32918. public:
  32919. /** Creates an empty treeview.
  32920. Once you've got a treeview component, you'll need to give it something to
  32921. display, using the setRootItem() method.
  32922. */
  32923. TreeView (const String& componentName = String::empty);
  32924. /** Destructor. */
  32925. ~TreeView();
  32926. /** Sets the item that is displayed in the treeview.
  32927. A tree has a single root item which contains as many sub-items as it needs. If
  32928. you want the tree to contain a number of root items, you should still use a single
  32929. root item above these, but hide it using setRootItemVisible().
  32930. You can pass in 0 to this method to clear the tree and remove its current root item.
  32931. The object passed in will not be deleted by the treeview, it's up to the caller
  32932. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  32933. this item until you've removed it from the tree, either by calling setRootItem (0),
  32934. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  32935. to delete it.
  32936. */
  32937. void setRootItem (TreeViewItem* const newRootItem);
  32938. /** Returns the tree's root item.
  32939. This will be the last object passed to setRootItem(), or 0 if none has been set.
  32940. */
  32941. TreeViewItem* getRootItem() const throw() { return rootItem; }
  32942. /** This will remove and delete the current root item.
  32943. It's a convenient way of deleting the item and calling setRootItem (0).
  32944. */
  32945. void deleteRootItem();
  32946. /** Changes whether the tree's root item is shown or not.
  32947. If the root item is hidden, only its sub-items will be shown in the treeview - this
  32948. lets you make the tree look as if it's got many root items. If it's hidden, this call
  32949. will also make sure the root item is open (otherwise the treeview would look empty).
  32950. */
  32951. void setRootItemVisible (const bool shouldBeVisible);
  32952. /** Returns true if the root item is visible.
  32953. @see setRootItemVisible
  32954. */
  32955. bool isRootItemVisible() const throw() { return rootItemVisible; }
  32956. /** Sets whether items are open or closed by default.
  32957. Normally, items are closed until the user opens them, but you can use this
  32958. to make them default to being open until explicitly closed.
  32959. @see areItemsOpenByDefault
  32960. */
  32961. void setDefaultOpenness (const bool isOpenByDefault);
  32962. /** Returns true if the tree's items default to being open.
  32963. @see setDefaultOpenness
  32964. */
  32965. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  32966. /** This sets a flag to indicate that the tree can be used for multi-selection.
  32967. You can always select multiple items internally by calling the
  32968. TreeViewItem::setSelected() method, but this flag indicates whether the user
  32969. is allowed to multi-select by clicking on the tree.
  32970. By default it is disabled.
  32971. @see isMultiSelectEnabled
  32972. */
  32973. void setMultiSelectEnabled (const bool canMultiSelect);
  32974. /** Returns whether multi-select has been enabled for the tree.
  32975. @see setMultiSelectEnabled
  32976. */
  32977. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  32978. /** Sets a flag to indicate whether to hide the open/close buttons.
  32979. @see areOpenCloseButtonsVisible
  32980. */
  32981. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  32982. /** Returns whether open/close buttons are shown.
  32983. @see setOpenCloseButtonsVisible
  32984. */
  32985. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  32986. /** Deselects any items that are currently selected. */
  32987. void clearSelectedItems();
  32988. /** Returns the number of items that are currently selected.
  32989. @see getSelectedItem, clearSelectedItems
  32990. */
  32991. int getNumSelectedItems() const throw();
  32992. /** Returns one of the selected items in the tree.
  32993. @param index the index, 0 to (getNumSelectedItems() - 1)
  32994. */
  32995. TreeViewItem* getSelectedItem (const int index) const throw();
  32996. /** Returns the number of rows the tree is using.
  32997. This will depend on which items are open.
  32998. @see TreeViewItem::getRowNumberInTree()
  32999. */
  33000. int getNumRowsInTree() const;
  33001. /** Returns the item on a particular row of the tree.
  33002. If the index is out of range, this will return 0.
  33003. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  33004. */
  33005. TreeViewItem* getItemOnRow (int index) const;
  33006. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  33007. void scrollToKeepItemVisible (TreeViewItem* item);
  33008. /** Returns the treeview's Viewport object. */
  33009. Viewport* getViewport() const throw() { return viewport; }
  33010. /** Returns the number of pixels by which each nested level of the tree is indented.
  33011. @see setIndentSize
  33012. */
  33013. int getIndentSize() const throw() { return indentSize; }
  33014. /** Changes the distance by which each nested level of the tree is indented.
  33015. @see getIndentSize
  33016. */
  33017. void setIndentSize (const int newIndentSize);
  33018. /** Saves the current state of open/closed nodes so it can be restored later.
  33019. This takes a snapshot of which nodes have been explicitly opened or closed,
  33020. and records it as XML. To identify node objects it uses the
  33021. TreeViewItem::getUniqueName() method to create named paths. This
  33022. means that the same state of open/closed nodes can be restored to a
  33023. completely different instance of the tree, as long as it contains nodes
  33024. whose unique names are the same.
  33025. The caller is responsible for deleting the object that is returned.
  33026. @param alsoIncludeScrollPosition if this is true, the state will also
  33027. include information about where the
  33028. tree has been scrolled to vertically,
  33029. so this can also be restored
  33030. @see restoreOpennessState
  33031. */
  33032. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  33033. /** Restores a previously saved arrangement of open/closed nodes.
  33034. This will try to restore a snapshot of the tree's state that was created by
  33035. the getOpennessState() method. If any of the nodes named in the original
  33036. XML aren't present in this tree, they will be ignored.
  33037. @see getOpennessState
  33038. */
  33039. void restoreOpennessState (const XmlElement& newState);
  33040. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  33041. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33042. methods.
  33043. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33044. */
  33045. enum ColourIds
  33046. {
  33047. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  33048. linesColourId = 0x1000501 /**< The colour to draw the lines with.*/
  33049. };
  33050. /** @internal */
  33051. void paint (Graphics& g);
  33052. /** @internal */
  33053. void resized();
  33054. /** @internal */
  33055. bool keyPressed (const KeyPress& key);
  33056. /** @internal */
  33057. void colourChanged();
  33058. /** @internal */
  33059. void enablementChanged();
  33060. juce_UseDebuggingNewOperator
  33061. private:
  33062. friend class TreeViewItem;
  33063. friend class TreeViewContentComponent;
  33064. Viewport* viewport;
  33065. CriticalSection nodeAlterationLock;
  33066. TreeViewItem* rootItem;
  33067. int indentSize;
  33068. bool defaultOpenness : 1;
  33069. bool needsRecalculating : 1;
  33070. bool rootItemVisible : 1;
  33071. bool multiSelectEnabled : 1;
  33072. bool openCloseButtonsVisible : 1;
  33073. void itemsChanged() throw();
  33074. void handleAsyncUpdate();
  33075. void moveSelectedRow (int delta);
  33076. void updateButtonUnderMouse (const MouseEvent& e);
  33077. TreeView (const TreeView&);
  33078. const TreeView& operator= (const TreeView&);
  33079. };
  33080. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  33081. /********* End of inlined file: juce_TreeView.h *********/
  33082. /**
  33083. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  33084. object.
  33085. @see KeyPressMappingSet
  33086. */
  33087. class JUCE_API KeyMappingEditorComponent : public Component,
  33088. public TreeViewItem,
  33089. public ChangeListener,
  33090. private ButtonListener
  33091. {
  33092. public:
  33093. /** Creates a KeyMappingEditorComponent.
  33094. @param mappingSet this is the set of mappings to display and
  33095. edit. Make sure the mappings object is not
  33096. deleted before this component!
  33097. @param showResetToDefaultButton if true, then at the bottom of the
  33098. list, the component will include a 'reset to
  33099. defaults' button.
  33100. */
  33101. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  33102. const bool showResetToDefaultButton);
  33103. /** Destructor. */
  33104. virtual ~KeyMappingEditorComponent();
  33105. /** Sets up the colours to use for parts of the component.
  33106. @param mainBackground colour to use for most of the background
  33107. @param textColour colour to use for the text
  33108. */
  33109. void setColours (const Colour& mainBackground,
  33110. const Colour& textColour);
  33111. /** Returns the KeyPressMappingSet that this component is acting upon.
  33112. */
  33113. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  33114. /** Can be overridden if some commands need to be excluded from the list.
  33115. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  33116. method to decide what to return, but you can override it to handle special cases.
  33117. */
  33118. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  33119. /** Can be overridden to indicate that some commands are shown as read-only.
  33120. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  33121. method to decide what to return, but you can override it to handle special cases.
  33122. */
  33123. virtual bool isCommandReadOnly (const CommandID commandID);
  33124. /** This can be overridden to let you change the format of the string used
  33125. to describe a keypress.
  33126. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  33127. keys that are triggered by something else externally. If you override the
  33128. method, be sure to let the base class's method handle keys you're not
  33129. interested in.
  33130. */
  33131. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  33132. /** @internal */
  33133. void parentHierarchyChanged();
  33134. /** @internal */
  33135. void resized();
  33136. /** @internal */
  33137. void changeListenerCallback (void*);
  33138. /** @internal */
  33139. bool mightContainSubItems();
  33140. /** @internal */
  33141. const String getUniqueName() const;
  33142. /** @internal */
  33143. void buttonClicked (Button* button);
  33144. juce_UseDebuggingNewOperator
  33145. private:
  33146. KeyPressMappingSet* mappings;
  33147. TreeView* tree;
  33148. friend class KeyMappingTreeViewItem;
  33149. friend class KeyCategoryTreeViewItem;
  33150. friend class KeyMappingItemComponent;
  33151. friend class KeyMappingChangeButton;
  33152. Colour backgroundColour, textColour;
  33153. TextButton* resetButton;
  33154. void assignNewKey (const CommandID commandID, int index);
  33155. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  33156. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  33157. };
  33158. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  33159. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  33160. #endif
  33161. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  33162. #endif
  33163. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  33164. #endif
  33165. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  33166. #endif
  33167. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  33168. #endif
  33169. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33170. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  33171. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33172. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33173. /********* Start of inlined file: juce_MenuBarModel.h *********/
  33174. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  33175. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  33176. class MenuBarModel;
  33177. /**
  33178. A class to receive callbacks when a MenuBarModel changes.
  33179. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  33180. */
  33181. class JUCE_API MenuBarModelListener
  33182. {
  33183. public:
  33184. /** Destructor. */
  33185. virtual ~MenuBarModelListener() {}
  33186. /** This callback is made when items are changed in the menu bar model.
  33187. */
  33188. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  33189. /** This callback is made when an application command is invoked that
  33190. is represented by one of the items in the menu bar model.
  33191. */
  33192. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  33193. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  33194. };
  33195. /**
  33196. A class for controlling MenuBar components.
  33197. This class is used to tell a MenuBar what menus to show, and to respond
  33198. to a menu being selected.
  33199. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  33200. */
  33201. class JUCE_API MenuBarModel : private AsyncUpdater,
  33202. private ApplicationCommandManagerListener
  33203. {
  33204. public:
  33205. MenuBarModel() throw();
  33206. /** Destructor. */
  33207. virtual ~MenuBarModel();
  33208. /** Call this when some of your menu items have changed.
  33209. This method will cause a callback to any MenuBarListener objects that
  33210. are registered with this model.
  33211. If this model is displaying items from an ApplicationCommandManager, you
  33212. can use the setApplicationCommandManagerToWatch() method to cause
  33213. change messages to be sent automatically when the ApplicationCommandManager
  33214. is changed.
  33215. @see addListener, removeListener, MenuBarListener
  33216. */
  33217. void menuItemsChanged();
  33218. /** Tells the menu bar to listen to the specified command manager, and to update
  33219. itself when the commands change.
  33220. This will also allow it to flash a menu name when a command from that menu
  33221. is invoked using a keystroke.
  33222. */
  33223. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  33224. /** Registers a listener for callbacks when the menu items in this model change.
  33225. The listener object will get callbacks when this object's menuItemsChanged()
  33226. method is called.
  33227. @see removeListener
  33228. */
  33229. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  33230. /** Removes a listener.
  33231. @see addListener
  33232. */
  33233. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  33234. /** This method must return a list of the names of the menus. */
  33235. virtual const StringArray getMenuBarNames() = 0;
  33236. /** This should return the popup menu to display for a given top-level menu.
  33237. @param topLevelMenuIndex the index of the top-level menu to show
  33238. @param menuName the name of the top-level menu item to show
  33239. */
  33240. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  33241. const String& menuName) = 0;
  33242. /** This is called when a menu item has been clicked on.
  33243. @param menuItemID the item ID of the PopupMenu item that was selected
  33244. @param topLevelMenuIndex the index of the top-level menu from which the item was
  33245. chosen (just in case you've used duplicate ID numbers
  33246. on more than one of the popup menus)
  33247. */
  33248. virtual void menuItemSelected (int menuItemID,
  33249. int topLevelMenuIndex) = 0;
  33250. #if JUCE_MAC || DOXYGEN
  33251. /** MAC ONLY - Sets the model that is currently being shown as the main
  33252. menu bar at the top of the screen on the Mac.
  33253. You can pass 0 to stop the current model being displayed. Be careful
  33254. not to delete a model while it is being used.
  33255. An optional extra menu can be specified, containing items to add to the top of
  33256. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  33257. an apple, it's the one next to it, with your application's name at the top
  33258. and the services menu etc on it). When one of these items is selected, the
  33259. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  33260. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  33261. object then newMenuBarModel must be non-null.
  33262. */
  33263. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  33264. const PopupMenu* extraAppleMenuItems = 0) throw();
  33265. /** MAC ONLY - Returns the menu model that is currently being shown as
  33266. the main menu bar.
  33267. */
  33268. static MenuBarModel* getMacMainMenu() throw();
  33269. #endif
  33270. /** @internal */
  33271. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  33272. /** @internal */
  33273. void applicationCommandListChanged();
  33274. /** @internal */
  33275. void handleAsyncUpdate();
  33276. juce_UseDebuggingNewOperator
  33277. private:
  33278. ApplicationCommandManager* manager;
  33279. SortedSet <void*> listeners;
  33280. MenuBarModel (const MenuBarModel&);
  33281. const MenuBarModel& operator= (const MenuBarModel&);
  33282. };
  33283. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  33284. /********* End of inlined file: juce_MenuBarModel.h *********/
  33285. /**
  33286. A menu bar component.
  33287. @see MenuBarModel
  33288. */
  33289. class JUCE_API MenuBarComponent : public Component,
  33290. private MenuBarModelListener,
  33291. private Timer
  33292. {
  33293. public:
  33294. /** Creates a menu bar.
  33295. @param model the model object to use to control this bar. You can
  33296. pass 0 into this if you like, and set the model later
  33297. using the setModel() method
  33298. */
  33299. MenuBarComponent (MenuBarModel* const model);
  33300. /** Destructor. */
  33301. ~MenuBarComponent();
  33302. /** Changes the model object to use to control the bar.
  33303. This can be 0, in which case the bar will be empty. Don't delete the object
  33304. that is passed-in while it's still being used by this MenuBar.
  33305. */
  33306. void setModel (MenuBarModel* const newModel);
  33307. /** Pops up one of the menu items.
  33308. This lets you manually open one of the menus - it could be triggered by a
  33309. key shortcut, for example.
  33310. */
  33311. void showMenu (const int menuIndex);
  33312. /** @internal */
  33313. void paint (Graphics& g);
  33314. /** @internal */
  33315. void resized();
  33316. /** @internal */
  33317. void mouseEnter (const MouseEvent& e);
  33318. /** @internal */
  33319. void mouseExit (const MouseEvent& e);
  33320. /** @internal */
  33321. void mouseDown (const MouseEvent& e);
  33322. /** @internal */
  33323. void mouseDrag (const MouseEvent& e);
  33324. /** @internal */
  33325. void mouseUp (const MouseEvent& e);
  33326. /** @internal */
  33327. void mouseMove (const MouseEvent& e);
  33328. /** @internal */
  33329. void inputAttemptWhenModal();
  33330. /** @internal */
  33331. void handleCommandMessage (int commandId);
  33332. /** @internal */
  33333. bool keyPressed (const KeyPress& key);
  33334. /** @internal */
  33335. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  33336. /** @internal */
  33337. void menuCommandInvoked (MenuBarModel* menuBarModel,
  33338. const ApplicationCommandTarget::InvocationInfo& info);
  33339. juce_UseDebuggingNewOperator
  33340. private:
  33341. MenuBarModel* model;
  33342. StringArray menuNames;
  33343. Array <int> xPositions;
  33344. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  33345. int lastMouseX, lastMouseY;
  33346. bool inModalState;
  33347. Component* currentPopup;
  33348. int getItemAt (int x, int y);
  33349. void updateItemUnderMouse (const int x, const int y);
  33350. void hideCurrentMenu();
  33351. void timerCallback();
  33352. void repaintMenuItem (int index);
  33353. MenuBarComponent (const MenuBarComponent&);
  33354. const MenuBarComponent& operator= (const MenuBarComponent&);
  33355. };
  33356. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  33357. /********* End of inlined file: juce_MenuBarComponent.h *********/
  33358. #endif
  33359. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  33360. #endif
  33361. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  33362. #endif
  33363. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  33364. #endif
  33365. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33366. /********* Start of inlined file: juce_ComponentDragger.h *********/
  33367. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33368. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33369. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  33370. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33371. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33372. /**
  33373. A class that imposes restrictions on a Component's size or position.
  33374. This is used by classes such as ResizableCornerComponent,
  33375. ResizableBorderComponent and ResizableWindow.
  33376. The base class can impose some basic size and position limits, but you can
  33377. also subclass this for custom uses.
  33378. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  33379. */
  33380. class JUCE_API ComponentBoundsConstrainer
  33381. {
  33382. public:
  33383. /** When first created, the object will not impose any restrictions on the components. */
  33384. ComponentBoundsConstrainer() throw();
  33385. /** Destructor. */
  33386. virtual ~ComponentBoundsConstrainer();
  33387. /** Imposes a minimum width limit. */
  33388. void setMinimumWidth (const int minimumWidth) throw();
  33389. /** Returns the current minimum width. */
  33390. int getMinimumWidth() const throw() { return minW; }
  33391. /** Imposes a maximum width limit. */
  33392. void setMaximumWidth (const int maximumWidth) throw();
  33393. /** Returns the current maximum width. */
  33394. int getMaximumWidth() const throw() { return maxW; }
  33395. /** Imposes a minimum height limit. */
  33396. void setMinimumHeight (const int minimumHeight) throw();
  33397. /** Returns the current minimum height. */
  33398. int getMinimumHeight() const throw() { return minH; }
  33399. /** Imposes a maximum height limit. */
  33400. void setMaximumHeight (const int maximumHeight) throw();
  33401. /** Returns the current maximum height. */
  33402. int getMaximumHeight() const throw() { return maxH; }
  33403. /** Imposes a minimum width and height limit. */
  33404. void setMinimumSize (const int minimumWidth,
  33405. const int minimumHeight) throw();
  33406. /** Imposes a maximum width and height limit. */
  33407. void setMaximumSize (const int maximumWidth,
  33408. const int maximumHeight) throw();
  33409. /** Set all the maximum and minimum dimensions. */
  33410. void setSizeLimits (const int minimumWidth,
  33411. const int minimumHeight,
  33412. const int maximumWidth,
  33413. const int maximumHeight) throw();
  33414. /** Sets the amount by which the component is allowed to go off-screen.
  33415. The values indicate how many pixels must remain on-screen when dragged off
  33416. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  33417. when the component goes off the top of the screen, its y-position will be
  33418. clipped so that there are always at least 10 pixels on-screen. In other words,
  33419. the lowest y-position it can take would be (10 - the component's height).
  33420. If you pass 0 or less for one of these amounts, the component is allowed
  33421. to move beyond that edge completely, with no restrictions at all.
  33422. If you pass a very large number (i.e. larger that the dimensions of the
  33423. component itself), then the component won't be allowed to overlap that
  33424. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  33425. the component will bump into the left side of the screen and go no further.
  33426. */
  33427. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  33428. const int minimumWhenOffTheLeft,
  33429. const int minimumWhenOffTheBottom,
  33430. const int minimumWhenOffTheRight) throw();
  33431. /** Specifies a width-to-height ratio that the resizer should always maintain.
  33432. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  33433. will always be maintained as this multiple of the height.
  33434. @see setResizeLimits
  33435. */
  33436. void setFixedAspectRatio (const double widthOverHeight) throw();
  33437. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  33438. If no aspect ratio is being enforced, this will return 0.
  33439. */
  33440. double getFixedAspectRatio() const throw();
  33441. /** This callback changes the given co-ordinates to impose whatever the current
  33442. constraints are set to be.
  33443. @param x the x position that should be examined and adjusted
  33444. @param y the y position that should be examined and adjusted
  33445. @param w the width that should be examined and adjusted
  33446. @param h the height that should be examined and adjusted
  33447. @param previousBounds the component's current size
  33448. @param limits the region in which the component can be positioned
  33449. @param isStretchingTop whether the top edge of the component is being resized
  33450. @param isStretchingLeft whether the left edge of the component is being resized
  33451. @param isStretchingBottom whether the bottom edge of the component is being resized
  33452. @param isStretchingRight whether the right edge of the component is being resized
  33453. */
  33454. virtual void checkBounds (int& x, int& y, int& w, int& h,
  33455. const Rectangle& previousBounds,
  33456. const Rectangle& limits,
  33457. const bool isStretchingTop,
  33458. const bool isStretchingLeft,
  33459. const bool isStretchingBottom,
  33460. const bool isStretchingRight);
  33461. /** This callback happens when the resizer is about to start dragging. */
  33462. virtual void resizeStart();
  33463. /** This callback happens when the resizer has finished dragging. */
  33464. virtual void resizeEnd();
  33465. /** Checks the given bounds, and then sets the component to the corrected size. */
  33466. void setBoundsForComponent (Component* const component,
  33467. int x, int y, int w, int h,
  33468. const bool isStretchingTop,
  33469. const bool isStretchingLeft,
  33470. const bool isStretchingBottom,
  33471. const bool isStretchingRight);
  33472. /** Performs a check on the current size of a component, and moves or resizes
  33473. it if it fails the constraints.
  33474. */
  33475. void checkComponentBounds (Component* component);
  33476. /** Called by setBoundsForComponent() to apply a new constrained size to a
  33477. component.
  33478. By default this just calls setBounds(), but it virtual in case it's needed for
  33479. extremely cunning purposes.
  33480. */
  33481. virtual void applyBoundsToComponent (Component* component,
  33482. int x, int y, int w, int h);
  33483. juce_UseDebuggingNewOperator
  33484. private:
  33485. int minW, maxW, minH, maxH;
  33486. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  33487. double aspectRatio;
  33488. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  33489. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  33490. };
  33491. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  33492. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  33493. /**
  33494. An object to take care of the logic for dragging components around with the mouse.
  33495. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  33496. then in your mouseDrag() callback, call dragComponent().
  33497. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  33498. to limit the component's position and keep it on-screen.
  33499. e.g. @code
  33500. class MyDraggableComp
  33501. {
  33502. ComponentDragger myDragger;
  33503. void mouseDown (const MouseEvent& e)
  33504. {
  33505. myDragger.startDraggingComponent (this, 0);
  33506. }
  33507. void mouseDrag (const MouseEvent& e)
  33508. {
  33509. myDragger.dragComponent (this, e);
  33510. }
  33511. };
  33512. @endcode
  33513. */
  33514. class JUCE_API ComponentDragger
  33515. {
  33516. public:
  33517. /** Creates a ComponentDragger. */
  33518. ComponentDragger();
  33519. /** Destructor. */
  33520. virtual ~ComponentDragger();
  33521. /** Call this from your component's mouseDown() method, to prepare for dragging.
  33522. @param componentToDrag the component that you want to drag
  33523. @param constrainer a constrainer object to use to keep the component
  33524. from going offscreen
  33525. @see dragComponent
  33526. */
  33527. void startDraggingComponent (Component* const componentToDrag,
  33528. ComponentBoundsConstrainer* constrainer);
  33529. /** Call this from your mouseDrag() callback to move the component.
  33530. This will move the component, but will first check the validity of the
  33531. component's new position using the checkPosition() method, which you
  33532. can override if you need to enforce special positioning limits on the
  33533. component.
  33534. @param componentToDrag the component that you want to drag
  33535. @param e the current mouse-drag event
  33536. @see dragComponent
  33537. */
  33538. void dragComponent (Component* const componentToDrag,
  33539. const MouseEvent& e);
  33540. juce_UseDebuggingNewOperator
  33541. private:
  33542. ComponentBoundsConstrainer* constrainer;
  33543. int originalX, originalY;
  33544. };
  33545. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  33546. /********* End of inlined file: juce_ComponentDragger.h *********/
  33547. #endif
  33548. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33549. #endif
  33550. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33551. #endif
  33552. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33553. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  33554. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33555. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33556. /**
  33557. Components derived from this class can have files dropped onto them by an external application.
  33558. @see DragAndDropContainer
  33559. */
  33560. class JUCE_API FileDragAndDropTarget
  33561. {
  33562. public:
  33563. /** Destructor. */
  33564. virtual ~FileDragAndDropTarget() {}
  33565. /** Callback to check whether this target is interested in the set of files being offered.
  33566. Note that this will be called repeatedly when the user is dragging the mouse around over your
  33567. component, so don't do anything time-consuming in here, like opening the files to have a look
  33568. inside them!
  33569. @param files the set of (absolute) pathnames of the files that the user is dragging
  33570. @returns true if this component wants to receive the other callbacks regarging this
  33571. type of object; if it returns false, no other callbacks will be made.
  33572. */
  33573. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  33574. /** Callback to indicate that some files are being dragged over this component.
  33575. This gets called when the user moves the mouse into this component while dragging.
  33576. Use this callback as a trigger to make your component repaint itself to give the
  33577. user feedback about whether the files can be dropped here or not.
  33578. @param files the set of (absolute) pathnames of the files that the user is dragging
  33579. @param x the mouse x position, relative to this component
  33580. @param y the mouse y position, relative to this component
  33581. */
  33582. virtual void fileDragEnter (const StringArray& files, int x, int y);
  33583. /** Callback to indicate that the user is dragging some files over this component.
  33584. This gets called when the user moves the mouse over this component while dragging.
  33585. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  33586. this lets you know what happens in-between.
  33587. @param files the set of (absolute) pathnames of the files that the user is dragging
  33588. @param x the mouse x position, relative to this component
  33589. @param y the mouse y position, relative to this component
  33590. */
  33591. virtual void fileDragMove (const StringArray& files, int x, int y);
  33592. /** Callback to indicate that the mouse has moved away from this component.
  33593. This gets called when the user moves the mouse out of this component while dragging
  33594. the files.
  33595. If you've used fileDragEnter() to repaint your component and give feedback, use this
  33596. as a signal to repaint it in its normal state.
  33597. @param files the set of (absolute) pathnames of the files that the user is dragging
  33598. */
  33599. virtual void fileDragExit (const StringArray& files);
  33600. /** Callback to indicate that the user has dropped the files onto this component.
  33601. When the user drops the files, this get called, and you can use the files in whatever
  33602. way is appropriate.
  33603. Note that after this is called, the fileDragExit method may not be called, so you should
  33604. clean up in here if there's anything you need to do when the drag finishes.
  33605. @param files the set of (absolute) pathnames of the files that the user is dragging
  33606. @param x the mouse x position, relative to this component
  33607. @param y the mouse y position, relative to this component
  33608. */
  33609. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  33610. };
  33611. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33612. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  33613. #endif
  33614. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33615. /********* Start of inlined file: juce_LassoComponent.h *********/
  33616. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33617. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  33618. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  33619. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33620. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33621. /** Manages a list of selectable items.
  33622. Use one of these to keep a track of things that the user has highlighted, like
  33623. icons or things in a list.
  33624. The class is templated so that you can use it to hold either a set of pointers
  33625. to objects, or a set of ID numbers or handles, for cases where each item may
  33626. not always have a corresponding object.
  33627. To be informed when items are selected/deselected, register a ChangeListener with
  33628. this object.
  33629. @see SelectableObject
  33630. */
  33631. template <class SelectableItemType>
  33632. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  33633. {
  33634. public:
  33635. /** Creates an empty set. */
  33636. SelectedItemSet()
  33637. {
  33638. }
  33639. /** Creates a set based on an array of items. */
  33640. SelectedItemSet (const Array <SelectableItemType>& items)
  33641. : selectedItems (items)
  33642. {
  33643. }
  33644. /** Creates a copy of another set. */
  33645. SelectedItemSet (const SelectedItemSet& other)
  33646. : selectedItems (other.selectedItems)
  33647. {
  33648. }
  33649. /** Creates a copy of another set. */
  33650. const SelectedItemSet& operator= (const SelectedItemSet& other)
  33651. {
  33652. if (selectedItems != other.selectedItems)
  33653. {
  33654. selectedItems = other.selectedItems;
  33655. changed();
  33656. }
  33657. return *this;
  33658. }
  33659. /** Destructor. */
  33660. ~SelectedItemSet()
  33661. {
  33662. }
  33663. /** Clears any other currently selected items, and selects this item.
  33664. If this item is already the only thing selected, no change notification
  33665. will be sent out.
  33666. @see addToSelection, addToSelectionBasedOnModifiers
  33667. */
  33668. void selectOnly (SelectableItemType item)
  33669. {
  33670. if (isSelected (item))
  33671. {
  33672. for (int i = selectedItems.size(); --i >= 0;)
  33673. {
  33674. if (selectedItems.getUnchecked(i) != item)
  33675. {
  33676. deselect (selectedItems.getUnchecked(i));
  33677. i = jmin (i, selectedItems.size());
  33678. }
  33679. }
  33680. }
  33681. else
  33682. {
  33683. deselectAll();
  33684. changed();
  33685. selectedItems.add (item);
  33686. itemSelected (item);
  33687. }
  33688. }
  33689. /** Selects an item.
  33690. If the item is already selected, no change notification will be sent out.
  33691. @see selectOnly, addToSelectionBasedOnModifiers
  33692. */
  33693. void addToSelection (SelectableItemType item)
  33694. {
  33695. if (! isSelected (item))
  33696. {
  33697. changed();
  33698. selectedItems.add (item);
  33699. itemSelected (item);
  33700. }
  33701. }
  33702. /** Selects or deselects an item.
  33703. This will use the modifier keys to decide whether to deselect other items
  33704. first.
  33705. So if the shift key is held down, the item will be added without deselecting
  33706. anything (same as calling addToSelection() )
  33707. If no modifiers are down, the current selection will be cleared first (same
  33708. as calling selectOnly() )
  33709. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  33710. so it'll be added to the set unless it's already there, in which case it'll be
  33711. deselected.
  33712. If the items that you're selecting can also be dragged, you may need to use the
  33713. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  33714. subtleties of this kind of usage.
  33715. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  33716. */
  33717. void addToSelectionBasedOnModifiers (SelectableItemType item,
  33718. const ModifierKeys& modifiers)
  33719. {
  33720. if (modifiers.isShiftDown())
  33721. {
  33722. addToSelection (item);
  33723. }
  33724. else if (modifiers.isCommandDown())
  33725. {
  33726. if (isSelected (item))
  33727. deselect (item);
  33728. else
  33729. addToSelection (item);
  33730. }
  33731. else
  33732. {
  33733. selectOnly (item);
  33734. }
  33735. }
  33736. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  33737. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  33738. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  33739. makes it easy to handle multiple-selection of sets of objects that can also
  33740. be dragged.
  33741. For example, if you have several items already selected, and you click on
  33742. one of them (without dragging), then you'd expect this to deselect the other, and
  33743. just select the item you clicked on. But if you had clicked on this item and
  33744. dragged it, you'd have expected them all to stay selected.
  33745. When you call this method, you'll need to store the boolean result, because the
  33746. addToSelectionOnMouseUp() method will need to be know this value.
  33747. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  33748. */
  33749. bool addToSelectionOnMouseDown (SelectableItemType item,
  33750. const ModifierKeys& modifiers)
  33751. {
  33752. if (isSelected (item))
  33753. {
  33754. return ! modifiers.isPopupMenu();
  33755. }
  33756. else
  33757. {
  33758. addToSelectionBasedOnModifiers (item, modifiers);
  33759. return false;
  33760. }
  33761. }
  33762. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  33763. Call this during a mouseUp callback, when you have previously called the
  33764. addToSelectionOnMouseDown() method during your mouseDown event.
  33765. See addToSelectionOnMouseDown() for more info
  33766. @param item the item to select (or deselect)
  33767. @param modifiers the modifiers from the mouse-up event
  33768. @param wasItemDragged true if your item was dragged during the mouse click
  33769. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  33770. back from the addToSelectionOnMouseDown() call that you
  33771. should have made during the matching mouseDown event
  33772. */
  33773. void addToSelectionOnMouseUp (SelectableItemType item,
  33774. const ModifierKeys& modifiers,
  33775. const bool wasItemDragged,
  33776. const bool resultOfMouseDownSelectMethod)
  33777. {
  33778. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  33779. addToSelectionBasedOnModifiers (item, modifiers);
  33780. }
  33781. /** Deselects an item. */
  33782. void deselect (SelectableItemType item)
  33783. {
  33784. const int i = selectedItems.indexOf (item);
  33785. if (i >= 0)
  33786. {
  33787. changed();
  33788. itemDeselected (selectedItems.remove (i));
  33789. }
  33790. }
  33791. /** Deselects all items. */
  33792. void deselectAll()
  33793. {
  33794. if (selectedItems.size() > 0)
  33795. {
  33796. changed();
  33797. for (int i = selectedItems.size(); --i >= 0;)
  33798. {
  33799. itemDeselected (selectedItems.remove (i));
  33800. i = jmin (i, selectedItems.size());
  33801. }
  33802. }
  33803. }
  33804. /** Returns the number of currently selected items.
  33805. @see getSelectedItem
  33806. */
  33807. int getNumSelected() const throw()
  33808. {
  33809. return selectedItems.size();
  33810. }
  33811. /** Returns one of the currently selected items.
  33812. Returns 0 if the index is out-of-range.
  33813. @see getNumSelected
  33814. */
  33815. SelectableItemType getSelectedItem (const int index) const throw()
  33816. {
  33817. return selectedItems [index];
  33818. }
  33819. /** True if this item is currently selected. */
  33820. bool isSelected (const SelectableItemType item) const throw()
  33821. {
  33822. return selectedItems.contains (item);
  33823. }
  33824. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  33825. /** Can be overridden to do special handling when an item is selected.
  33826. For example, if the item is an object, you might want to call it and tell
  33827. it that it's being selected.
  33828. */
  33829. virtual void itemSelected (SelectableItemType item) {}
  33830. /** Can be overridden to do special handling when an item is deselected.
  33831. For example, if the item is an object, you might want to call it and tell
  33832. it that it's being deselected.
  33833. */
  33834. virtual void itemDeselected (SelectableItemType item) {}
  33835. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  33836. */
  33837. void changed (const bool synchronous = false)
  33838. {
  33839. if (synchronous)
  33840. sendSynchronousChangeMessage (this);
  33841. else
  33842. sendChangeMessage (this);
  33843. }
  33844. juce_UseDebuggingNewOperator
  33845. private:
  33846. Array <SelectableItemType> selectedItems;
  33847. };
  33848. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  33849. /********* End of inlined file: juce_SelectedItemSet.h *********/
  33850. /**
  33851. A class used by the LassoComponent to manage the things that it selects.
  33852. This allows the LassoComponent to find out which items are within the lasso,
  33853. and to change the list of selected items.
  33854. @see LassoComponent, SelectedItemSet
  33855. */
  33856. template <class SelectableItemType>
  33857. class LassoSource
  33858. {
  33859. public:
  33860. /** Destructor. */
  33861. virtual ~LassoSource() {}
  33862. /** Returns the set of items that lie within a given lassoable region.
  33863. Your implementation of this method must find all the relevent items that lie
  33864. within the given rectangle. and add them to the itemsFound array.
  33865. The co-ordinates are relative to the top-left of the lasso component's parent
  33866. component. (i.e. they are the same as the size and position of the lasso
  33867. component itself).
  33868. */
  33869. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  33870. int x, int y, int width, int height) = 0;
  33871. /** Returns the SelectedItemSet that the lasso should update.
  33872. This set will be continuously updated by the LassoComponent as it gets
  33873. dragged around, so make sure that you've got a ChangeListener attached to
  33874. the set so that your UI objects will know when the selection changes and
  33875. be able to update themselves appropriately.
  33876. */
  33877. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  33878. };
  33879. /**
  33880. A component that acts as a rectangular selection region, which you drag with
  33881. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  33882. To use one of these:
  33883. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  33884. component, and call its beginLasso() method, giving it a
  33885. suitable LassoSource object that it can use to find out which items are in
  33886. the active area.
  33887. - Each time your parent component gets a mouseDrag event, call dragLasso()
  33888. to update the lasso's position - it will use its LassoSource to calculate and
  33889. update the current selection.
  33890. - After the drag has finished and you get a mouseUp callback, you should call
  33891. endLasso() to clean up. This will make the lasso component invisible, and you
  33892. can remove it from the parent component, or delete it.
  33893. The class takes into account the modifier keys that are being held down while
  33894. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  33895. be added to the original selection; if ctrl or command is pressed, they will be
  33896. xor'ed with any previously selected items.
  33897. @see LassoSource, SelectedItemSet
  33898. */
  33899. template <class SelectableItemType>
  33900. class LassoComponent : public Component
  33901. {
  33902. public:
  33903. /** Creates a Lasso component.
  33904. The fill colour is used to fill the lasso'ed rectangle, and the outline
  33905. colour is used to draw a line around its edge.
  33906. */
  33907. LassoComponent (const int outlineThickness_ = 1)
  33908. : source (0),
  33909. outlineThickness (outlineThickness_)
  33910. {
  33911. }
  33912. /** Destructor. */
  33913. ~LassoComponent()
  33914. {
  33915. }
  33916. /** Call this in your mouseDown event, to initialise a drag.
  33917. Pass in a suitable LassoSource object which the lasso will use to find
  33918. the items and change the selection.
  33919. After using this method to initialise the lasso, repeatedly call dragLasso()
  33920. in your component's mouseDrag callback.
  33921. @see dragLasso, endLasso, LassoSource
  33922. */
  33923. void beginLasso (const MouseEvent& e,
  33924. LassoSource <SelectableItemType>* const lassoSource)
  33925. {
  33926. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  33927. jassert (lassoSource != 0); // the source can't be null!
  33928. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  33929. source = lassoSource;
  33930. if (lassoSource != 0)
  33931. originalSelection = lassoSource->getLassoSelection().getItemArray();
  33932. setSize (0, 0);
  33933. }
  33934. /** Call this in your mouseDrag event, to update the lasso's position.
  33935. This must be repeatedly calling when the mouse is dragged, after you've
  33936. first initialised the lasso with beginLasso().
  33937. This method takes into account the modifier keys that are being held down, so
  33938. if shift is pressed, then the lassoed items will be added to any that were
  33939. previously selected; if ctrl or command is pressed, then they will be xor'ed
  33940. with previously selected items.
  33941. @see beginLasso, endLasso
  33942. */
  33943. void dragLasso (const MouseEvent& e)
  33944. {
  33945. if (source != 0)
  33946. {
  33947. const int x1 = e.getMouseDownX();
  33948. const int y1 = e.getMouseDownY();
  33949. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  33950. setVisible (true);
  33951. Array <SelectableItemType> itemsInLasso;
  33952. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  33953. if (e.mods.isShiftDown())
  33954. {
  33955. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  33956. itemsInLasso.addArray (originalSelection);
  33957. }
  33958. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  33959. {
  33960. Array <SelectableItemType> originalMinusNew (originalSelection);
  33961. originalMinusNew.removeValuesIn (itemsInLasso);
  33962. itemsInLasso.removeValuesIn (originalSelection);
  33963. itemsInLasso.addArray (originalMinusNew);
  33964. }
  33965. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  33966. }
  33967. }
  33968. /** Call this in your mouseUp event, after the lasso has been dragged.
  33969. @see beginLasso, dragLasso
  33970. */
  33971. void endLasso()
  33972. {
  33973. source = 0;
  33974. originalSelection.clear();
  33975. setVisible (false);
  33976. }
  33977. /** A set of colour IDs to use to change the colour of various aspects of the label.
  33978. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33979. methods.
  33980. Note that you can also use the constants from TextEditor::ColourIds to change the
  33981. colour of the text editor that is opened when a label is editable.
  33982. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33983. */
  33984. enum ColourIds
  33985. {
  33986. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  33987. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  33988. };
  33989. /** @internal */
  33990. void paint (Graphics& g)
  33991. {
  33992. g.fillAll (findColour (lassoFillColourId));
  33993. g.setColour (findColour (lassoOutlineColourId));
  33994. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33995. // this suggests that you've left a lasso comp lying around after the
  33996. // mouse drag has finished.. Be careful to call endLasso() when you get a
  33997. // mouse-up event.
  33998. jassert (isMouseButtonDownAnywhere());
  33999. }
  34000. /** @internal */
  34001. bool hitTest (int x, int y) { return false; }
  34002. juce_UseDebuggingNewOperator
  34003. private:
  34004. Array <SelectableItemType> originalSelection;
  34005. LassoSource <SelectableItemType>* source;
  34006. int outlineThickness;
  34007. };
  34008. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  34009. /********* End of inlined file: juce_LassoComponent.h *********/
  34010. #endif
  34011. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  34012. #endif
  34013. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  34014. #endif
  34015. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34016. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  34017. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34018. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34019. /**
  34020. Monitors a component for mouse activity, and triggers a callback
  34021. when the mouse hovers in one place for a specified length of time.
  34022. To use a hover-detector, just create one and call its setHoverComponent()
  34023. method to start it watching a component. You can call setHoverComponent (0)
  34024. to make it inactive.
  34025. (Be careful not to delete a component that's being monitored without first
  34026. stopping or deleting the hover detector).
  34027. */
  34028. class JUCE_API MouseHoverDetector
  34029. {
  34030. public:
  34031. /** Creates a hover detector.
  34032. Initially the object is inactive, and you need to tell it which component
  34033. to monitor, using the setHoverComponent() method.
  34034. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  34035. needs to stay still before the mouseHovered() method
  34036. is invoked. You can change this setting later with
  34037. the setHoverTimeMillisecs() method
  34038. */
  34039. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  34040. /** Destructor. */
  34041. virtual ~MouseHoverDetector();
  34042. /** Changes the time for which the mouse has to stay still before it's considered
  34043. to be hovering.
  34044. */
  34045. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  34046. /** Changes the component that's being monitored for hovering.
  34047. Be careful not to delete a component that's being monitored without first
  34048. stopping or deleting the hover detector.
  34049. */
  34050. void setHoverComponent (Component* const newSourceComponent);
  34051. protected:
  34052. /** Called back when the mouse hovers.
  34053. After the mouse has stayed still over the component for the length of time
  34054. specified by setHoverTimeMillisecs(), this method will be invoked.
  34055. When the mouse is first moved after this callback has occurred, the
  34056. mouseMovedAfterHover() method will be called.
  34057. @param mouseX the mouse's X position relative to the component being monitored
  34058. @param mouseY the mouse's Y position relative to the component being monitored
  34059. */
  34060. virtual void mouseHovered (int mouseX,
  34061. int mouseY) = 0;
  34062. /** Called when the mouse is moved away after just having hovered. */
  34063. virtual void mouseMovedAfterHover() = 0;
  34064. private:
  34065. class JUCE_API HoverDetectorInternal : public MouseListener,
  34066. public Timer
  34067. {
  34068. public:
  34069. MouseHoverDetector* owner;
  34070. int lastX, lastY;
  34071. void timerCallback();
  34072. void mouseEnter (const MouseEvent&);
  34073. void mouseExit (const MouseEvent&);
  34074. void mouseDown (const MouseEvent&);
  34075. void mouseUp (const MouseEvent&);
  34076. void mouseMove (const MouseEvent&);
  34077. void mouseWheelMove (const MouseEvent&, float, float);
  34078. } internalTimer;
  34079. friend class HoverDetectorInternal;
  34080. Component* source;
  34081. int hoverTimeMillisecs;
  34082. bool hasJustHovered;
  34083. void hoverTimerCallback();
  34084. void checkJustHoveredCallback();
  34085. };
  34086. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  34087. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  34088. #endif
  34089. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  34090. #endif
  34091. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  34092. #endif
  34093. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34094. #endif
  34095. #ifndef __JUCE_LABEL_JUCEHEADER__
  34096. #endif
  34097. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34098. #endif
  34099. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34100. /********* Start of inlined file: juce_ProgressBar.h *********/
  34101. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34102. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34103. /**
  34104. A progress bar component.
  34105. To use this, just create one and make it visible. It'll run its own timer
  34106. to keep an eye on a variable that you give it, and will automatically
  34107. redraw itself when the variable changes.
  34108. For an easy way of running a background task with a dialog box showing its
  34109. progress, see the ThreadWithProgressWindow class.
  34110. @see ThreadWithProgressWindow
  34111. */
  34112. class JUCE_API ProgressBar : public Component,
  34113. public SettableTooltipClient,
  34114. private Timer
  34115. {
  34116. public:
  34117. /** Creates a ProgressBar.
  34118. @param progress pass in a reference to a double that you're going to
  34119. update with your task's progress. The ProgressBar will
  34120. monitor the value of this variable and will redraw itself
  34121. when the value changes. The range is from 0 to 1.0. Obviously
  34122. you'd better be careful not to delete this variable while the
  34123. ProgressBar still exists!
  34124. */
  34125. ProgressBar (double& progress);
  34126. /** Destructor. */
  34127. ~ProgressBar();
  34128. /** Turns the percentage display on or off.
  34129. By default this is on, and the progress bar will display a text string showing
  34130. its current percentage.
  34131. */
  34132. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34133. /** Gives the progress bar a string to display inside it.
  34134. If you call this, it will turn off the percentage display.
  34135. @see setPercentageDisplay
  34136. */
  34137. void setTextToDisplay (const String& text);
  34138. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34139. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34140. methods.
  34141. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34142. */
  34143. enum ColourIds
  34144. {
  34145. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34146. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34147. classes will probably use variations on this colour. */
  34148. };
  34149. juce_UseDebuggingNewOperator
  34150. protected:
  34151. /** @internal */
  34152. void paint (Graphics& g);
  34153. /** @internal */
  34154. void lookAndFeelChanged();
  34155. /** @internal */
  34156. void visibilityChanged();
  34157. /** @internal */
  34158. void colourChanged();
  34159. private:
  34160. double& progress;
  34161. double currentValue;
  34162. bool displayPercentage;
  34163. String displayedMessage, currentMessage;
  34164. uint32 lastCallbackTime;
  34165. void timerCallback();
  34166. ProgressBar (const ProgressBar&);
  34167. const ProgressBar& operator= (const ProgressBar&);
  34168. };
  34169. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34170. /********* End of inlined file: juce_ProgressBar.h *********/
  34171. #endif
  34172. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34173. /********* Start of inlined file: juce_Slider.h *********/
  34174. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34175. #define __JUCE_SLIDER_JUCEHEADER__
  34176. /********* Start of inlined file: juce_SliderListener.h *********/
  34177. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34178. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  34179. class Slider;
  34180. /**
  34181. A class for receiving callbacks from a Slider.
  34182. To be told when a slider's value changes, you can register a SliderListener
  34183. object using Slider::addListener().
  34184. @see Slider::addListener, Slider::removeListener
  34185. */
  34186. class JUCE_API SliderListener
  34187. {
  34188. public:
  34189. /** Destructor. */
  34190. virtual ~SliderListener() {}
  34191. /** Called when the slider's value is changed.
  34192. This may be caused by dragging it, or by typing in its text entry box,
  34193. or by a call to Slider::setValue().
  34194. You can find out the new value using Slider::getValue().
  34195. @see Slider::valueChanged
  34196. */
  34197. virtual void sliderValueChanged (Slider* slider) = 0;
  34198. /** Called when the slider is about to be dragged.
  34199. This is called when a drag begins, then it's followed by multiple calls
  34200. to sliderValueChanged(), and then sliderDragEnded() is called after the
  34201. user lets go.
  34202. @see sliderDragEnded, Slider::startedDragging
  34203. */
  34204. virtual void sliderDragStarted (Slider* slider);
  34205. /** Called after a drag operation has finished.
  34206. @see sliderDragStarted, Slider::stoppedDragging
  34207. */
  34208. virtual void sliderDragEnded (Slider* slider);
  34209. };
  34210. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  34211. /********* End of inlined file: juce_SliderListener.h *********/
  34212. /**
  34213. A slider control for changing a value.
  34214. The slider can be horizontal, vertical, or rotary, and can optionally have
  34215. a text-box inside it to show an editable display of the current value.
  34216. To use it, create a Slider object and use the setSliderStyle() method
  34217. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  34218. To define the values that it can be set to, see the setRange() and setValue() methods.
  34219. There are also lots of custom tweaks you can do by subclassing and overriding
  34220. some of the virtual methods, such as changing the scaling, changing the format of
  34221. the text display, custom ways of limiting the values, etc.
  34222. You can register SliderListeners with a slider, which will be informed when the value
  34223. changes, or a subclass can override valueChanged() to be informed synchronously.
  34224. @see SliderListener
  34225. */
  34226. class JUCE_API Slider : public Component,
  34227. public SettableTooltipClient,
  34228. private AsyncUpdater,
  34229. private ButtonListener,
  34230. private LabelListener
  34231. {
  34232. public:
  34233. /** Creates a slider.
  34234. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  34235. setRange(), etc.
  34236. */
  34237. Slider (const String& componentName);
  34238. /** Destructor. */
  34239. ~Slider();
  34240. /** The types of slider available.
  34241. @see setSliderStyle, setRotaryParameters
  34242. */
  34243. enum SliderStyle
  34244. {
  34245. LinearHorizontal, /**< A traditional horizontal slider. */
  34246. LinearVertical, /**< A traditional vertical slider. */
  34247. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  34248. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  34249. @see setRotaryParameters */
  34250. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  34251. @see setRotaryParameters */
  34252. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  34253. @see setRotaryParameters */
  34254. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  34255. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34256. @see setMinValue, setMaxValue */
  34257. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34258. @see setMinValue, setMaxValue */
  34259. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  34260. value, with the current value being somewhere between them.
  34261. @see setMinValue, setMaxValue */
  34262. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  34263. value, with the current value being somewhere between them.
  34264. @see setMinValue, setMaxValue */
  34265. };
  34266. /** Changes the type of slider interface being used.
  34267. @param newStyle the type of interface
  34268. @see setRotaryParameters, setVelocityBasedMode,
  34269. */
  34270. void setSliderStyle (const SliderStyle newStyle);
  34271. /** Returns the slider's current style.
  34272. @see setSliderStyle
  34273. */
  34274. SliderStyle getSliderStyle() const throw() { return style; }
  34275. /** Changes the properties of a rotary slider.
  34276. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  34277. the slider's minimum value is represented
  34278. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  34279. the slider's maximum value is represented. This must be
  34280. greater than startAngleRadians
  34281. @param stopAtEnd if true, then when the slider is dragged around past the
  34282. minimum or maximum, it'll stop there; if false, it'll wrap
  34283. back to the opposite value
  34284. */
  34285. void setRotaryParameters (const float startAngleRadians,
  34286. const float endAngleRadians,
  34287. const bool stopAtEnd);
  34288. /** Sets the distance the mouse has to move to drag the slider across
  34289. the full extent of its range.
  34290. This only applies when in modes like RotaryHorizontalDrag, where it's using
  34291. relative mouse movements to adjust the slider.
  34292. */
  34293. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  34294. /** Changes the way the the mouse is used when dragging the slider.
  34295. If true, this will turn on velocity-sensitive dragging, so that
  34296. the faster the mouse moves, the bigger the movement to the slider. This
  34297. helps when making accurate adjustments if the slider's range is quite large.
  34298. If false, the slider will just try to snap to wherever the mouse is.
  34299. */
  34300. void setVelocityBasedMode (const bool isVelocityBased) throw();
  34301. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  34302. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  34303. or if you're holding down ctrl.
  34304. @param sensitivity higher values than 1.0 increase the range of acceleration used
  34305. @param threshold the minimum number of pixels that the mouse needs to move for it
  34306. to be treated as a movement
  34307. @param offset values greater than 0.0 increase the minimum speed that will be used when
  34308. the threshold is reached
  34309. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  34310. key to toggle velocity-sensitive mode
  34311. */
  34312. void setVelocityModeParameters (const double sensitivity = 1.0,
  34313. const int threshold = 1,
  34314. const double offset = 0.0,
  34315. const bool userCanPressKeyToSwapMode = true) throw();
  34316. /** Sets up a skew factor to alter the way values are distributed.
  34317. You may want to use a range of values on the slider where more accuracy
  34318. is required towards one end of the range, so this will logarithmically
  34319. spread the values across the length of the slider.
  34320. If the factor is < 1.0, the lower end of the range will fill more of the
  34321. slider's length; if the factor is > 1.0, the upper end of the range
  34322. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  34323. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  34324. method instead.
  34325. @see getSkewFactor, setSkewFactorFromMidPoint
  34326. */
  34327. void setSkewFactor (const double factor) throw();
  34328. /** Sets up a skew factor to alter the way values are distributed.
  34329. This allows you to specify the slider value that should appear in the
  34330. centre of the slider's visible range.
  34331. @see setSkewFactor, getSkewFactor
  34332. */
  34333. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  34334. /** Returns the current skew factor.
  34335. See setSkewFactor for more info.
  34336. @see setSkewFactor, setSkewFactorFromMidPoint
  34337. */
  34338. double getSkewFactor() const throw() { return skewFactor; }
  34339. /** Used by setIncDecButtonsMode().
  34340. */
  34341. enum IncDecButtonMode
  34342. {
  34343. incDecButtonsNotDraggable,
  34344. incDecButtonsDraggable_AutoDirection,
  34345. incDecButtonsDraggable_Horizontal,
  34346. incDecButtonsDraggable_Vertical
  34347. };
  34348. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  34349. can be dragged on the buttons to drag the values.
  34350. By default this is turned off. When enabled, clicking on the buttons still works
  34351. them as normal, but by holding down the mouse on a button and dragging it a little
  34352. distance, it flips into a mode where the value can be dragged. The drag direction can
  34353. either be set explicitly to be vertical or horizontal, or can be set to
  34354. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  34355. are side-by-side or above each other.
  34356. */
  34357. void setIncDecButtonsMode (const IncDecButtonMode mode);
  34358. /** The position of the slider's text-entry box.
  34359. @see setTextBoxStyle
  34360. */
  34361. enum TextEntryBoxPosition
  34362. {
  34363. NoTextBox, /**< Doesn't display a text box. */
  34364. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  34365. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  34366. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  34367. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  34368. };
  34369. /** Changes the location and properties of the text-entry box.
  34370. @param newPosition where it should go (or NoTextBox to not have one at all)
  34371. @param isReadOnly if true, it's a read-only display
  34372. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  34373. room for the slider as well!
  34374. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  34375. room for the slider as well!
  34376. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  34377. */
  34378. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  34379. const bool isReadOnly,
  34380. const int textEntryBoxWidth,
  34381. const int textEntryBoxHeight);
  34382. /** Returns the status of the text-box.
  34383. @see setTextBoxStyle
  34384. */
  34385. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  34386. /** Returns the width used for the text-box.
  34387. @see setTextBoxStyle
  34388. */
  34389. int getTextBoxWidth() const throw() { return textBoxWidth; }
  34390. /** Returns the height used for the text-box.
  34391. @see setTextBoxStyle
  34392. */
  34393. int getTextBoxHeight() const throw() { return textBoxHeight; }
  34394. /** Makes the text-box editable.
  34395. By default this is true, and the user can enter values into the textbox,
  34396. but it can be turned off if that's not suitable.
  34397. @see setTextBoxStyle, getValueFromText, getTextFromValue
  34398. */
  34399. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  34400. /** Returns true if the text-box is read-only.
  34401. @see setTextBoxStyle
  34402. */
  34403. bool isTextBoxEditable() const throw() { return editableText; }
  34404. /** If the text-box is editable, this will give it the focus so that the user can
  34405. type directly into it.
  34406. This is basically the effect as the user clicking on it.
  34407. */
  34408. void showTextBox();
  34409. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  34410. focus away from it.
  34411. @param discardCurrentEditorContents if true, the slider's value will be left
  34412. unchanged; if false, the current contents of the
  34413. text editor will be used to set the slider position
  34414. before it is hidden.
  34415. */
  34416. void hideTextBox (const bool discardCurrentEditorContents);
  34417. /** Changes the slider's current value.
  34418. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34419. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34420. want to handle it.
  34421. @param newValue the new value to set - this will be restricted by the
  34422. minimum and maximum range, and will be snapped to the
  34423. nearest interval if one has been set
  34424. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34425. any SliderListeners or the valueChanged() method
  34426. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34427. synchronously; if false, it will be asynchronous
  34428. */
  34429. void setValue (double newValue,
  34430. const bool sendUpdateMessage = true,
  34431. const bool sendMessageSynchronously = false);
  34432. /** Returns the slider's current value. */
  34433. double getValue() const throw();
  34434. /** Sets the limits that the slider's value can take.
  34435. @param newMinimum the lowest value allowed
  34436. @param newMaximum the highest value allowed
  34437. @param newInterval the steps in which the value is allowed to increase - if this
  34438. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  34439. */
  34440. void setRange (const double newMinimum,
  34441. const double newMaximum,
  34442. const double newInterval = 0);
  34443. /** Returns the current maximum value.
  34444. @see setRange
  34445. */
  34446. double getMaximum() const throw() { return maximum; }
  34447. /** Returns the current minimum value.
  34448. @see setRange
  34449. */
  34450. double getMinimum() const throw() { return minimum; }
  34451. /** Returns the current step-size for values.
  34452. @see setRange
  34453. */
  34454. double getInterval() const throw() { return interval; }
  34455. /** For a slider with two or three thumbs, this returns the lower of its values.
  34456. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34457. A slider with three values also uses the normal getValue() and setValue() methods to
  34458. control the middle value.
  34459. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34460. */
  34461. double getMinValue() const throw();
  34462. /** For a slider with two or three thumbs, this sets the lower of its values.
  34463. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34464. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34465. want to handle it.
  34466. @param newValue the new value to set - this will be restricted by the
  34467. minimum and maximum range, and will be snapped to the nearest
  34468. interval if one has been set.
  34469. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34470. any SliderListeners or the valueChanged() method
  34471. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34472. synchronously; if false, it will be asynchronous
  34473. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34474. max value (in a two-value slider) or the mid value (in a three-value
  34475. slider). If false, then if this value goes beyond those values,
  34476. it will push them along with it.
  34477. @see getMinValue, setMaxValue, setValue
  34478. */
  34479. void setMinValue (double newValue,
  34480. const bool sendUpdateMessage = true,
  34481. const bool sendMessageSynchronously = false,
  34482. const bool allowNudgingOfOtherValues = false);
  34483. /** For a slider with two or three thumbs, this returns the higher of its values.
  34484. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34485. A slider with three values also uses the normal getValue() and setValue() methods to
  34486. control the middle value.
  34487. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34488. */
  34489. double getMaxValue() const throw();
  34490. /** For a slider with two or three thumbs, this sets the lower of its values.
  34491. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34492. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34493. want to handle it.
  34494. @param newValue the new value to set - this will be restricted by the
  34495. minimum and maximum range, and will be snapped to the nearest
  34496. interval if one has been set.
  34497. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34498. any SliderListeners or the valueChanged() method
  34499. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34500. synchronously; if false, it will be asynchronous
  34501. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34502. min value (in a two-value slider) or the mid value (in a three-value
  34503. slider). If false, then if this value goes beyond those values,
  34504. it will push them along with it.
  34505. @see getMaxValue, setMinValue, setValue
  34506. */
  34507. void setMaxValue (double newValue,
  34508. const bool sendUpdateMessage = true,
  34509. const bool sendMessageSynchronously = false,
  34510. const bool allowNudgingOfOtherValues = false);
  34511. /** Adds a listener to be called when this slider's value changes. */
  34512. void addListener (SliderListener* const listener) throw();
  34513. /** Removes a previously-registered listener. */
  34514. void removeListener (SliderListener* const listener) throw();
  34515. /** This lets you choose whether double-clicking moves the slider to a given position.
  34516. By default this is turned off, but it's handy if you want a double-click to act
  34517. as a quick way of resetting a slider. Just pass in the value you want it to
  34518. go to when double-clicked.
  34519. @see getDoubleClickReturnValue
  34520. */
  34521. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  34522. const double valueToSetOnDoubleClick) throw();
  34523. /** Returns the values last set by setDoubleClickReturnValue() method.
  34524. Sets isEnabled to true if double-click is enabled, and returns the value
  34525. that was set.
  34526. @see setDoubleClickReturnValue
  34527. */
  34528. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  34529. /** Tells the slider whether to keep sending change messages while the user
  34530. is dragging the slider.
  34531. If set to true, a change message will only be sent when the user has
  34532. dragged the slider and let go. If set to false (the default), then messages
  34533. will be continuously sent as they drag it while the mouse button is still
  34534. held down.
  34535. */
  34536. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  34537. /** This lets you change whether the slider thumb jumps to the mouse position
  34538. when you click.
  34539. By default, this is true. If it's false, then the slider moves with relative
  34540. motion when you drag it.
  34541. This only applies to linear bars, and won't affect two- or three- value
  34542. sliders.
  34543. */
  34544. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  34545. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34546. slider is being dragged.
  34547. This can be handy if your slider doesn't have a text-box, so that users can
  34548. see the value just when they're changing it.
  34549. If you pass a component as the parentComponentToUse parameter, the pop-up
  34550. bubble will be added as a child of that component when it's needed. If you
  34551. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34552. transparent window, so if you're using an OS that can't do transparent windows
  34553. you'll have to add it to a parent component instead).
  34554. */
  34555. void setPopupDisplayEnabled (const bool isEnabled,
  34556. Component* const parentComponentToUse) throw();
  34557. /** If this is set to true, then right-clicking on the slider will pop-up
  34558. a menu to let the user change the way it works.
  34559. By default this is turned off, but when turned on, the menu will include
  34560. things like velocity sensitivity, and for rotary sliders, whether they
  34561. use a linear or rotary mouse-drag to move them.
  34562. */
  34563. void setPopupMenuEnabled (const bool menuEnabled) throw();
  34564. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34565. By default it's enabled.
  34566. */
  34567. void setScrollWheelEnabled (const bool enabled) throw();
  34568. /** Returns a number to indicate which thumb is currently being dragged by the
  34569. mouse.
  34570. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34571. the maximum-value thumb, or -1 if none is currently down.
  34572. */
  34573. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  34574. /** Callback to indicate that the user is about to start dragging the slider.
  34575. @see SliderListener::sliderDragStarted
  34576. */
  34577. virtual void startedDragging();
  34578. /** Callback to indicate that the user has just stopped dragging the slider.
  34579. @see SliderListener::sliderDragEnded
  34580. */
  34581. virtual void stoppedDragging();
  34582. /** Callback to indicate that the user has just moved the slider.
  34583. @see SliderListener::sliderValueChanged
  34584. */
  34585. virtual void valueChanged();
  34586. /** Callback to indicate that the user has just moved the slider.
  34587. Note - the valueChanged() method has changed its format and now no longer has
  34588. any parameters. Update your code to use the new version.
  34589. This version has been left here with an int as its return value to cause
  34590. a syntax error if you've got existing code that uses the old version.
  34591. */
  34592. virtual int valueChanged (double) { jassertfalse; return 0; }
  34593. /** Subclasses can override this to convert a text string to a value.
  34594. When the user enters something into the text-entry box, this method is
  34595. called to convert it to a value.
  34596. The default routine just tries to convert it to a double.
  34597. @see getTextFromValue
  34598. */
  34599. virtual double getValueFromText (const String& text);
  34600. /** Turns the slider's current value into a text string.
  34601. Subclasses can override this to customise the formatting of the text-entry box.
  34602. The default implementation just turns the value into a string, using
  34603. a number of decimal places based on the range interval. If a suffix string
  34604. has been set using setTextValueSuffix(), this will be appended to the text.
  34605. @see getValueFromText
  34606. */
  34607. virtual const String getTextFromValue (double value);
  34608. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34609. a string.
  34610. This is used by the default implementation of getTextFromValue(), and is just
  34611. appended to the numeric value. For more advanced formatting, you can override
  34612. getTextFromValue() and do something else.
  34613. */
  34614. void setTextValueSuffix (const String& suffix);
  34615. /** Allows a user-defined mapping of distance along the slider to its value.
  34616. The default implementation for this performs the skewing operation that
  34617. can be set up in the setSkewFactor() method. Override it if you need
  34618. some kind of custom mapping instead, but make sure you also implement the
  34619. inverse function in valueToProportionOfLength().
  34620. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34621. @returns the slider value that is represented by this position
  34622. @see valueToProportionOfLength
  34623. */
  34624. virtual double proportionOfLengthToValue (double proportion);
  34625. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34626. The default implementation for this performs the skewing operation that
  34627. can be set up in the setSkewFactor() method. Override it if you need
  34628. some kind of custom mapping instead, but make sure you also implement the
  34629. inverse function in proportionOfLengthToValue().
  34630. @param value a valid slider value, between the range of values specified in
  34631. setRange()
  34632. @returns a value 0 to 1.0 indicating the distance along the slider that
  34633. represents this value
  34634. @see proportionOfLengthToValue
  34635. */
  34636. virtual double valueToProportionOfLength (double value);
  34637. /** Returns the X or Y coordinate of a value along the slider's length.
  34638. If the slider is horizontal, this will be the X coordinate of the given
  34639. value, relative to the left of the slider. If it's vertical, then this will
  34640. be the Y coordinate, relative to the top of the slider.
  34641. If the slider is rotary, this will throw an assertion and return 0. If the
  34642. value is out-of-range, it will be constrained to the length of the slider.
  34643. */
  34644. float getPositionOfValue (const double value);
  34645. /** This can be overridden to allow the slider to snap to user-definable values.
  34646. If overridden, it will be called when the user tries to move the slider to
  34647. a given position, and allows a subclass to sanity-check this value, possibly
  34648. returning a different value to use instead.
  34649. @param attemptedValue the value the user is trying to enter
  34650. @param userIsDragging true if the user is dragging with the mouse; false if
  34651. they are entering the value using the text box
  34652. @returns the value to use instead
  34653. */
  34654. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  34655. /** This can be called to force the text box to update its contents.
  34656. (Not normally needed, as this is done automatically).
  34657. */
  34658. void updateText();
  34659. /** True if the slider moves horizontally. */
  34660. bool isHorizontal() const throw();
  34661. /** True if the slider moves vertically. */
  34662. bool isVertical() const throw();
  34663. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34664. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34665. methods.
  34666. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34667. */
  34668. enum ColourIds
  34669. {
  34670. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34671. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34672. and feel class how this is used. */
  34673. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34674. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34675. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34676. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34677. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34678. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34679. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34680. };
  34681. juce_UseDebuggingNewOperator
  34682. protected:
  34683. /** @internal */
  34684. void labelTextChanged (Label*);
  34685. /** @internal */
  34686. void paint (Graphics& g);
  34687. /** @internal */
  34688. void resized();
  34689. /** @internal */
  34690. void mouseDown (const MouseEvent& e);
  34691. /** @internal */
  34692. void mouseUp (const MouseEvent& e);
  34693. /** @internal */
  34694. void mouseDrag (const MouseEvent& e);
  34695. /** @internal */
  34696. void mouseDoubleClick (const MouseEvent& e);
  34697. /** @internal */
  34698. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34699. /** @internal */
  34700. void modifierKeysChanged (const ModifierKeys& modifiers);
  34701. /** @internal */
  34702. void buttonClicked (Button* button);
  34703. /** @internal */
  34704. void lookAndFeelChanged();
  34705. /** @internal */
  34706. void enablementChanged();
  34707. /** @internal */
  34708. void focusOfChildComponentChanged (FocusChangeType cause);
  34709. /** @internal */
  34710. void handleAsyncUpdate();
  34711. /** @internal */
  34712. void colourChanged();
  34713. private:
  34714. SortedSet <void*> listeners;
  34715. double currentValue, valueMin, valueMax;
  34716. double minimum, maximum, interval, doubleClickReturnValue;
  34717. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34718. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34719. int velocityModeThreshold;
  34720. float rotaryStart, rotaryEnd;
  34721. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34722. int mouseDragStartX, mouseDragStartY;
  34723. int sliderRegionStart, sliderRegionSize;
  34724. int sliderBeingDragged;
  34725. int pixelsForFullDragExtent;
  34726. Rectangle sliderRect;
  34727. String textSuffix;
  34728. SliderStyle style;
  34729. TextEntryBoxPosition textBoxPos;
  34730. int textBoxWidth, textBoxHeight;
  34731. IncDecButtonMode incDecButtonMode;
  34732. bool editableText : 1, doubleClickToValue : 1;
  34733. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34734. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34735. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34736. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34737. Font font;
  34738. Label* valueBox;
  34739. Button* incButton;
  34740. Button* decButton;
  34741. Component* popupDisplay;
  34742. Component* parentForPopupDisplay;
  34743. float getLinearSliderPos (const double value);
  34744. void restoreMouseIfHidden();
  34745. void sendDragStart();
  34746. void sendDragEnd();
  34747. double constrainedValue (double value) const throw();
  34748. void triggerChangeMessage (const bool synchronous);
  34749. bool incDecDragDirectionIsHorizontal() const throw();
  34750. Slider (const Slider&);
  34751. const Slider& operator= (const Slider&);
  34752. };
  34753. #endif // __JUCE_SLIDER_JUCEHEADER__
  34754. /********* End of inlined file: juce_Slider.h *********/
  34755. #endif
  34756. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34757. #endif
  34758. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34759. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  34760. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34761. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34762. class TableHeaderComponent;
  34763. /**
  34764. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  34765. You can register one of these objects for table events using TableHeaderComponent::addListener()
  34766. and TableHeaderComponent::removeListener().
  34767. @see TableHeaderComponent
  34768. */
  34769. class JUCE_API TableHeaderListener
  34770. {
  34771. public:
  34772. TableHeaderListener() {}
  34773. /** Destructor. */
  34774. virtual ~TableHeaderListener() {}
  34775. /** This is called when some of the table's columns are added, removed, hidden,
  34776. or rearranged.
  34777. */
  34778. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  34779. /** This is called when one or more of the table's columns are resized.
  34780. */
  34781. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  34782. /** This is called when the column by which the table should be sorted is changed.
  34783. */
  34784. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  34785. /** This is called when the user begins or ends dragging one of the columns around.
  34786. When the user starts dragging a column, this is called with the ID of that
  34787. column. When they finish dragging, it is called again with 0 as the ID.
  34788. */
  34789. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  34790. int columnIdNowBeingDragged);
  34791. };
  34792. /**
  34793. A component that displays a strip of column headings for a table, and allows these
  34794. to be resized, dragged around, etc.
  34795. This is just the component that goes at the top of a table. You can use it
  34796. directly for custom components, or to create a simple table, use the
  34797. TableListBox class.
  34798. To use one of these, create it and use addColumn() to add all the columns that you need.
  34799. Each column must be given a unique ID number that's used to refer to it.
  34800. @see TableListBox, TableHeaderListener
  34801. */
  34802. class JUCE_API TableHeaderComponent : public Component,
  34803. private AsyncUpdater
  34804. {
  34805. public:
  34806. /** Creates an empty table header.
  34807. */
  34808. TableHeaderComponent();
  34809. /** Destructor. */
  34810. ~TableHeaderComponent();
  34811. /** A combination of these flags are passed into the addColumn() method to specify
  34812. the properties of a column.
  34813. */
  34814. enum ColumnPropertyFlags
  34815. {
  34816. 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. */
  34817. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  34818. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  34819. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  34820. 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. */
  34821. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  34822. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  34823. /** This set of default flags is used as the default parameter value in addColumn(). */
  34824. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  34825. /** A quick way of combining flags for a column that's not resizable. */
  34826. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  34827. /** A quick way of combining flags for a column that's not resizable or sortable. */
  34828. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  34829. /** A quick way of combining flags for a column that's not sortable. */
  34830. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  34831. };
  34832. /** Adds a column to the table.
  34833. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  34834. registered listeners.
  34835. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  34836. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  34837. a unique ID. This is used to identify the column later on, after the user may have
  34838. changed the order that they appear in
  34839. @param width the initial width of the column, in pixels
  34840. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  34841. if the 'resizable' flag is specified for this column
  34842. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  34843. if the 'resizable' flag is specified for this column
  34844. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  34845. properties of this column
  34846. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  34847. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  34848. all columns, not just the index amongst those that are currently visible
  34849. */
  34850. void addColumn (const String& columnName,
  34851. const int columnId,
  34852. const int width,
  34853. const int minimumWidth = 30,
  34854. const int maximumWidth = -1,
  34855. const int propertyFlags = defaultFlags,
  34856. const int insertIndex = -1);
  34857. /** Removes a column with the given ID.
  34858. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  34859. registered listeners.
  34860. */
  34861. void removeColumn (const int columnIdToRemove);
  34862. /** Deletes all columns from the table.
  34863. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  34864. registered listeners.
  34865. */
  34866. void removeAllColumns();
  34867. /** Returns the number of columns in the table.
  34868. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  34869. return the total number of columns, including hidden ones.
  34870. @see isColumnVisible
  34871. */
  34872. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  34873. /** Returns the name for a column.
  34874. @see setColumnName
  34875. */
  34876. const String getColumnName (const int columnId) const throw();
  34877. /** Changes the name of a column. */
  34878. void setColumnName (const int columnId, const String& newName);
  34879. /** Moves a column to a different index in the table.
  34880. @param columnId the column to move
  34881. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  34882. */
  34883. void moveColumn (const int columnId, int newVisibleIndex);
  34884. /** Changes the width of a column.
  34885. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  34886. */
  34887. void setColumnWidth (const int columnId, const int newWidth);
  34888. /** Shows or hides a column.
  34889. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  34890. @see isColumnVisible
  34891. */
  34892. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  34893. /** Returns true if this column is currently visible.
  34894. @see setColumnVisible
  34895. */
  34896. bool isColumnVisible (const int columnId) const;
  34897. /** Changes the column which is the sort column.
  34898. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  34899. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  34900. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  34901. @see getSortColumnId, isSortedForwards, reSortTable
  34902. */
  34903. void setSortColumnId (const int columnId, const bool sortForwards);
  34904. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  34905. @see setSortColumnId, isSortedForwards
  34906. */
  34907. int getSortColumnId() const throw();
  34908. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  34909. @see setSortColumnId
  34910. */
  34911. bool isSortedForwards() const throw();
  34912. /** Triggers a re-sort of the table according to the current sort-column.
  34913. If you modifiy the table's contents, you can call this to signal that the table needs
  34914. to be re-sorted.
  34915. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  34916. tableSortOrderChanged() method of any listeners).
  34917. */
  34918. void reSortTable();
  34919. /** Returns the total width of all the visible columns in the table.
  34920. */
  34921. int getTotalWidth() const throw();
  34922. /** Returns the index of a given column.
  34923. If there's no such column ID, this will return -1.
  34924. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  34925. otherwise it'll return the index amongst all the columns, including any hidden ones.
  34926. */
  34927. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  34928. /** Returns the ID of the column at a given index.
  34929. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  34930. otherwise it'll count it amongst all the columns, including any hidden ones.
  34931. If the index is out-of-range, it'll return 0.
  34932. */
  34933. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  34934. /** Returns the rectangle containing of one of the columns.
  34935. The index is an index from 0 to the number of columns that are currently visible (hidden
  34936. ones are not counted). It returns a rectangle showing the position of the column relative
  34937. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  34938. */
  34939. const Rectangle getColumnPosition (const int index) const throw();
  34940. /** Finds the column ID at a given x-position in the component.
  34941. If there is a column at this point this returns its ID, or if not, it will return 0.
  34942. */
  34943. int getColumnIdAtX (const int xToFind) const throw();
  34944. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  34945. entire width of the component.
  34946. By default this is disabled. Turning it on also means that when resizing a column, those
  34947. on the right will be squashed to fit.
  34948. */
  34949. void setStretchToFitActive (const bool shouldStretchToFit);
  34950. /** Returns true if stretch-to-fit has been enabled.
  34951. @see setStretchToFitActive
  34952. */
  34953. bool isStretchToFitActive() const throw();
  34954. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34955. specified width, keeping their relative proportions the same.
  34956. If the minimum widths of the columns are too wide to fit into this space, it may
  34957. actually end up wider.
  34958. */
  34959. void resizeAllColumnsToFit (int targetTotalWidth);
  34960. /** Enables or disables the pop-up menu.
  34961. The default menu allows the user to show or hide columns. You can add custom
  34962. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34963. By default the menu is enabled.
  34964. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34965. */
  34966. void setPopupMenuActive (const bool hasMenu);
  34967. /** Returns true if the pop-up menu is enabled.
  34968. @see setPopupMenuActive
  34969. */
  34970. bool isPopupMenuActive() const throw();
  34971. /** Returns a string that encapsulates the table's current layout.
  34972. This can be restored later using restoreFromString(). It saves the order of
  34973. the columns, the currently-sorted column, and the widths.
  34974. @see restoreFromString
  34975. */
  34976. const String toString() const;
  34977. /** Restores the state of the table, based on a string previously created with
  34978. toString().
  34979. @see toString
  34980. */
  34981. void restoreFromString (const String& storedVersion);
  34982. /** Adds a listener to be informed about things that happen to the header. */
  34983. void addListener (TableHeaderListener* const newListener) throw();
  34984. /** Removes a previously-registered listener. */
  34985. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  34986. /** This can be overridden to handle a mouse-click on one of the column headers.
  34987. The default implementation will use this click to call getSortColumnId() and
  34988. change the sort order.
  34989. */
  34990. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34991. /** This can be overridden to add custom items to the pop-up menu.
  34992. If you override this, you should call the superclass's method to add its
  34993. column show/hide items, if you want them on the menu as well.
  34994. Then to handle the result, override reactToMenuItem().
  34995. @see reactToMenuItem
  34996. */
  34997. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  34998. /** Override this to handle any custom items that you have added to the
  34999. pop-up menu with an addMenuItems() override.
  35000. If the menuReturnId isn't one of your own custom menu items, you'll need to
  35001. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  35002. handle the items that it had added.
  35003. @see addMenuItems
  35004. */
  35005. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  35006. /** @internal */
  35007. void paint (Graphics& g);
  35008. /** @internal */
  35009. void resized();
  35010. /** @internal */
  35011. void mouseMove (const MouseEvent&);
  35012. /** @internal */
  35013. void mouseEnter (const MouseEvent&);
  35014. /** @internal */
  35015. void mouseExit (const MouseEvent&);
  35016. /** @internal */
  35017. void mouseDown (const MouseEvent&);
  35018. /** @internal */
  35019. void mouseDrag (const MouseEvent&);
  35020. /** @internal */
  35021. void mouseUp (const MouseEvent&);
  35022. /** @internal */
  35023. const MouseCursor getMouseCursor();
  35024. /** Can be overridden for more control over the pop-up menu behaviour. */
  35025. virtual void showColumnChooserMenu (const int columnIdClicked);
  35026. juce_UseDebuggingNewOperator
  35027. private:
  35028. struct ColumnInfo
  35029. {
  35030. String name;
  35031. int id, propertyFlags, width, minimumWidth, maximumWidth;
  35032. double lastDeliberateWidth;
  35033. bool isVisible() const throw();
  35034. };
  35035. OwnedArray <ColumnInfo> columns;
  35036. Array <TableHeaderListener*> listeners;
  35037. Component* dragOverlayComp;
  35038. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  35039. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  35040. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  35041. ColumnInfo* getInfoForId (const int columnId) const throw();
  35042. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  35043. void sendColumnsChanged();
  35044. void handleAsyncUpdate();
  35045. void beginDrag (const MouseEvent&);
  35046. void endDrag (const int finalIndex);
  35047. int getResizeDraggerAt (const int mouseX) const throw();
  35048. void updateColumnUnderMouse (int x, int y);
  35049. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  35050. TableHeaderComponent (const TableHeaderComponent&);
  35051. const TableHeaderComponent operator= (const TableHeaderComponent&);
  35052. };
  35053. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35054. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  35055. #endif
  35056. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35057. /********* Start of inlined file: juce_TableListBox.h *********/
  35058. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35059. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  35060. /**
  35061. One of these is used by a TableListBox as the data model for the table's contents.
  35062. The virtual methods that you override in this class take care of drawing the
  35063. table cells, and reacting to events.
  35064. @see TableListBox
  35065. */
  35066. class JUCE_API TableListBoxModel
  35067. {
  35068. public:
  35069. TableListBoxModel() {}
  35070. /** Destructor. */
  35071. virtual ~TableListBoxModel() {}
  35072. /** This must return the number of rows currently in the table.
  35073. If the number of rows changes, you must call TableListBox::updateContent() to
  35074. cause it to refresh the list.
  35075. */
  35076. virtual int getNumRows() = 0;
  35077. /** This must draw the background behind one of the rows in the table.
  35078. The graphics context has its origin at the row's top-left, and your method
  35079. should fill the area specified by the width and height parameters.
  35080. */
  35081. virtual void paintRowBackground (Graphics& g,
  35082. int rowNumber,
  35083. int width, int height,
  35084. bool rowIsSelected) = 0;
  35085. /** This must draw one of the cells.
  35086. The graphics context's origin will already be set to the top-left of the cell,
  35087. whose size is specified by (width, height).
  35088. */
  35089. virtual void paintCell (Graphics& g,
  35090. int rowNumber,
  35091. int columnId,
  35092. int width, int height,
  35093. bool rowIsSelected) = 0;
  35094. /** This is used to create or update a custom component to go in a cell.
  35095. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  35096. and handle mouse clicks with cellClicked().
  35097. This method will be called whenever a custom component might need to be updated - e.g.
  35098. when the table is changed, or TableListBox::updateContent() is called.
  35099. If you don't need a custom component for the specified cell, then return 0.
  35100. If you do want a custom component, and the existingComponentToUpdate is null, then
  35101. this method must create a new component suitable for the cell, and return it.
  35102. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35103. by this method. In this case, the method must either update it to make sure it's correctly representing
  35104. the given cell (which may be different from the one that the component was created for), or it can
  35105. delete this component and return a new one.
  35106. */
  35107. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  35108. Component* existingComponentToUpdate);
  35109. /** This callback is made when the user clicks on one of the cells in the table.
  35110. The mouse event's coordinates will be relative to the entire table row.
  35111. @see cellDoubleClicked, backgroundClicked
  35112. */
  35113. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  35114. /** This callback is made when the user clicks on one of the cells in the table.
  35115. The mouse event's coordinates will be relative to the entire table row.
  35116. @see cellClicked, backgroundClicked
  35117. */
  35118. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  35119. /** This can be overridden to react to the user double-clicking on a part of the list where
  35120. there are no rows.
  35121. @see cellClicked
  35122. */
  35123. virtual void backgroundClicked();
  35124. /** This callback is made when the table's sort order is changed.
  35125. This could be because the user has clicked a column header, or because the
  35126. TableHeaderComponent::setSortColumnId() method was called.
  35127. If you implement this, your method should re-sort the table using the given
  35128. column as the key.
  35129. */
  35130. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  35131. /** Returns the best width for one of the columns.
  35132. If you implement this method, you should measure the width of all the items
  35133. in this column, and return the best size.
  35134. Returning 0 means that the column shouldn't be changed.
  35135. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  35136. */
  35137. virtual int getColumnAutoSizeWidth (int columnId);
  35138. /** Override this to be informed when rows are selected or deselected.
  35139. @see ListBox::selectedRowsChanged()
  35140. */
  35141. virtual void selectedRowsChanged (int lastRowSelected);
  35142. /** Override this to be informed when the delete key is pressed.
  35143. @see ListBox::deleteKeyPressed()
  35144. */
  35145. virtual void deleteKeyPressed (int lastRowSelected);
  35146. /** Override this to be informed when the return key is pressed.
  35147. @see ListBox::returnKeyPressed()
  35148. */
  35149. virtual void returnKeyPressed (int lastRowSelected);
  35150. /** Override this to be informed when the list is scrolled.
  35151. This might be caused by the user moving the scrollbar, or by programmatic changes
  35152. to the list position.
  35153. */
  35154. virtual void listWasScrolled();
  35155. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  35156. If this returns a non-empty name then when the user drags a row, the table will try to
  35157. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  35158. drag-and-drop operation, using this string as the source description, and the listbox
  35159. itself as the source component.
  35160. @see DragAndDropContainer::startDragging
  35161. */
  35162. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35163. };
  35164. /**
  35165. A table of cells, using a TableHeaderComponent as its header.
  35166. This component makes it easy to create a table by providing a TableListBoxModel as
  35167. the data source.
  35168. @see TableListBoxModel, TableHeaderComponent
  35169. */
  35170. class JUCE_API TableListBox : public ListBox,
  35171. private ListBoxModel,
  35172. private TableHeaderListener
  35173. {
  35174. public:
  35175. /** Creates a TableListBox.
  35176. The model pointer passed-in can be null, in which case you can set it later
  35177. with setModel().
  35178. */
  35179. TableListBox (const String& componentName,
  35180. TableListBoxModel* const model);
  35181. /** Destructor. */
  35182. ~TableListBox();
  35183. /** Changes the TableListBoxModel that is being used for this table.
  35184. */
  35185. void setModel (TableListBoxModel* const newModel);
  35186. /** Returns the model currently in use. */
  35187. TableListBoxModel* getModel() const throw() { return model; }
  35188. /** Returns the header component being used in this table. */
  35189. TableHeaderComponent* getHeader() const throw() { return header; }
  35190. /** Changes the height of the table header component.
  35191. @see getHeaderHeight
  35192. */
  35193. void setHeaderHeight (const int newHeight);
  35194. /** Returns the height of the table header.
  35195. @see setHeaderHeight
  35196. */
  35197. int getHeaderHeight() const throw();
  35198. /** Resizes a column to fit its contents.
  35199. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  35200. and applies that to the column.
  35201. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  35202. */
  35203. void autoSizeColumn (const int columnId);
  35204. /** Calls autoSizeColumn() for all columns in the table. */
  35205. void autoSizeAllColumns();
  35206. /** Enables or disables the auto size options on the popup menu.
  35207. By default, these are enabled.
  35208. */
  35209. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  35210. /** True if the auto-size options should be shown on the menu.
  35211. @see setAutoSizeMenuOptionsShown
  35212. */
  35213. bool isAutoSizeMenuOptionShown() const throw();
  35214. /** Returns the position of one of the cells in the table.
  35215. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  35216. the table component's top-left. The row number isn't checked to see if it's
  35217. in-range, but the column ID must exist or this will return an empty rectangle.
  35218. If relativeToComponentTopLeft is false, the co-ords are relative to the
  35219. top-left of the table's top-left cell.
  35220. */
  35221. const Rectangle getCellPosition (const int columnId,
  35222. const int rowNumber,
  35223. const bool relativeToComponentTopLeft) const;
  35224. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  35225. @see ListBox::scrollToEnsureRowIsOnscreen
  35226. */
  35227. void scrollToEnsureColumnIsOnscreen (const int columnId);
  35228. /** @internal */
  35229. int getNumRows();
  35230. /** @internal */
  35231. void paintListBoxItem (int, Graphics&, int, int, bool);
  35232. /** @internal */
  35233. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35234. /** @internal */
  35235. void selectedRowsChanged (int lastRowSelected);
  35236. /** @internal */
  35237. void deleteKeyPressed (int currentSelectedRow);
  35238. /** @internal */
  35239. void returnKeyPressed (int currentSelectedRow);
  35240. /** @internal */
  35241. void backgroundClicked();
  35242. /** @internal */
  35243. void listWasScrolled();
  35244. /** @internal */
  35245. void tableColumnsChanged (TableHeaderComponent*);
  35246. /** @internal */
  35247. void tableColumnsResized (TableHeaderComponent*);
  35248. /** @internal */
  35249. void tableSortOrderChanged (TableHeaderComponent*);
  35250. /** @internal */
  35251. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  35252. /** @internal */
  35253. void resized();
  35254. juce_UseDebuggingNewOperator
  35255. private:
  35256. TableHeaderComponent* header;
  35257. TableListBoxModel* model;
  35258. int columnIdNowBeingDragged;
  35259. bool autoSizeOptionsShown;
  35260. void updateColumnComponents() const;
  35261. TableListBox (const TableListBox&);
  35262. const TableListBox& operator= (const TableListBox&);
  35263. };
  35264. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  35265. /********* End of inlined file: juce_TableListBox.h *********/
  35266. #endif
  35267. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  35268. #endif
  35269. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35270. #endif
  35271. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35272. #endif
  35273. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35274. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  35275. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35276. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35277. /**
  35278. A factory object which can create ToolbarItemComponent objects.
  35279. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  35280. that it can create.
  35281. Each type of item is identified by a unique ID, and multiple instances of an
  35282. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  35283. bars).
  35284. @see Toolbar, ToolbarItemComponent, ToolbarButton
  35285. */
  35286. class JUCE_API ToolbarItemFactory
  35287. {
  35288. public:
  35289. ToolbarItemFactory();
  35290. /** Destructor. */
  35291. virtual ~ToolbarItemFactory();
  35292. /** A set of reserved item ID values, used for the built-in item types.
  35293. */
  35294. enum SpecialItemIds
  35295. {
  35296. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  35297. can be placed between sets of items to break them into groups. */
  35298. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  35299. items.*/
  35300. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  35301. either side of it, filling any available space. */
  35302. };
  35303. /** Must return a list of the IDs for all the item types that this factory can create.
  35304. The ids should be added to the array that is passed-in.
  35305. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  35306. and the predefined IDs in the SpecialItemIds enum.
  35307. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  35308. to this list if you want your toolbar to be able to contain those items.
  35309. The list returned here is used by the ToolbarItemPalette class to obtain its list
  35310. of available items, and their order on the palette will reflect the order in which
  35311. they appear on this list.
  35312. @see ToolbarItemPalette
  35313. */
  35314. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  35315. /** Must return the set of items that should be added to a toolbar as its default set.
  35316. This method is used by Toolbar::addDefaultItems() to determine which items to
  35317. create.
  35318. The items that your method adds to the array that is passed-in will be added to the
  35319. toolbar in the same order. Items can appear in the list more than once.
  35320. */
  35321. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  35322. /** Must create an instance of one of the items that the factory lists in its
  35323. getAllToolbarItemIds() method.
  35324. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  35325. method, except for the built-in item types from the SpecialItemIds enum, which
  35326. are created internally by the toolbar code.
  35327. Try not to keep a pointer to the object that is returned, as it will be deleted
  35328. automatically by the toolbar, and remember that multiple instances of the same
  35329. item type are likely to exist at the same time.
  35330. */
  35331. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  35332. };
  35333. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35334. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  35335. #endif
  35336. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35337. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  35338. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35339. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35340. /**
  35341. A component containing a list of toolbar items, which the user can drag onto
  35342. a toolbar to add them.
  35343. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  35344. which automatically shows one of these in a dialog box with lots of extra controls.
  35345. @see Toolbar
  35346. */
  35347. class JUCE_API ToolbarItemPalette : public Component,
  35348. public DragAndDropContainer
  35349. {
  35350. public:
  35351. /** Creates a palette of items for a given factory, with the aim of adding them
  35352. to the specified toolbar.
  35353. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  35354. set of items that are shown in this palette.
  35355. The toolbar and factory must not be deleted while this object exists.
  35356. */
  35357. ToolbarItemPalette (ToolbarItemFactory& factory,
  35358. Toolbar* const toolbar);
  35359. /** Destructor. */
  35360. ~ToolbarItemPalette();
  35361. /** @internal */
  35362. void resized();
  35363. juce_UseDebuggingNewOperator
  35364. private:
  35365. ToolbarItemFactory& factory;
  35366. Toolbar* toolbar;
  35367. Viewport* viewport;
  35368. friend class Toolbar;
  35369. void replaceComponent (ToolbarItemComponent* const comp);
  35370. ToolbarItemPalette (const ToolbarItemPalette&);
  35371. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  35372. };
  35373. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35374. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  35375. #endif
  35376. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35377. #endif
  35378. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35379. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  35380. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35381. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35382. /**
  35383. A PropertyComponent that contains an on/off toggle button.
  35384. This type of property component can be used if you have a boolean value to
  35385. toggle on/off.
  35386. @see PropertyComponent
  35387. */
  35388. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  35389. private ButtonListener
  35390. {
  35391. public:
  35392. /** Creates a button component.
  35393. @param propertyName the property name to be passed to the PropertyComponent
  35394. @param buttonTextWhenTrue the text shown in the button when the value is true
  35395. @param buttonTextWhenFalse the text shown in the button when the value is false
  35396. */
  35397. BooleanPropertyComponent (const String& propertyName,
  35398. const String& buttonTextWhenTrue,
  35399. const String& buttonTextWhenFalse);
  35400. /** Destructor. */
  35401. ~BooleanPropertyComponent();
  35402. /** Called to change the state of the boolean value. */
  35403. virtual void setState (const bool newState) = 0;
  35404. /** Must return the current value of the property. */
  35405. virtual bool getState() const = 0;
  35406. /** @internal */
  35407. void paint (Graphics& g);
  35408. /** @internal */
  35409. void refresh();
  35410. /** @internal */
  35411. void buttonClicked (Button*);
  35412. juce_UseDebuggingNewOperator
  35413. private:
  35414. ToggleButton* button;
  35415. String onText, offText;
  35416. };
  35417. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  35418. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  35419. #endif
  35420. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35421. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  35422. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35423. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35424. /**
  35425. A PropertyComponent that contains a button.
  35426. This type of property component can be used if you need a button to trigger some
  35427. kind of action.
  35428. @see PropertyComponent
  35429. */
  35430. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  35431. private ButtonListener
  35432. {
  35433. public:
  35434. /** Creates a button component.
  35435. @param propertyName the property name to be passed to the PropertyComponent
  35436. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  35437. */
  35438. ButtonPropertyComponent (const String& propertyName,
  35439. const bool triggerOnMouseDown);
  35440. /** Destructor. */
  35441. ~ButtonPropertyComponent();
  35442. /** Called when the user clicks the button.
  35443. */
  35444. virtual void buttonClicked() = 0;
  35445. /** Returns the string that should be displayed in the button.
  35446. If you need to change this string, call refresh() to update the component.
  35447. */
  35448. virtual const String getButtonText() const = 0;
  35449. /** @internal */
  35450. void refresh();
  35451. /** @internal */
  35452. void buttonClicked (Button*);
  35453. juce_UseDebuggingNewOperator
  35454. private:
  35455. TextButton* button;
  35456. };
  35457. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  35458. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  35459. #endif
  35460. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35461. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  35462. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35463. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35464. /**
  35465. A PropertyComponent that shows its value as a combo box.
  35466. This type of property component contains a list of options and has a
  35467. combo box to choose one.
  35468. Your subclass's constructor must add some strings to the choices StringArray
  35469. and these are shown in the list.
  35470. The getIndex() method will be called to find out which option is the currently
  35471. selected one. If you call refresh() it will call getIndex() to check whether
  35472. the value has changed, and will update the combo box if needed.
  35473. If the user selects a different item from the list, setIndex() will be
  35474. called to let your class process this.
  35475. @see PropertyComponent, PropertyPanel
  35476. */
  35477. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  35478. private ComboBoxListener
  35479. {
  35480. public:
  35481. /** Creates the component.
  35482. Your subclass's constructor must add a list of options to the choices
  35483. member variable.
  35484. */
  35485. ChoicePropertyComponent (const String& propertyName);
  35486. /** Destructor. */
  35487. ~ChoicePropertyComponent();
  35488. /** Called when the user selects an item from the combo box.
  35489. Your subclass must use this callback to update the value that this component
  35490. represents. The index is the index of the chosen item in the choices
  35491. StringArray.
  35492. */
  35493. virtual void setIndex (const int newIndex) = 0;
  35494. /** Returns the index of the item that should currently be shown.
  35495. This is the index of the item in the choices StringArray that will be
  35496. shown.
  35497. */
  35498. virtual int getIndex() const = 0;
  35499. /** Returns the list of options. */
  35500. const StringArray& getChoices() const throw();
  35501. /** @internal */
  35502. void refresh();
  35503. /** @internal */
  35504. void comboBoxChanged (ComboBox*);
  35505. juce_UseDebuggingNewOperator
  35506. protected:
  35507. /** The list of options that will be shown in the combo box.
  35508. Your subclass must populate this array in its constructor. If any empty
  35509. strings are added, these will be replaced with horizontal separators (see
  35510. ComboBox::addSeparator() for more info).
  35511. */
  35512. StringArray choices;
  35513. private:
  35514. ComboBox* comboBox;
  35515. };
  35516. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  35517. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  35518. #endif
  35519. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  35520. #endif
  35521. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  35522. #endif
  35523. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35524. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  35525. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35526. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35527. /**
  35528. A PropertyComponent that shows its value as a slider.
  35529. @see PropertyComponent, Slider
  35530. */
  35531. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  35532. private SliderListener
  35533. {
  35534. public:
  35535. /** Creates the property component.
  35536. The ranges, interval and skew factor are passed to the Slider component.
  35537. If you need to customise the slider in other ways, your constructor can
  35538. access the slider member variable and change it directly.
  35539. */
  35540. SliderPropertyComponent (const String& propertyName,
  35541. const double rangeMin,
  35542. const double rangeMax,
  35543. const double interval,
  35544. const double skewFactor = 1.0);
  35545. /** Destructor. */
  35546. ~SliderPropertyComponent();
  35547. /** Called when the user moves the slider to change its value.
  35548. Your subclass must use this method to update whatever item this property
  35549. represents.
  35550. */
  35551. virtual void setValue (const double newValue) = 0;
  35552. /** Returns the value that the slider should show. */
  35553. virtual const double getValue() const = 0;
  35554. /** @internal */
  35555. void refresh();
  35556. /** @internal */
  35557. void changeListenerCallback (void*);
  35558. /** @internal */
  35559. void sliderValueChanged (Slider*);
  35560. juce_UseDebuggingNewOperator
  35561. protected:
  35562. /** The slider component being used in this component.
  35563. Your subclass has access to this in case it needs to customise it in some way.
  35564. */
  35565. Slider* slider;
  35566. };
  35567. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  35568. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  35569. #endif
  35570. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35571. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  35572. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35573. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35574. /**
  35575. A PropertyComponent that shows its value as editable text.
  35576. @see PropertyComponent
  35577. */
  35578. class JUCE_API TextPropertyComponent : public PropertyComponent
  35579. {
  35580. public:
  35581. /** Creates a text property component.
  35582. The maxNumChars is used to set the length of string allowable, and isMultiLine
  35583. sets whether the text editor allows carriage returns.
  35584. @see TextEditor
  35585. */
  35586. TextPropertyComponent (const String& propertyName,
  35587. const int maxNumChars,
  35588. const bool isMultiLine);
  35589. /** Destructor. */
  35590. ~TextPropertyComponent();
  35591. /** Called when the user edits the text.
  35592. Your subclass must use this callback to change the value of whatever item
  35593. this property component represents.
  35594. */
  35595. virtual void setText (const String& newText) = 0;
  35596. /** Returns the text that should be shown in the text editor.
  35597. */
  35598. virtual const String getText() const = 0;
  35599. /** @internal */
  35600. void refresh();
  35601. /** @internal */
  35602. void textWasEdited();
  35603. juce_UseDebuggingNewOperator
  35604. private:
  35605. Label* textEditor;
  35606. };
  35607. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  35608. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  35609. #endif
  35610. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  35611. #endif
  35612. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  35613. #endif
  35614. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35615. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  35616. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35617. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35618. /** An object that watches for any movement of a component or any of its parent components.
  35619. This makes it easy to check when a component is moved relative to its top-level
  35620. peer window. The normal Component::moved() method is only called when a component
  35621. moves relative to its immediate parent, and sometimes you want to know if any of
  35622. components higher up the tree have moved (which of course will affect the overall
  35623. position of all their sub-components).
  35624. It also includes a callback that lets you know when the top-level peer is changed.
  35625. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  35626. because they need to keep their custom windows in the right place and respond to
  35627. changes in the peer.
  35628. */
  35629. class JUCE_API ComponentMovementWatcher : public ComponentListener
  35630. {
  35631. public:
  35632. /** Creates a ComponentMovementWatcher to watch a given target component. */
  35633. ComponentMovementWatcher (Component* const component);
  35634. /** Destructor. */
  35635. ~ComponentMovementWatcher();
  35636. /** This callback happens when the component that is being watched is moved
  35637. relative to its top-level peer window, or when it is resized.
  35638. */
  35639. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  35640. /** This callback happens when the component's top-level peer is changed.
  35641. */
  35642. virtual void componentPeerChanged() = 0;
  35643. juce_UseDebuggingNewOperator
  35644. /** @internal */
  35645. void componentParentHierarchyChanged (Component& component);
  35646. /** @internal */
  35647. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  35648. private:
  35649. Component* const component;
  35650. ComponentPeer* lastPeer;
  35651. VoidArray registeredParentComps;
  35652. bool reentrant;
  35653. int lastX, lastY, lastWidth, lastHeight;
  35654. #ifdef JUCE_DEBUG
  35655. ComponentDeletionWatcher* deletionWatcher;
  35656. #endif
  35657. void unregister() throw();
  35658. void registerWithParentComps() throw();
  35659. ComponentMovementWatcher (const ComponentMovementWatcher&);
  35660. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  35661. };
  35662. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  35663. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  35664. #endif
  35665. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35666. /********* Start of inlined file: juce_GroupComponent.h *********/
  35667. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35668. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35669. /**
  35670. A component that draws an outline around itself and has an optional title at
  35671. the top, for drawing an outline around a group of controls.
  35672. */
  35673. class JUCE_API GroupComponent : public Component
  35674. {
  35675. public:
  35676. /** Creates a GroupComponent.
  35677. @param componentName the name to give the component
  35678. @param labelText the text to show at the top of the outline
  35679. */
  35680. GroupComponent (const String& componentName,
  35681. const String& labelText);
  35682. /** Destructor. */
  35683. ~GroupComponent();
  35684. /** Changes the text that's shown at the top of the component. */
  35685. void setText (const String& newText) throw();
  35686. /** Returns the currently displayed text label. */
  35687. const String getText() const throw();
  35688. /** Sets the positioning of the text label.
  35689. (The default is Justification::left)
  35690. @see getTextLabelPosition
  35691. */
  35692. void setTextLabelPosition (const Justification& justification);
  35693. /** Returns the current text label position.
  35694. @see setTextLabelPosition
  35695. */
  35696. const Justification getTextLabelPosition() const throw() { return justification; }
  35697. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35698. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35699. methods.
  35700. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35701. */
  35702. enum ColourIds
  35703. {
  35704. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  35705. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  35706. };
  35707. /** @internal */
  35708. void paint (Graphics& g);
  35709. /** @internal */
  35710. void enablementChanged();
  35711. /** @internal */
  35712. void colourChanged();
  35713. private:
  35714. String text;
  35715. Justification justification;
  35716. GroupComponent (const GroupComponent&);
  35717. const GroupComponent& operator= (const GroupComponent&);
  35718. };
  35719. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  35720. /********* End of inlined file: juce_GroupComponent.h *********/
  35721. #endif
  35722. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35723. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  35724. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35725. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  35726. /********* Start of inlined file: juce_TabbedComponent.h *********/
  35727. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35728. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  35729. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  35730. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35731. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35732. class TabbedButtonBar;
  35733. /** In a TabbedButtonBar, this component is used for each of the buttons.
  35734. If you want to create a TabbedButtonBar with custom tab components, derive
  35735. your component from this class, and override the TabbedButtonBar::createTabButton()
  35736. method to create it instead of the default one.
  35737. @see TabbedButtonBar
  35738. */
  35739. class JUCE_API TabBarButton : public Button
  35740. {
  35741. public:
  35742. /** Creates the tab button. */
  35743. TabBarButton (const String& name,
  35744. TabbedButtonBar* const ownerBar,
  35745. const int tabIndex);
  35746. /** Destructor. */
  35747. ~TabBarButton();
  35748. /** Chooses the best length for the tab, given the specified depth.
  35749. If the tab is horizontal, this should return its width, and the depth
  35750. specifies its height. If it's vertical, it should return the height, and
  35751. the depth is actually its width.
  35752. */
  35753. virtual int getBestTabLength (const int depth);
  35754. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  35755. void clicked (const ModifierKeys& mods);
  35756. bool hitTest (int x, int y);
  35757. juce_UseDebuggingNewOperator
  35758. protected:
  35759. friend class TabbedButtonBar;
  35760. TabbedButtonBar* const owner;
  35761. int tabIndex, overlapPixels;
  35762. DropShadowEffect shadow;
  35763. /** Returns an area of the component that's safe to draw in.
  35764. This deals with the orientation of the tabs, which affects which side is
  35765. touching the tabbed box's content component.
  35766. */
  35767. void getActiveArea (int& x, int& y, int& w, int& h);
  35768. private:
  35769. TabBarButton (const TabBarButton&);
  35770. const TabBarButton& operator= (const TabBarButton&);
  35771. };
  35772. /**
  35773. A vertical or horizontal bar containing tabs that you can select.
  35774. You can use one of these to generate things like a dialog box that has
  35775. tabbed pages you can flip between. Attach a ChangeListener to the
  35776. button bar to be told when the user changes the page.
  35777. An easier method than doing this is to use a TabbedComponent, which
  35778. contains its own TabbedButtonBar and which takes care of the layout
  35779. and other housekeeping.
  35780. @see TabbedComponent
  35781. */
  35782. class JUCE_API TabbedButtonBar : public Component,
  35783. public ChangeBroadcaster,
  35784. public ButtonListener
  35785. {
  35786. public:
  35787. /** The placement of the tab-bar
  35788. @see setOrientation, getOrientation
  35789. */
  35790. enum Orientation
  35791. {
  35792. TabsAtTop,
  35793. TabsAtBottom,
  35794. TabsAtLeft,
  35795. TabsAtRight
  35796. };
  35797. /** Creates a TabbedButtonBar with a given placement.
  35798. You can change the orientation later if you need to.
  35799. */
  35800. TabbedButtonBar (const Orientation orientation);
  35801. /** Destructor. */
  35802. ~TabbedButtonBar();
  35803. /** Changes the bar's orientation.
  35804. This won't change the bar's actual size - you'll need to do that yourself,
  35805. but this determines which direction the tabs go in, and which side they're
  35806. stuck to.
  35807. */
  35808. void setOrientation (const Orientation orientation);
  35809. /** Returns the current orientation.
  35810. @see setOrientation
  35811. */
  35812. Orientation getOrientation() const throw() { return orientation; }
  35813. /** Deletes all the tabs from the bar.
  35814. @see addTab
  35815. */
  35816. void clearTabs();
  35817. /** Adds a tab to the bar.
  35818. Tabs are added in left-to-right reading order.
  35819. If this is the first tab added, it'll also be automatically selected.
  35820. */
  35821. void addTab (const String& tabName,
  35822. const Colour& tabBackgroundColour,
  35823. int insertIndex = -1);
  35824. /** Changes the name of one of the tabs. */
  35825. void setTabName (const int tabIndex,
  35826. const String& newName);
  35827. /** Gets rid of one of the tabs. */
  35828. void removeTab (const int tabIndex);
  35829. /** Moves a tab to a new index in the list.
  35830. Pass -1 as the index to move it to the end of the list.
  35831. */
  35832. void moveTab (const int currentIndex,
  35833. const int newIndex);
  35834. /** Returns the number of tabs in the bar. */
  35835. int getNumTabs() const;
  35836. /** Returns a list of all the tab names in the bar. */
  35837. const StringArray getTabNames() const;
  35838. /** Changes the currently selected tab.
  35839. This will send a change message and cause a synchronous callback to
  35840. the currentTabChanged() method. (But if the given tab is already selected,
  35841. nothing will be done).
  35842. To deselect all the tabs, use an index of -1.
  35843. */
  35844. void setCurrentTabIndex (int newTabIndex, const bool sendChangeMessage = true);
  35845. /** Returns the name of the currently selected tab.
  35846. This could be an empty string if none are selected.
  35847. */
  35848. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  35849. /** Returns the index of the currently selected tab.
  35850. This could return -1 if none are selected.
  35851. */
  35852. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  35853. /** Returns the button for a specific tab.
  35854. The button that is returned may be deleted later by this component, so don't hang
  35855. on to the pointer that is returned. A null pointer may be returned if the index is
  35856. out of range.
  35857. */
  35858. TabBarButton* getTabButton (const int index) const;
  35859. /** Callback method to indicate the selected tab has been changed.
  35860. @see setCurrentTabIndex
  35861. */
  35862. virtual void currentTabChanged (const int newCurrentTabIndex,
  35863. const String& newCurrentTabName);
  35864. /** Callback method to indicate that the user has right-clicked on a tab.
  35865. (Or ctrl-clicked on the Mac)
  35866. */
  35867. virtual void popupMenuClickOnTab (const int tabIndex,
  35868. const String& tabName);
  35869. /** Returns the colour of a tab.
  35870. This is the colour that was specified in addTab().
  35871. */
  35872. const Colour getTabBackgroundColour (const int tabIndex);
  35873. /** Changes the background colour of a tab.
  35874. @see addTab, getTabBackgroundColour
  35875. */
  35876. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35877. /** A set of colour IDs to use to change the colour of various aspects of the component.
  35878. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35879. methods.
  35880. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35881. */
  35882. enum ColourIds
  35883. {
  35884. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  35885. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  35886. the look and feel will choose an appropriate colour. */
  35887. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  35888. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  35889. this isn't specified, the look and feel will choose an appropriate
  35890. colour. */
  35891. };
  35892. /** @internal */
  35893. void resized();
  35894. /** @internal */
  35895. void buttonClicked (Button* button);
  35896. /** @internal */
  35897. void lookAndFeelChanged();
  35898. juce_UseDebuggingNewOperator
  35899. protected:
  35900. /** This creates one of the tabs.
  35901. If you need to use custom tab components, you can override this method and
  35902. return your own class instead of the default.
  35903. */
  35904. virtual TabBarButton* createTabButton (const String& tabName,
  35905. const int tabIndex);
  35906. private:
  35907. Orientation orientation;
  35908. StringArray tabs;
  35909. Array <Colour> tabColours;
  35910. int currentTabIndex;
  35911. Component* behindFrontTab;
  35912. Button* extraTabsButton;
  35913. TabbedButtonBar (const TabbedButtonBar&);
  35914. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  35915. };
  35916. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  35917. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  35918. /**
  35919. A component with a TabbedButtonBar along one of its sides.
  35920. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  35921. with addTab(), and this will take care of showing the pages for you when the
  35922. user clicks on a different tab.
  35923. @see TabbedButtonBar
  35924. */
  35925. class JUCE_API TabbedComponent : public Component
  35926. {
  35927. public:
  35928. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  35929. Once created, add some tabs with the addTab() method.
  35930. */
  35931. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  35932. /** Destructor. */
  35933. ~TabbedComponent();
  35934. /** Changes the placement of the tabs.
  35935. This will rearrange the layout to place the tabs along the appropriate
  35936. side of this component, and will shift the content component accordingly.
  35937. @see TabbedButtonBar::setOrientation
  35938. */
  35939. void setOrientation (const TabbedButtonBar::Orientation orientation);
  35940. /** Returns the current tab placement.
  35941. @see setOrientation, TabbedButtonBar::getOrientation
  35942. */
  35943. TabbedButtonBar::Orientation getOrientation() const throw();
  35944. /** Specifies how many pixels wide or high the tab-bar should be.
  35945. If the tabs are placed along the top or bottom, this specified the height
  35946. of the bar; if they're along the left or right edges, it'll be the width
  35947. of the bar.
  35948. */
  35949. void setTabBarDepth (const int newDepth);
  35950. /** Returns the current thickness of the tab bar.
  35951. @see setTabBarDepth
  35952. */
  35953. int getTabBarDepth() const throw() { return tabDepth; }
  35954. /** Specifies the thickness of an outline that should be drawn around the content component.
  35955. If this thickness is > 0, a line will be drawn around the three sides of the content
  35956. component which don't touch the tab-bar, and the content component will be inset by this amount.
  35957. To set the colour of the line, use setColour (outlineColourId, ...).
  35958. */
  35959. void setOutline (const int newThickness);
  35960. /** Specifies a gap to leave around the edge of the content component.
  35961. Each edge of the content component will be indented by the given number of pixels.
  35962. */
  35963. void setIndent (const int indentThickness);
  35964. /** Removes all the tabs from the bar.
  35965. @see TabbedButtonBar::clearTabs
  35966. */
  35967. void clearTabs();
  35968. /** Adds a tab to the tab-bar.
  35969. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  35970. is true, it will be deleted when the tab is removed or when this object is
  35971. deleted.
  35972. @see TabbedButtonBar::addTab
  35973. */
  35974. void addTab (const String& tabName,
  35975. const Colour& tabBackgroundColour,
  35976. Component* const contentComponent,
  35977. const bool deleteComponentWhenNotNeeded,
  35978. const int insertIndex = -1);
  35979. /** Changes the name of one of the tabs. */
  35980. void setTabName (const int tabIndex,
  35981. const String& newName);
  35982. /** Gets rid of one of the tabs. */
  35983. void removeTab (const int tabIndex);
  35984. /** Returns the number of tabs in the bar. */
  35985. int getNumTabs() const;
  35986. /** Returns a list of all the tab names in the bar. */
  35987. const StringArray getTabNames() const;
  35988. /** Returns the content component that was added for the given index.
  35989. Be sure not to use or delete the components that are returned, as this may interfere
  35990. with the TabbedComponent's use of them.
  35991. */
  35992. Component* getTabContentComponent (const int tabIndex) const throw();
  35993. /** Returns the colour of one of the tabs. */
  35994. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  35995. /** Changes the background colour of one of the tabs. */
  35996. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  35997. /** Changes the currently-selected tab.
  35998. To deselect all the tabs, pass -1 as the index.
  35999. @see TabbedButtonBar::setCurrentTabIndex
  36000. */
  36001. void setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage = true);
  36002. /** Returns the index of the currently selected tab.
  36003. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  36004. */
  36005. int getCurrentTabIndex() const;
  36006. /** Returns the name of the currently selected tab.
  36007. @see addTab, TabbedButtonBar::getCurrentTabName()
  36008. */
  36009. const String& getCurrentTabName() const;
  36010. /** Returns the current component that's filling the panel.
  36011. This will return 0 if there isn't one.
  36012. */
  36013. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  36014. /** Callback method to indicate the selected tab has been changed.
  36015. @see setCurrentTabIndex
  36016. */
  36017. virtual void currentTabChanged (const int newCurrentTabIndex,
  36018. const String& newCurrentTabName);
  36019. /** Callback method to indicate that the user has right-clicked on a tab.
  36020. (Or ctrl-clicked on the Mac)
  36021. */
  36022. virtual void popupMenuClickOnTab (const int tabIndex,
  36023. const String& tabName);
  36024. /** Returns the tab button bar component that is being used.
  36025. */
  36026. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  36027. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36028. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36029. methods.
  36030. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36031. */
  36032. enum ColourIds
  36033. {
  36034. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  36035. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  36036. (See setOutline) */
  36037. };
  36038. /** @internal */
  36039. void paint (Graphics& g);
  36040. /** @internal */
  36041. void resized();
  36042. /** @internal */
  36043. void lookAndFeelChanged();
  36044. juce_UseDebuggingNewOperator
  36045. protected:
  36046. TabbedButtonBar* tabs;
  36047. /** This creates one of the tab buttons.
  36048. If you need to use custom tab components, you can override this method and
  36049. return your own class instead of the default.
  36050. */
  36051. virtual TabBarButton* createTabButton (const String& tabName,
  36052. const int tabIndex);
  36053. private:
  36054. Array <Component*> contentComponents;
  36055. Component* panelComponent;
  36056. int tabDepth;
  36057. int outlineThickness, edgeIndent;
  36058. friend class TabCompButtonBar;
  36059. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  36060. TabbedComponent (const TabbedComponent&);
  36061. const TabbedComponent& operator= (const TabbedComponent&);
  36062. };
  36063. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36064. /********* End of inlined file: juce_TabbedComponent.h *********/
  36065. /********* Start of inlined file: juce_DocumentWindow.h *********/
  36066. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36067. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36068. /********* Start of inlined file: juce_ResizableWindow.h *********/
  36069. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36070. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36071. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  36072. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36073. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36074. /********* Start of inlined file: juce_DropShadower.h *********/
  36075. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36076. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36077. /**
  36078. Adds a drop-shadow to a component.
  36079. This object creates and manages a set of components which sit around a
  36080. component, creating a gaussian shadow around it. The components will track
  36081. the position of the component and if it's brought to the front they'll also
  36082. follow this.
  36083. For desktop windows you don't need to use this class directly - just
  36084. set the Component::windowHasDropShadow flag when calling
  36085. Component::addToDesktop(), and the system will create one of these if it's
  36086. needed (which it obviously isn't on the Mac, for example).
  36087. */
  36088. class JUCE_API DropShadower : public ComponentListener
  36089. {
  36090. public:
  36091. /** Creates a DropShadower.
  36092. @param alpha the opacity of the shadows, from 0 to 1.0
  36093. @param xOffset the horizontal displacement of the shadow, in pixels
  36094. @param yOffset the vertical displacement of the shadow, in pixels
  36095. @param blurRadius the radius of the blur to use for creating the shadow
  36096. */
  36097. DropShadower (const float alpha = 0.5f,
  36098. const int xOffset = 1,
  36099. const int yOffset = 5,
  36100. const float blurRadius = 10.0f);
  36101. /** Destructor. */
  36102. virtual ~DropShadower();
  36103. /** Attaches the DropShadower to the component you want to shadow. */
  36104. void setOwner (Component* componentToFollow);
  36105. /** @internal */
  36106. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36107. /** @internal */
  36108. void componentBroughtToFront (Component& component);
  36109. /** @internal */
  36110. void componentChildrenChanged (Component& component);
  36111. /** @internal */
  36112. void componentParentHierarchyChanged (Component& component);
  36113. /** @internal */
  36114. void componentVisibilityChanged (Component& component);
  36115. juce_UseDebuggingNewOperator
  36116. private:
  36117. Component* owner;
  36118. int numShadows;
  36119. Component* shadowWindows[4];
  36120. Image* shadowImageSections[12];
  36121. const int shadowEdge, xOffset, yOffset;
  36122. const float alpha, blurRadius;
  36123. bool inDestructor, reentrant;
  36124. void updateShadows();
  36125. void setShadowImage (Image* const src,
  36126. const int num,
  36127. const int w, const int h,
  36128. const int sx, const int sy) throw();
  36129. void bringShadowWindowsToFront();
  36130. void deleteShadowWindows();
  36131. DropShadower (const DropShadower&);
  36132. const DropShadower& operator= (const DropShadower&);
  36133. };
  36134. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  36135. /********* End of inlined file: juce_DropShadower.h *********/
  36136. /**
  36137. A base class for top-level windows.
  36138. This class is used for components that are considered a major part of your
  36139. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  36140. etc. Things like menus that pop up briefly aren't derived from it.
  36141. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  36142. could itself be the child of another component.
  36143. The class manages a list of all instances of top-level windows that are in use,
  36144. and each one is also given the concept of being "active". The active window is
  36145. one that is actively being used by the user. This isn't quite the same as the
  36146. component with the keyboard focus, because there may be a popup menu or other
  36147. temporary window which gets keyboard focus while the active top level window is
  36148. unchanged.
  36149. A top-level window also has an optional drop-shadow.
  36150. @see ResizableWindow, DocumentWindow, DialogWindow
  36151. */
  36152. class JUCE_API TopLevelWindow : public Component
  36153. {
  36154. public:
  36155. /** Creates a TopLevelWindow.
  36156. @param name the name to give the component
  36157. @param addToDesktop if true, the window will be automatically added to the
  36158. desktop; if false, you can use it as a child component
  36159. */
  36160. TopLevelWindow (const String& name,
  36161. const bool addToDesktop);
  36162. /** Destructor. */
  36163. ~TopLevelWindow();
  36164. /** True if this is currently the TopLevelWindow that is actively being used.
  36165. This isn't quite the same as having keyboard focus, because the focus may be
  36166. on a child component or a temporary pop-up menu, etc, while this window is
  36167. still considered to be active.
  36168. @see activeWindowStatusChanged
  36169. */
  36170. bool isActiveWindow() const throw() { return windowIsActive_; }
  36171. /** This will set the bounds of the window so that it's centred in front of another
  36172. window.
  36173. If your app has a few windows open and want to pop up a dialog box for one of
  36174. them, you can use this to show it in front of the relevent parent window, which
  36175. is a bit neater than just having it appear in the middle of the screen.
  36176. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  36177. be used instead. If no window is focused, it'll just default to the middle of the
  36178. screen.
  36179. */
  36180. void centreAroundComponent (Component* componentToCentreAround,
  36181. const int width, const int height);
  36182. /** Turns the drop-shadow on and off. */
  36183. void setDropShadowEnabled (const bool useShadow);
  36184. /** Sets whether an OS-native title bar will be used, or a Juce one.
  36185. @see isUsingNativeTitleBar
  36186. */
  36187. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  36188. /** Returns true if the window is currently using an OS-native title bar.
  36189. @see setUsingNativeTitleBar
  36190. */
  36191. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  36192. /** Returns the number of TopLevelWindow objects currently in use.
  36193. @see getTopLevelWindow
  36194. */
  36195. static int getNumTopLevelWindows() throw();
  36196. /** Returns one of the TopLevelWindow objects currently in use.
  36197. The index is 0 to (getNumTopLevelWindows() - 1).
  36198. */
  36199. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  36200. /** Returns the currently-active top level window.
  36201. There might not be one, of course, so this can return 0.
  36202. */
  36203. static TopLevelWindow* getActiveTopLevelWindow() throw();
  36204. juce_UseDebuggingNewOperator
  36205. /** @internal */
  36206. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  36207. protected:
  36208. /** This callback happens when this window becomes active or inactive.
  36209. @see isActiveWindow
  36210. */
  36211. virtual void activeWindowStatusChanged();
  36212. /** @internal */
  36213. void focusOfChildComponentChanged (FocusChangeType cause);
  36214. /** @internal */
  36215. void parentHierarchyChanged();
  36216. /** @internal */
  36217. void visibilityChanged();
  36218. /** @internal */
  36219. virtual int getDesktopWindowStyleFlags() const;
  36220. /** @internal */
  36221. void recreateDesktopWindow();
  36222. private:
  36223. friend class TopLevelWindowManager;
  36224. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  36225. DropShadower* shadower;
  36226. void setWindowActive (const bool isNowActive) throw();
  36227. TopLevelWindow (const TopLevelWindow&);
  36228. const TopLevelWindow& operator= (const TopLevelWindow&);
  36229. };
  36230. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36231. /********* End of inlined file: juce_TopLevelWindow.h *********/
  36232. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  36233. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36234. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36235. /**
  36236. A component that resizes its parent window when dragged.
  36237. This component forms a frame around the edge of a component, allowing it to
  36238. be dragged by the edges or corners to resize it - like the way windows are
  36239. resized in MSWindows or Linux.
  36240. To use it, just add it to your component, making it fill the entire parent component
  36241. (there's a mouse hit-test that only traps mouse-events which land around the
  36242. edge of the component, so it's even ok to put it on top of any other components
  36243. you're using). Make sure you rescale the resizer component to fill the parent
  36244. each time the parent's size changes.
  36245. @see ResizableCornerComponent
  36246. */
  36247. class JUCE_API ResizableBorderComponent : public Component
  36248. {
  36249. public:
  36250. /** Creates a resizer.
  36251. Pass in the target component which you want to be resized when this one is
  36252. dragged.
  36253. The target component will usually be a parent of the resizer component, but this
  36254. isn't mandatory.
  36255. Remember that when the target component is resized, it'll need to move and
  36256. resize this component to keep it in place, as this won't happen automatically.
  36257. If the constrainer parameter is non-zero, then this object will be used to enforce
  36258. limits on the size and position that the component can be stretched to. Make sure
  36259. that the constrainer isn't deleted while still in use by this object.
  36260. @see ComponentBoundsConstrainer
  36261. */
  36262. ResizableBorderComponent (Component* const componentToResize,
  36263. ComponentBoundsConstrainer* const constrainer);
  36264. /** Destructor. */
  36265. ~ResizableBorderComponent();
  36266. /** Specifies how many pixels wide the draggable edges of this component are.
  36267. @see getBorderThickness
  36268. */
  36269. void setBorderThickness (const BorderSize& newBorderSize) throw();
  36270. /** Returns the number of pixels wide that the draggable edges of this component are.
  36271. @see setBorderThickness
  36272. */
  36273. const BorderSize getBorderThickness() const throw();
  36274. juce_UseDebuggingNewOperator
  36275. protected:
  36276. /** @internal */
  36277. void paint (Graphics& g);
  36278. /** @internal */
  36279. void mouseEnter (const MouseEvent& e);
  36280. /** @internal */
  36281. void mouseMove (const MouseEvent& e);
  36282. /** @internal */
  36283. void mouseDown (const MouseEvent& e);
  36284. /** @internal */
  36285. void mouseDrag (const MouseEvent& e);
  36286. /** @internal */
  36287. void mouseUp (const MouseEvent& e);
  36288. /** @internal */
  36289. bool hitTest (int x, int y);
  36290. private:
  36291. Component* const component;
  36292. ComponentBoundsConstrainer* constrainer;
  36293. BorderSize borderSize;
  36294. int originalX, originalY, originalW, originalH;
  36295. int mouseZone;
  36296. void updateMouseZone (const MouseEvent& e) throw();
  36297. ResizableBorderComponent (const ResizableBorderComponent&);
  36298. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  36299. };
  36300. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36301. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  36302. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  36303. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36304. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36305. /** A component that resizes a parent window when dragged.
  36306. This is the small triangular stripey resizer component you get in the bottom-right
  36307. of windows (more commonly on the Mac than Windows). Put one in the corner of
  36308. a larger component and it will automatically resize its parent when it gets dragged
  36309. around.
  36310. @see ResizableFrameComponent
  36311. */
  36312. class JUCE_API ResizableCornerComponent : public Component
  36313. {
  36314. public:
  36315. /** Creates a resizer.
  36316. Pass in the target component which you want to be resized when this one is
  36317. dragged.
  36318. The target component will usually be a parent of the resizer component, but this
  36319. isn't mandatory.
  36320. Remember that when the target component is resized, it'll need to move and
  36321. resize this component to keep it in place, as this won't happen automatically.
  36322. If the constrainer parameter is non-zero, then this object will be used to enforce
  36323. limits on the size and position that the component can be stretched to. Make sure
  36324. that the constrainer isn't deleted while still in use by this object. If you
  36325. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  36326. @see ComponentBoundsConstrainer
  36327. */
  36328. ResizableCornerComponent (Component* const componentToResize,
  36329. ComponentBoundsConstrainer* const constrainer);
  36330. /** Destructor. */
  36331. ~ResizableCornerComponent();
  36332. juce_UseDebuggingNewOperator
  36333. protected:
  36334. /** @internal */
  36335. void paint (Graphics& g);
  36336. /** @internal */
  36337. void mouseDown (const MouseEvent& e);
  36338. /** @internal */
  36339. void mouseDrag (const MouseEvent& e);
  36340. /** @internal */
  36341. void mouseUp (const MouseEvent& e);
  36342. /** @internal */
  36343. bool hitTest (int x, int y);
  36344. private:
  36345. Component* const component;
  36346. ComponentBoundsConstrainer* constrainer;
  36347. int originalX, originalY, originalW, originalH;
  36348. ResizableCornerComponent (const ResizableCornerComponent&);
  36349. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  36350. };
  36351. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36352. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  36353. /**
  36354. A base class for top-level windows that can be dragged around and resized.
  36355. To add content to the window, use its setContentComponent() method to
  36356. give it a component that will remain positioned inside it (leaving a gap around
  36357. the edges for a border).
  36358. It's not advisable to add child components directly to a ResizableWindow: put them
  36359. inside your content component instead. And overriding methods like resized(), moved(), etc
  36360. is also not recommended - instead override these methods for your content component.
  36361. (If for some obscure reason you do need to override these methods, always remember to
  36362. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36363. decorations correctly).
  36364. By default resizing isn't enabled - use the setResizable() method to enable it and
  36365. to choose the style of resizing to use.
  36366. @see TopLevelWindow
  36367. */
  36368. class JUCE_API ResizableWindow : public TopLevelWindow
  36369. {
  36370. public:
  36371. /** Creates a ResizableWindow.
  36372. This constructor doesn't specify a background colour, so the LookAndFeel's default
  36373. background colour will be used.
  36374. @param name the name to give the component
  36375. @param addToDesktop if true, the window will be automatically added to the
  36376. desktop; if false, you can use it as a child component
  36377. */
  36378. ResizableWindow (const String& name,
  36379. const bool addToDesktop);
  36380. /** Creates a ResizableWindow.
  36381. @param name the name to give the component
  36382. @param backgroundColour the colour to use for filling the window's background.
  36383. @param addToDesktop if true, the window will be automatically added to the
  36384. desktop; if false, you can use it as a child component
  36385. */
  36386. ResizableWindow (const String& name,
  36387. const Colour& backgroundColour,
  36388. const bool addToDesktop);
  36389. /** Destructor.
  36390. If a content component has been set with setContentComponent(), it
  36391. will be deleted.
  36392. */
  36393. ~ResizableWindow();
  36394. /** Returns the colour currently being used for the window's background.
  36395. As a convenience the window will fill itself with this colour, but you
  36396. can override the paint() method if you need more customised behaviour.
  36397. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  36398. @see setBackgroundColour
  36399. */
  36400. const Colour getBackgroundColour() const throw();
  36401. /** Changes the colour currently being used for the window's background.
  36402. As a convenience the window will fill itself with this colour, but you
  36403. can override the paint() method if you need more customised behaviour.
  36404. Note that the opaque state of this window is altered by this call to reflect
  36405. the opacity of the colour passed-in. On window systems which can't support
  36406. semi-transparent windows this might cause problems, (though it's unlikely you'll
  36407. be using this class as a base for a semi-transparent component anyway).
  36408. You can also use the ResizableWindow::backgroundColourId colour id to set
  36409. this colour.
  36410. @see getBackgroundColour
  36411. */
  36412. void setBackgroundColour (const Colour& newColour);
  36413. /** Make the window resizable or fixed.
  36414. @param shouldBeResizable whether it's resizable at all
  36415. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  36416. bottom-right; if false, it'll use a ResizableBorderComponent
  36417. around the edge
  36418. @see setResizeLimits, isResizable
  36419. */
  36420. void setResizable (const bool shouldBeResizable,
  36421. const bool useBottomRightCornerResizer);
  36422. /** True if resizing is enabled.
  36423. @see setResizable
  36424. */
  36425. bool isResizable() const throw();
  36426. /** This sets the maximum and minimum sizes for the window.
  36427. If the window's current size is outside these limits, it will be resized to
  36428. make sure it's within them.
  36429. Calling setBounds() on the component will bypass any size checking - it's only when
  36430. the window is being resized by the user that these values are enforced.
  36431. @see setResizable, setFixedAspectRatio
  36432. */
  36433. void setResizeLimits (const int newMinimumWidth,
  36434. const int newMinimumHeight,
  36435. const int newMaximumWidth,
  36436. const int newMaximumHeight) throw();
  36437. /** Returns the bounds constrainer object that this window is using.
  36438. You can access this to change its properties.
  36439. */
  36440. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  36441. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  36442. A pointer to the object you pass in will be kept, but it won't be deleted
  36443. by this object, so it's the caller's responsiblity to manage it.
  36444. If you pass 0, then no contraints will be placed on the positioning of the window.
  36445. */
  36446. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  36447. /** Calls the window's setBounds method, after first checking these bounds
  36448. with the current constrainer.
  36449. @see setConstrainer
  36450. */
  36451. void setBoundsConstrained (int x, int y, int width, int height);
  36452. /** Returns true if the window is currently in full-screen mode.
  36453. @see setFullScreen
  36454. */
  36455. bool isFullScreen() const;
  36456. /** Puts the window into full-screen mode, or restores it to its normal size.
  36457. If true, the window will become full-screen; if false, it will return to the
  36458. last size it was before being made full-screen.
  36459. @see isFullScreen
  36460. */
  36461. void setFullScreen (const bool shouldBeFullScreen);
  36462. /** Returns true if the window is currently minimised.
  36463. @see setMinimised
  36464. */
  36465. bool isMinimised() const;
  36466. /** Minimises the window, or restores it to its previous position and size.
  36467. When being un-minimised, it'll return to the last position and size it
  36468. was in before being minimised.
  36469. @see isMinimised
  36470. */
  36471. void setMinimised (const bool shouldMinimise);
  36472. /** Returns a string which encodes the window's current size and position.
  36473. This string will encapsulate the window's size, position, and whether it's
  36474. in full-screen mode. It's intended for letting your application save and
  36475. restore a window's position.
  36476. Use the restoreWindowStateFromString() to restore from a saved state.
  36477. @see restoreWindowStateFromString
  36478. */
  36479. const String getWindowStateAsString();
  36480. /** Restores the window to a previously-saved size and position.
  36481. This restores the window's size, positon and full-screen status from an
  36482. string that was previously created with the getWindowStateAsString()
  36483. method.
  36484. @returns false if the string wasn't a valid window state
  36485. @see getWindowStateAsString
  36486. */
  36487. bool restoreWindowStateFromString (const String& previousState);
  36488. /** Returns the current content component.
  36489. This will be the component set by setContentComponent(), or 0 if none
  36490. has yet been specified.
  36491. @see setContentComponent
  36492. */
  36493. Component* getContentComponent() const throw() { return contentComponent; }
  36494. /** Changes the current content component.
  36495. This sets a component that will be placed in the centre of the ResizableWindow,
  36496. (leaving a space around the edge for the border).
  36497. You should never add components directly to a ResizableWindow (or any of its subclasses)
  36498. with addChildComponent(). Instead, add them to the content component.
  36499. @param newContentComponent the new component to use (or null to not use one) - this
  36500. component will be deleted either when replaced by another call
  36501. to this method, or when the ResizableWindow is deleted.
  36502. To remove a content component without deleting it, use
  36503. setContentComponent (0, false).
  36504. @param deleteOldOne if true, the previous content component will be deleted; if
  36505. false, the previous component will just be removed without
  36506. deleting it.
  36507. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  36508. it always fits around the size of the content component. If false, the
  36509. new content will be resized to fit the current space available.
  36510. */
  36511. void setContentComponent (Component* const newContentComponent,
  36512. const bool deleteOldOne = true,
  36513. const bool resizeToFit = false);
  36514. /** Changes the window so that the content component ends up with the specified size.
  36515. This is basically a setSize call on the window, but which adds on the borders,
  36516. so you can specify the content component's target size.
  36517. */
  36518. void setContentComponentSize (int width, int height);
  36519. /** A set of colour IDs to use to change the colour of various aspects of the window.
  36520. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36521. methods.
  36522. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36523. */
  36524. enum ColourIds
  36525. {
  36526. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  36527. };
  36528. juce_UseDebuggingNewOperator
  36529. protected:
  36530. /** @internal */
  36531. void paint (Graphics& g);
  36532. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  36533. void moved();
  36534. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  36535. void resized();
  36536. /** @internal */
  36537. void mouseDown (const MouseEvent& e);
  36538. /** @internal */
  36539. void mouseDrag (const MouseEvent& e);
  36540. /** @internal */
  36541. void lookAndFeelChanged();
  36542. /** @internal */
  36543. void childBoundsChanged (Component* child);
  36544. /** @internal */
  36545. void parentSizeChanged();
  36546. /** @internal */
  36547. void visibilityChanged();
  36548. /** @internal */
  36549. void activeWindowStatusChanged();
  36550. /** @internal */
  36551. int getDesktopWindowStyleFlags() const;
  36552. /** Returns the width of the border to use around the window.
  36553. @see getContentComponentBorder
  36554. */
  36555. virtual const BorderSize getBorderThickness();
  36556. /** Returns the insets to use when positioning the content component.
  36557. @see getBorderThickness
  36558. */
  36559. virtual const BorderSize getContentComponentBorder();
  36560. #ifdef JUCE_DEBUG
  36561. /** Overridden to warn people about adding components directly to this component
  36562. instead of using setContentComponent().
  36563. If you know what you're doing and are sure you really want to add a component, specify
  36564. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  36565. */
  36566. void addChildComponent (Component* const child, int zOrder = -1);
  36567. /** Overridden to warn people about adding components directly to this component
  36568. instead of using setContentComponent().
  36569. If you know what you're doing and are sure you really want to add a component, specify
  36570. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  36571. */
  36572. void addAndMakeVisible (Component* const child, int zOrder = -1);
  36573. #endif
  36574. ResizableCornerComponent* resizableCorner;
  36575. ResizableBorderComponent* resizableBorder;
  36576. private:
  36577. Component* contentComponent;
  36578. bool resizeToFitContent, fullscreen;
  36579. ComponentDragger dragger;
  36580. Rectangle lastNonFullScreenPos;
  36581. ComponentBoundsConstrainer defaultConstrainer;
  36582. ComponentBoundsConstrainer* constrainer;
  36583. #ifdef JUCE_DEBUG
  36584. bool hasBeenResized;
  36585. #endif
  36586. void updateLastPos();
  36587. ResizableWindow (const ResizableWindow&);
  36588. const ResizableWindow& operator= (const ResizableWindow&);
  36589. // (xxx remove these eventually)
  36590. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  36591. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  36592. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  36593. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  36594. };
  36595. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36596. /********* End of inlined file: juce_ResizableWindow.h *********/
  36597. /**
  36598. A resizable window with a title bar and maximise, minimise and close buttons.
  36599. This subclass of ResizableWindow creates a fairly standard type of window with
  36600. a title bar and various buttons. The name of the component is shown in the
  36601. title bar, and an icon can optionally be specified with setIcon().
  36602. All the methods available to a ResizableWindow are also available to this,
  36603. so it can easily be made resizable, minimised, maximised, etc.
  36604. It's not advisable to add child components directly to a DocumentWindow: put them
  36605. inside your content component instead. And overriding methods like resized(), moved(), etc
  36606. is also not recommended - instead override these methods for your content component.
  36607. (If for some obscure reason you do need to override these methods, always remember to
  36608. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36609. decorations correctly).
  36610. You can also automatically add a menu bar to the window, using the setMenuBar()
  36611. method.
  36612. @see ResizableWindow, DialogWindow
  36613. */
  36614. class JUCE_API DocumentWindow : public ResizableWindow
  36615. {
  36616. public:
  36617. /** The set of available button-types that can be put on the title bar.
  36618. @see setTitleBarButtonsRequired
  36619. */
  36620. enum TitleBarButtons
  36621. {
  36622. minimiseButton = 1,
  36623. maximiseButton = 2,
  36624. closeButton = 4,
  36625. /** A combination of all the buttons above. */
  36626. allButtons = 7
  36627. };
  36628. /** Creates a DocumentWindow.
  36629. @param name the name to give the component - this is also
  36630. the title shown at the top of the window. To change
  36631. this later, use setName()
  36632. @param backgroundColour the colour to use for filling the window's background.
  36633. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36634. should be shown on the title bar. This value is a bitwise
  36635. combination of values from the TitleBarButtons enum. Note
  36636. that it can be "allButtons" to get them all. You
  36637. can change this later with the setTitleBarButtonsRequired()
  36638. method, which can also specify where they are positioned.
  36639. @param addToDesktop if true, the window will be automatically added to the
  36640. desktop; if false, you can use it as a child component
  36641. @see TitleBarButtons
  36642. */
  36643. DocumentWindow (const String& name,
  36644. const Colour& backgroundColour,
  36645. const int requiredButtons,
  36646. const bool addToDesktop = true);
  36647. /** Destructor.
  36648. If a content component has been set with setContentComponent(), it
  36649. will be deleted.
  36650. */
  36651. ~DocumentWindow();
  36652. /** Changes the component's name.
  36653. (This is overridden from Component::setName() to cause a repaint, as
  36654. the name is what gets drawn across the window's title bar).
  36655. */
  36656. void setName (const String& newName);
  36657. /** Sets an icon to show in the title bar, next to the title.
  36658. A copy is made internally of the image, so the caller can delete the
  36659. image after calling this. If 0 is passed-in, any existing icon will be
  36660. removed.
  36661. */
  36662. void setIcon (const Image* imageToUse);
  36663. /** Changes the height of the title-bar. */
  36664. void setTitleBarHeight (const int newHeight);
  36665. /** Returns the current title bar height. */
  36666. int getTitleBarHeight() const;
  36667. /** Changes the set of title-bar buttons being shown.
  36668. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36669. should be shown on the title bar. This value is a bitwise
  36670. combination of values from the TitleBarButtons enum. Note
  36671. that it can be "allButtons" to get them all.
  36672. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  36673. left side of the bar; if false, they'll be placed at the right
  36674. */
  36675. void setTitleBarButtonsRequired (const int requiredButtons,
  36676. const bool positionTitleBarButtonsOnLeft);
  36677. /** Sets whether the title should be centred within the window.
  36678. If true, the title text is shown in the middle of the title-bar; if false,
  36679. it'll be shown at the left of the bar.
  36680. */
  36681. void setTitleBarTextCentred (const bool textShouldBeCentred);
  36682. /** Creates a menu inside this window.
  36683. @param menuBarModel this specifies a MenuBarModel that should be used to
  36684. generate the contents of a menu bar that will be placed
  36685. just below the title bar, and just above any content
  36686. component. If this value is zero, any existing menu bar
  36687. will be removed from the component; if non-zero, one will
  36688. be added if it's required.
  36689. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  36690. or less to use the look-and-feel's default size.
  36691. */
  36692. void setMenuBar (MenuBarModel* menuBarModel,
  36693. const int menuBarHeight = 0);
  36694. /** This method is called when the user tries to close the window.
  36695. This is triggered by the user clicking the close button, or using some other
  36696. OS-specific key shortcut or OS menu for getting rid of a window.
  36697. If the window is just a pop-up, you should override this closeButtonPressed()
  36698. method and make it delete the window in whatever way is appropriate for your
  36699. app. E.g. you might just want to call "delete this".
  36700. If your app is centred around this window such that the whole app should quit when
  36701. the window is closed, then you will probably want to use this method as an opportunity
  36702. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  36703. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  36704. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  36705. or closing it via the taskbar icon on Windows).
  36706. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  36707. redirects it to call this method, so any methods of closing the window that are
  36708. caught by userTriedToCloseWindow() will also end up here).
  36709. */
  36710. virtual void closeButtonPressed();
  36711. /** Callback that is triggered when the minimise button is pressed.
  36712. The default implementation of this calls ResizableWindow::setMinimised(), but
  36713. you can override it to do more customised behaviour.
  36714. */
  36715. virtual void minimiseButtonPressed();
  36716. /** Callback that is triggered when the maximise button is pressed, or when the
  36717. title-bar is double-clicked.
  36718. The default implementation of this calls ResizableWindow::setFullScreen(), but
  36719. you can override it to do more customised behaviour.
  36720. */
  36721. virtual void maximiseButtonPressed();
  36722. /** Returns the close button, (or 0 if there isn't one). */
  36723. Button* getCloseButton() const throw();
  36724. /** Returns the minimise button, (or 0 if there isn't one). */
  36725. Button* getMinimiseButton() const throw();
  36726. /** Returns the maximise button, (or 0 if there isn't one). */
  36727. Button* getMaximiseButton() const throw();
  36728. /** A set of colour IDs to use to change the colour of various aspects of the window.
  36729. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36730. methods.
  36731. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36732. */
  36733. enum ColourIds
  36734. {
  36735. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  36736. and feel class how this is used. */
  36737. };
  36738. /** @internal */
  36739. void paint (Graphics& g);
  36740. /** @internal */
  36741. void resized();
  36742. /** @internal */
  36743. void lookAndFeelChanged();
  36744. /** @internal */
  36745. const BorderSize getBorderThickness();
  36746. /** @internal */
  36747. const BorderSize getContentComponentBorder();
  36748. /** @internal */
  36749. void mouseDoubleClick (const MouseEvent& e);
  36750. /** @internal */
  36751. void userTriedToCloseWindow();
  36752. /** @internal */
  36753. void activeWindowStatusChanged();
  36754. /** @internal */
  36755. int getDesktopWindowStyleFlags() const;
  36756. /** @internal */
  36757. void parentHierarchyChanged();
  36758. juce_UseDebuggingNewOperator
  36759. private:
  36760. int titleBarHeight, menuBarHeight, requiredButtons;
  36761. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  36762. Button* titleBarButtons [3];
  36763. Image* titleBarIcon;
  36764. MenuBarComponent* menuBar;
  36765. MenuBarModel* menuBarModel;
  36766. class ButtonListenerProxy : public ButtonListener
  36767. {
  36768. public:
  36769. ButtonListenerProxy();
  36770. void buttonClicked (Button* button);
  36771. DocumentWindow* owner;
  36772. } buttonListener;
  36773. int getBorderSize() const;
  36774. void repaintTitleBar();
  36775. DocumentWindow (const DocumentWindow&);
  36776. const DocumentWindow& operator= (const DocumentWindow&);
  36777. };
  36778. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36779. /********* End of inlined file: juce_DocumentWindow.h *********/
  36780. class MultiDocumentPanel;
  36781. class MDITabbedComponentInternal;
  36782. /**
  36783. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  36784. component.
  36785. It's like a normal DocumentWindow but has some extra functionality to make sure
  36786. everything works nicely inside a MultiDocumentPanel.
  36787. @see MultiDocumentPanel
  36788. */
  36789. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  36790. {
  36791. public:
  36792. /**
  36793. */
  36794. MultiDocumentPanelWindow (const Colour& backgroundColour);
  36795. /** Destructor. */
  36796. ~MultiDocumentPanelWindow();
  36797. /** @internal */
  36798. void maximiseButtonPressed();
  36799. /** @internal */
  36800. void closeButtonPressed();
  36801. /** @internal */
  36802. void activeWindowStatusChanged();
  36803. /** @internal */
  36804. void broughtToFront();
  36805. juce_UseDebuggingNewOperator
  36806. private:
  36807. void updateOrder();
  36808. MultiDocumentPanel* getOwner() const throw();
  36809. };
  36810. /**
  36811. A component that contains a set of other components either in floating windows
  36812. or tabs.
  36813. This acts as a panel that can be used to hold a set of open document windows, with
  36814. different layout modes.
  36815. Use addDocument() and closeDocument() to add or remove components from the
  36816. panel - never use any of the Component methods to access the panel's child
  36817. components directly, as these are managed internally.
  36818. */
  36819. class JUCE_API MultiDocumentPanel : public Component,
  36820. private ComponentListener
  36821. {
  36822. public:
  36823. /** Creates an empty panel.
  36824. Use addDocument() and closeDocument() to add or remove components from the
  36825. panel - never use any of the Component methods to access the panel's child
  36826. components directly, as these are managed internally.
  36827. */
  36828. MultiDocumentPanel();
  36829. /** Destructor.
  36830. When deleted, this will call closeAllDocuments (false) to make sure all its
  36831. components are deleted. If you need to make sure all documents are saved
  36832. before closing, then you should call closeAllDocuments (true) and check that
  36833. it returns true before deleting the panel.
  36834. */
  36835. ~MultiDocumentPanel();
  36836. /** Tries to close all the documents.
  36837. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36838. be called for each open document, and any of these calls fails, this method
  36839. will stop and return false, leaving some documents still open.
  36840. If checkItsOkToCloseFirst is false, then all documents will be closed
  36841. unconditionally.
  36842. @see closeDocument
  36843. */
  36844. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  36845. /** Adds a document component to the panel.
  36846. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  36847. this will fail and return false. (If it does fail, the component passed-in will not be
  36848. deleted, even if deleteWhenRemoved was set to true).
  36849. The MultiDocumentPanel will deal with creating a window border to go around your component,
  36850. so just pass in the bare content component here, no need to give it a ResizableWindow
  36851. or DocumentWindow.
  36852. @param component the component to add
  36853. @param backgroundColour the background colour to use to fill the component's
  36854. window or tab
  36855. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  36856. or closeAllDocuments(), then it will be deleted. If false, then
  36857. the caller must handle the component's deletion
  36858. */
  36859. bool addDocument (Component* const component,
  36860. const Colour& backgroundColour,
  36861. const bool deleteWhenRemoved);
  36862. /** Closes one of the documents.
  36863. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  36864. be called, and if it fails, this method will return false without closing the
  36865. document.
  36866. If checkItsOkToCloseFirst is false, then the documents will be closed
  36867. unconditionally.
  36868. The component will be deleted if the deleteWhenRemoved parameter was set to
  36869. true when it was added with addDocument.
  36870. @see addDocument, closeAllDocuments
  36871. */
  36872. bool closeDocument (Component* component,
  36873. const bool checkItsOkToCloseFirst);
  36874. /** Returns the number of open document windows.
  36875. @see getDocument
  36876. */
  36877. int getNumDocuments() const throw();
  36878. /** Returns one of the open documents.
  36879. The order of the documents in this array may change when they are added, removed
  36880. or moved around.
  36881. @see getNumDocuments
  36882. */
  36883. Component* getDocument (const int index) const throw();
  36884. /** Returns the document component that is currently focused or on top.
  36885. If currently using floating windows, then this will be the component in the currently
  36886. active window, or the top component if none are active.
  36887. If it's currently in tabbed mode, then it'll return the component in the active tab.
  36888. @see setActiveDocument
  36889. */
  36890. Component* getActiveDocument() const throw();
  36891. /** Makes one of the components active and brings it to the top.
  36892. @see getActiveDocument
  36893. */
  36894. void setActiveDocument (Component* component);
  36895. /** Callback which gets invoked when the currently-active document changes. */
  36896. virtual void activeDocumentChanged();
  36897. /** Sets a limit on how many windows can be open at once.
  36898. If this is zero or less there's no limit (the default). addDocument() will fail
  36899. if this number is exceeded.
  36900. */
  36901. void setMaximumNumDocuments (const int maximumNumDocuments);
  36902. /** Sets an option to make the document fullscreen if there's only one document open.
  36903. If set to true, then if there's only one document, it'll fill the whole of this
  36904. component without tabs or a window border. If false, then tabs or a window
  36905. will always be shown, even if there's only one document. If there's more than
  36906. one document open, then this option makes no difference.
  36907. */
  36908. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  36909. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  36910. */
  36911. bool isFullscreenWhenOneDocument() const throw();
  36912. /** The different layout modes available. */
  36913. enum LayoutMode
  36914. {
  36915. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  36916. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  36917. };
  36918. /** Changes the panel's mode.
  36919. @see LayoutMode, getLayoutMode
  36920. */
  36921. void setLayoutMode (const LayoutMode newLayoutMode);
  36922. /** Returns the current layout mode. */
  36923. LayoutMode getLayoutMode() const throw() { return mode; }
  36924. /** Sets the background colour for the whole panel.
  36925. Each document has its own background colour, but this is the one used to fill the areas
  36926. behind them.
  36927. */
  36928. void setBackgroundColour (const Colour& newBackgroundColour);
  36929. /** Returns the current background colour.
  36930. @see setBackgroundColour
  36931. */
  36932. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  36933. /** A subclass must override this to say whether its currently ok for a document
  36934. to be closed.
  36935. This method is called by closeDocument() and closeAllDocuments() to indicate that
  36936. a document should be saved if possible, ready for it to be closed.
  36937. If this method returns true, then it means the document is ok and can be closed.
  36938. If it returns false, then it means that the closeDocument() method should stop
  36939. and not close.
  36940. Normally, you'd use this method to ask the user if they want to save any changes,
  36941. then return true if the save operation went ok. If the user cancelled the save
  36942. operation you could return false here to abort the close operation.
  36943. If your component is based on the FileBasedDocument class, then you'd probably want
  36944. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  36945. FileBasedDocument::savedOk
  36946. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  36947. */
  36948. virtual bool tryToCloseDocument (Component* component) = 0;
  36949. /** Creates a new window to be used for a document.
  36950. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  36951. but you might want to override it to return a custom component.
  36952. */
  36953. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  36954. /** @internal */
  36955. void paint (Graphics& g);
  36956. /** @internal */
  36957. void resized();
  36958. /** @internal */
  36959. void componentNameChanged (Component&);
  36960. juce_UseDebuggingNewOperator
  36961. private:
  36962. LayoutMode mode;
  36963. Array <Component*> components;
  36964. TabbedComponent* tabComponent;
  36965. Colour backgroundColour;
  36966. int maximumNumDocuments, numDocsBeforeTabsUsed;
  36967. friend class MultiDocumentPanelWindow;
  36968. friend class MDITabbedComponentInternal;
  36969. Component* getContainerComp (Component* c) const;
  36970. void updateOrder();
  36971. void addWindow (Component* component);
  36972. };
  36973. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36974. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  36975. #endif
  36976. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36977. #endif
  36978. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36979. #endif
  36980. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  36981. #endif
  36982. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36983. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  36984. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36985. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  36986. /**
  36987. For laying out a set of components, where the components have preferred sizes
  36988. and size limits, but where they are allowed to stretch to fill the available
  36989. space.
  36990. For example, if you have a component containing several other components, and
  36991. each one should be given a share of the total size, you could use one of these
  36992. to resize the child components when the parent component is resized. Then
  36993. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  36994. A StretchableLayoutManager operates only in one dimension, so if you have a set
  36995. of components stacked vertically on top of each other, you'd use one to manage their
  36996. heights. To build up complex arrangements of components, e.g. for applications
  36997. with multiple nested panels, you would use more than one StretchableLayoutManager.
  36998. E.g. by using two (one vertical, one horizontal), you could create a resizable
  36999. spreadsheet-style table.
  37000. E.g.
  37001. @code
  37002. class MyComp : public Component
  37003. {
  37004. StretchableLayoutManager myLayout;
  37005. MyComp()
  37006. {
  37007. myLayout.setItemLayout (0, // for item 0
  37008. 50, 100, // must be between 50 and 100 pixels in size
  37009. -0.6); // and its preferred size is 60% of the total available space
  37010. myLayout.setItemLayout (1, // for item 1
  37011. -0.2, -0.6, // size must be between 20% and 60% of the available space
  37012. 50); // and its preferred size is 50 pixels
  37013. }
  37014. void resized()
  37015. {
  37016. // make a list of two of our child components that we want to reposition
  37017. Component* comps[] = { myComp1, myComp2 };
  37018. // this will position the 2 components, one above the other, to fit
  37019. // vertically into the rectangle provided.
  37020. myLayout.layOutComponents (comps, 2,
  37021. 0, 0, getWidth(), getHeight(),
  37022. true);
  37023. }
  37024. };
  37025. @endcode
  37026. @see StretchableLayoutResizerBar
  37027. */
  37028. class JUCE_API StretchableLayoutManager
  37029. {
  37030. public:
  37031. /** Creates an empty layout.
  37032. You'll need to add some item properties to the layout before it can be used
  37033. to resize things - see setItemLayout().
  37034. */
  37035. StretchableLayoutManager();
  37036. /** Destructor. */
  37037. ~StretchableLayoutManager();
  37038. /** For a numbered item, this sets its size limits and preferred size.
  37039. @param itemIndex the index of the item to change.
  37040. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37041. indicates an absolute size in pixels. A negative number indicates a
  37042. proportion of the available space (e.g -0.5 is 50%)
  37043. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37044. indicates an absolute size in pixels. A negative number indicates a
  37045. proportion of the available space
  37046. @param preferredSize the size that this item would like to be, if there's enough room. A
  37047. positive number indicates an absolute size in pixels. A negative number
  37048. indicates a proportion of the available space
  37049. @see getItemLayout
  37050. */
  37051. void setItemLayout (const int itemIndex,
  37052. const double minimumSize,
  37053. const double maximumSize,
  37054. const double preferredSize);
  37055. /** For a numbered item, this returns its size limits and preferred size.
  37056. @param itemIndex the index of the item.
  37057. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37058. indicates an absolute size in pixels. A negative number indicates a
  37059. proportion of the available space (e.g -0.5 is 50%)
  37060. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37061. indicates an absolute size in pixels. A negative number indicates a
  37062. proportion of the available space
  37063. @param preferredSize the size that this item would like to be, if there's enough room. A
  37064. positive number indicates an absolute size in pixels. A negative number
  37065. indicates a proportion of the available space
  37066. @returns false if the item's properties hadn't been set
  37067. @see setItemLayout
  37068. */
  37069. bool getItemLayout (const int itemIndex,
  37070. double& minimumSize,
  37071. double& maximumSize,
  37072. double& preferredSize) const;
  37073. /** Clears all the properties that have been set with setItemLayout() and resets
  37074. this object to its initial state.
  37075. */
  37076. void clearAllItems();
  37077. /** Takes a set of components that correspond to the layout's items, and positions
  37078. them to fill a space.
  37079. This will try to give each item its preferred size, whether that's a relative size
  37080. or an absolute one.
  37081. @param components an array of components that correspond to each of the
  37082. numbered items that the StretchableLayoutManager object
  37083. has been told about with setItemLayout()
  37084. @param numComponents the number of components in the array that is passed-in. This
  37085. should be the same as the number of items this object has been
  37086. told about.
  37087. @param x the left of the rectangle in which the components should
  37088. be laid out
  37089. @param y the top of the rectangle in which the components should
  37090. be laid out
  37091. @param width the width of the rectangle in which the components should
  37092. be laid out
  37093. @param height the height of the rectangle in which the components should
  37094. be laid out
  37095. @param vertically if true, the components will be positioned in a vertical stack,
  37096. so that they fill the height of the rectangle. If false, they
  37097. will be placed side-by-side in a horizontal line, filling the
  37098. available width
  37099. @param resizeOtherDimension if true, this means that the components will have their
  37100. other dimension resized to fit the space - i.e. if the 'vertically'
  37101. parameter is true, their x-positions and widths are adjusted to fit
  37102. the x and width parameters; if 'vertically' is false, their y-positions
  37103. and heights are adjusted to fit the y and height parameters.
  37104. */
  37105. void layOutComponents (Component** const components,
  37106. int numComponents,
  37107. int x, int y, int width, int height,
  37108. const bool vertically,
  37109. const bool resizeOtherDimension);
  37110. /** Returns the current position of one of the items.
  37111. This is only a valid call after layOutComponents() has been called, as it
  37112. returns the last position that this item was placed at. If the layout was
  37113. vertical, the value returned will be the y position of the top of the item,
  37114. relative to the top of the rectangle in which the items were placed (so for
  37115. example, item 0 will always have position of 0, even in the rectangle passed
  37116. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  37117. the position returned is the item's left-hand position, again relative to the
  37118. x position of the rectangle used.
  37119. @see getItemCurrentSize, setItemPosition
  37120. */
  37121. int getItemCurrentPosition (const int itemIndex) const;
  37122. /** Returns the current size of one of the items.
  37123. This is only meaningful after layOutComponents() has been called, as it
  37124. returns the last size that this item was given. If the layout was done
  37125. vertically, it'll return the item's height in pixels; if it was horizontal,
  37126. it'll return its width.
  37127. @see getItemCurrentRelativeSize
  37128. */
  37129. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  37130. /** Returns the current size of one of the items.
  37131. This is only meaningful after layOutComponents() has been called, as it
  37132. returns the last size that this item was given. If the layout was done
  37133. vertically, it'll return a negative value representing the item's height relative
  37134. to the last size used for laying the components out; if the layout was done
  37135. horizontally it'll be the proportion of its width.
  37136. @see getItemCurrentAbsoluteSize
  37137. */
  37138. double getItemCurrentRelativeSize (const int itemIndex) const;
  37139. /** Moves one of the items, shifting along any other items as necessary in
  37140. order to get it to the desired position.
  37141. Calling this method will also update the preferred sizes of the items it
  37142. shuffles along, so that they reflect their new positions.
  37143. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  37144. about when it's dragged).
  37145. @param itemIndex the item to move
  37146. @param newPosition the absolute position that you'd like this item to move
  37147. to. The item might not be able to always reach exactly this position,
  37148. because other items may have minimum sizes that constrain how
  37149. far it can go
  37150. */
  37151. void setItemPosition (const int itemIndex,
  37152. int newPosition);
  37153. juce_UseDebuggingNewOperator
  37154. private:
  37155. struct ItemLayoutProperties
  37156. {
  37157. int itemIndex;
  37158. int currentSize;
  37159. double minSize, maxSize, preferredSize;
  37160. };
  37161. OwnedArray <ItemLayoutProperties> items;
  37162. int totalSize;
  37163. static int sizeToRealSize (double size, int totalSpace);
  37164. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  37165. void setTotalSize (const int newTotalSize);
  37166. int fitComponentsIntoSpace (const int startIndex,
  37167. const int endIndex,
  37168. const int availableSpace,
  37169. int startPos);
  37170. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  37171. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  37172. void updatePrefSizesToMatchCurrentPositions();
  37173. StretchableLayoutManager (const StretchableLayoutManager&);
  37174. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  37175. };
  37176. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37177. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  37178. #endif
  37179. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37180. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37181. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37182. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37183. /**
  37184. A component that acts as one of the vertical or horizontal bars you see being
  37185. used to resize panels in a window.
  37186. One of these acts with a StretchableLayoutManager to resize the other components.
  37187. @see StretchableLayoutManager
  37188. */
  37189. class JUCE_API StretchableLayoutResizerBar : public Component
  37190. {
  37191. public:
  37192. /** Creates a resizer bar for use on a specified layout.
  37193. @param layoutToUse the layout that will be affected when this bar
  37194. is dragged
  37195. @param itemIndexInLayout the item index in the layout that corresponds to
  37196. this bar component. You'll need to set up the item
  37197. properties in a suitable way for a divider bar, e.g.
  37198. for an 8-pixel wide bar which, you could call
  37199. myLayout->setItemLayout (barIndex, 8, 8, 8)
  37200. @param isBarVertical true if it's an upright bar that you drag left and
  37201. right; false for a horizontal one that you drag up and
  37202. down
  37203. */
  37204. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  37205. const int itemIndexInLayout,
  37206. const bool isBarVertical);
  37207. /** Destructor. */
  37208. ~StretchableLayoutResizerBar();
  37209. /** This is called when the bar is dragged.
  37210. This method must update the positions of any components whose position is
  37211. determined by the StretchableLayoutManager, because they might have just
  37212. moved.
  37213. The default implementation calls the resized() method of this component's
  37214. parent component, because that's often where you're likely to apply the
  37215. layout, but it can be overridden for more specific needs.
  37216. */
  37217. virtual void hasBeenMoved();
  37218. /** @internal */
  37219. void paint (Graphics& g);
  37220. /** @internal */
  37221. void mouseDown (const MouseEvent& e);
  37222. /** @internal */
  37223. void mouseDrag (const MouseEvent& e);
  37224. juce_UseDebuggingNewOperator
  37225. private:
  37226. StretchableLayoutManager* layout;
  37227. int itemIndex, mouseDownPos;
  37228. bool isVertical;
  37229. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  37230. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  37231. };
  37232. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37233. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37234. #endif
  37235. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37236. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  37237. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37238. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37239. /**
  37240. A utility class for fitting a set of objects whose sizes can vary between
  37241. a minimum and maximum size, into a space.
  37242. This is a trickier algorithm than it would first seem, so I've put it in this
  37243. class to allow it to be shared by various bits of code.
  37244. To use it, create one of these objects, call addItem() to add the list of items
  37245. you need, then call resizeToFit(), which will change all their sizes. You can
  37246. then retrieve the new sizes with getItemSize() and getNumItems().
  37247. It's currently used by the TableHeaderComponent for stretching out the table
  37248. headings to fill the table's width.
  37249. */
  37250. class StretchableObjectResizer
  37251. {
  37252. public:
  37253. /** Creates an empty object resizer. */
  37254. StretchableObjectResizer();
  37255. /** Destructor. */
  37256. ~StretchableObjectResizer();
  37257. /** Adds an item to the list.
  37258. The order parameter lets you specify groups of items that are resized first when some
  37259. space needs to be found. Those items with an order of 0 will be the first ones to be
  37260. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  37261. will then try resizing the items with an order of 1, then 2, and so on.
  37262. */
  37263. void addItem (const double currentSize,
  37264. const double minSize,
  37265. const double maxSize,
  37266. const int order = 0);
  37267. /** Resizes all the items to fit this amount of space.
  37268. This will attempt to fit them in without exceeding each item's miniumum and
  37269. maximum sizes. In cases where none of the items can be expanded or enlarged any
  37270. further, the final size may be greater or less than the size passed in.
  37271. After calling this method, you can retrieve the new sizes with the getItemSize()
  37272. method.
  37273. */
  37274. void resizeToFit (const double targetSize);
  37275. /** Returns the number of items that have been added. */
  37276. int getNumItems() const throw() { return items.size(); }
  37277. /** Returns the size of one of the items. */
  37278. double getItemSize (const int index) const throw();
  37279. juce_UseDebuggingNewOperator
  37280. private:
  37281. struct Item
  37282. {
  37283. double size;
  37284. double minSize;
  37285. double maxSize;
  37286. int order;
  37287. };
  37288. OwnedArray <Item> items;
  37289. StretchableObjectResizer (const StretchableObjectResizer&);
  37290. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  37291. };
  37292. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37293. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  37294. #endif
  37295. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  37296. #endif
  37297. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  37298. #endif
  37299. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  37300. #endif
  37301. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37302. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  37303. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37304. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37305. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  37306. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37307. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37308. /********* Start of inlined file: juce_FileFilter.h *********/
  37309. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37310. #define __JUCE_FILEFILTER_JUCEHEADER__
  37311. /**
  37312. Interface for deciding which files are suitable for something.
  37313. For example, this is used by DirectoryContentsList to select which files
  37314. go into the list.
  37315. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37316. */
  37317. class JUCE_API FileFilter
  37318. {
  37319. public:
  37320. /** Creates a filter with the given description.
  37321. The description can be returned later with the getDescription() method.
  37322. */
  37323. FileFilter (const String& filterDescription);
  37324. /** Destructor. */
  37325. virtual ~FileFilter();
  37326. /** Returns the description that the filter was created with. */
  37327. const String& getDescription() const throw();
  37328. /** Should return true if this file is suitable for inclusion in whatever context
  37329. the object is being used.
  37330. */
  37331. virtual bool isFileSuitable (const File& file) const = 0;
  37332. /** Should return true if this directory is suitable for inclusion in whatever context
  37333. the object is being used.
  37334. */
  37335. virtual bool isDirectorySuitable (const File& file) const = 0;
  37336. protected:
  37337. String description;
  37338. };
  37339. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  37340. /********* End of inlined file: juce_FileFilter.h *********/
  37341. /**
  37342. A class to asynchronously scan for details about the files in a directory.
  37343. This keeps a list of files and some information about them, using a background
  37344. thread to scan for more files. As files are found, it broadcasts change messages
  37345. to tell any listeners.
  37346. @see FileListComponent, FileBrowserComponent
  37347. */
  37348. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  37349. public TimeSliceClient
  37350. {
  37351. public:
  37352. /** Creates a directory list.
  37353. To set the directory it should point to, use setDirectory(), which will
  37354. also start it scanning for files on the background thread.
  37355. When the background thread finds and adds new files to this list, the
  37356. ChangeBroadcaster class will send a change message, so you can register
  37357. listeners and update them when the list changes.
  37358. @param fileFilter an optional filter to select which files are
  37359. included in the list. If this is 0, then all files
  37360. and directories are included. Make sure that the
  37361. filter doesn't get deleted during the lifetime of this
  37362. object
  37363. @param threadToUse a thread object that this list can use
  37364. to scan for files as a background task. Make sure
  37365. that the thread you give it has been started, or you
  37366. won't get any files!
  37367. */
  37368. DirectoryContentsList (const FileFilter* const fileFilter,
  37369. TimeSliceThread& threadToUse);
  37370. /** Destructor. */
  37371. ~DirectoryContentsList();
  37372. /** Sets the directory to look in for files.
  37373. If the directory that's passed in is different to the current one, this will
  37374. also start the background thread scanning it for files.
  37375. */
  37376. void setDirectory (const File& directory,
  37377. const bool includeDirectories,
  37378. const bool includeFiles);
  37379. /** Returns the directory that's currently being used. */
  37380. const File& getDirectory() const throw();
  37381. /** Clears the list, and stops the thread scanning for files. */
  37382. void clear();
  37383. /** Clears the list and restarts scanning the directory for files. */
  37384. void refresh();
  37385. /** True if the background thread hasn't yet finished scanning for files. */
  37386. bool isStillLoading() const;
  37387. /** Tells the list whether or not to ignore hidden files.
  37388. By default these are ignored.
  37389. */
  37390. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  37391. /** Returns true if hidden files are ignored.
  37392. @see setIgnoresHiddenFiles
  37393. */
  37394. bool ignoresHiddenFiles() const throw() { return ignoreHiddenFiles; }
  37395. /** Contains cached information about one of the files in a DirectoryContentsList.
  37396. */
  37397. struct FileInfo
  37398. {
  37399. /** The filename.
  37400. This isn't a full pathname, it's just the last part of the path, same as you'd
  37401. get from File::getFileName().
  37402. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  37403. */
  37404. String filename;
  37405. /** File size in bytes. */
  37406. int64 fileSize;
  37407. /** File modification time.
  37408. As supplied by File::getLastModificationTime().
  37409. */
  37410. Time modificationTime;
  37411. /** File creation time.
  37412. As supplied by File::getCreationTime().
  37413. */
  37414. Time creationTime;
  37415. /** True if the file is a directory. */
  37416. bool isDirectory;
  37417. /** True if the file is read-only. */
  37418. bool isReadOnly;
  37419. };
  37420. /** Returns the number of files currently available in the list.
  37421. The info about one of these files can be retrieved with getFileInfo() or
  37422. getFile().
  37423. Obviously as the background thread runs and scans the directory for files, this
  37424. number will change.
  37425. @see getFileInfo, getFile
  37426. */
  37427. int getNumFiles() const;
  37428. /** Returns the cached information about one of the files in the list.
  37429. If the index is in-range, this will return true and will copy the file's details
  37430. to the structure that is passed-in.
  37431. If it returns false, then the index wasn't in range, and the structure won't
  37432. be affected.
  37433. @see getNumFiles, getFile
  37434. */
  37435. bool getFileInfo (const int index,
  37436. FileInfo& resultInfo) const;
  37437. /** Returns one of the files in the list.
  37438. @param index should be less than getNumFiles(). If this is out-of-range, the
  37439. return value will be File::nonexistent
  37440. @see getNumFiles, getFileInfo
  37441. */
  37442. const File getFile (const int index) const;
  37443. /** Returns the file filter being used.
  37444. The filter is specified in the constructor.
  37445. */
  37446. const FileFilter* getFilter() const throw() { return fileFilter; }
  37447. /** @internal */
  37448. bool useTimeSlice();
  37449. /** @internal */
  37450. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  37451. /** @internal */
  37452. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  37453. const DirectoryContentsList::FileInfo* const second) throw();
  37454. juce_UseDebuggingNewOperator
  37455. private:
  37456. File root;
  37457. const FileFilter* fileFilter;
  37458. TimeSliceThread& thread;
  37459. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  37460. CriticalSection fileListLock;
  37461. OwnedArray <FileInfo> files;
  37462. void* volatile fileFindHandle;
  37463. bool volatile shouldStop;
  37464. void changed();
  37465. bool checkNextFile (bool& hasChanged);
  37466. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  37467. const int64 fileSize, const Time& modTime,
  37468. const Time& creationTime, const bool isReadOnly);
  37469. DirectoryContentsList (const DirectoryContentsList&);
  37470. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  37471. };
  37472. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37473. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  37474. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  37475. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37476. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37477. /**
  37478. A listener for user selection events in a file browser.
  37479. This is used by a FileBrowserComponent or FileListComponent.
  37480. */
  37481. class JUCE_API FileBrowserListener
  37482. {
  37483. public:
  37484. /** Destructor. */
  37485. virtual ~FileBrowserListener();
  37486. /** Callback when the user selects a different file in the browser. */
  37487. virtual void selectionChanged() = 0;
  37488. /** Callback when the user clicks on a file in the browser. */
  37489. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  37490. /** Callback when the user double-clicks on a file in the browser. */
  37491. virtual void fileDoubleClicked (const File& file) = 0;
  37492. };
  37493. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37494. /********* End of inlined file: juce_FileBrowserListener.h *********/
  37495. /**
  37496. A base class for components that display a list of the files in a directory.
  37497. @see DirectoryContentsList
  37498. */
  37499. class JUCE_API DirectoryContentsDisplayComponent
  37500. {
  37501. public:
  37502. /**
  37503. */
  37504. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  37505. /** Destructor. */
  37506. virtual ~DirectoryContentsDisplayComponent();
  37507. /** Returns the file that the user has currently selected.
  37508. Returns File::nonexistent if none is selected.
  37509. */
  37510. virtual const File getSelectedFile() const = 0;
  37511. /** Scrolls this view to the top. */
  37512. virtual void scrollToTop() = 0;
  37513. /** Adds a listener to be told when files are selected or clicked.
  37514. @see removeListener
  37515. */
  37516. void addListener (FileBrowserListener* const listener) throw();
  37517. /** Removes a listener.
  37518. @see addListener
  37519. */
  37520. void removeListener (FileBrowserListener* const listener) throw();
  37521. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37522. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37523. methods.
  37524. Note that you can also use the constants from TextEditor::ColourIds to change the
  37525. colour of the text editor that is opened when a label is editable.
  37526. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37527. */
  37528. enum ColourIds
  37529. {
  37530. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  37531. textColourId = 0x1000541, /**< The colour for the text. */
  37532. };
  37533. /** @internal */
  37534. void sendSelectionChangeMessage();
  37535. /** @internal */
  37536. void sendDoubleClickMessage (const File& file);
  37537. /** @internal */
  37538. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  37539. juce_UseDebuggingNewOperator
  37540. protected:
  37541. DirectoryContentsList& fileList;
  37542. SortedSet <void*> listeners;
  37543. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  37544. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  37545. };
  37546. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  37547. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  37548. #endif
  37549. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  37550. #endif
  37551. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37552. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  37553. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37554. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37555. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  37556. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37557. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37558. /**
  37559. Base class for components that live inside a file chooser dialog box and
  37560. show previews of the files that get selected.
  37561. One of these allows special extra information to be displayed for files
  37562. in a dialog box as the user selects them. Each time the current file or
  37563. directory is changed, the selectedFileChanged() method will be called
  37564. to allow it to update itself appropriately.
  37565. @see FileChooser, ImagePreviewComponent
  37566. */
  37567. class JUCE_API FilePreviewComponent : public Component
  37568. {
  37569. public:
  37570. /** Creates a FilePreviewComponent. */
  37571. FilePreviewComponent();
  37572. /** Destructor. */
  37573. ~FilePreviewComponent();
  37574. /** Called to indicate that the user's currently selected file has changed.
  37575. @param newSelectedFile the newly selected file or directory, which may be
  37576. File::nonexistent if none is selected.
  37577. */
  37578. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  37579. juce_UseDebuggingNewOperator
  37580. private:
  37581. FilePreviewComponent (const FilePreviewComponent&);
  37582. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  37583. };
  37584. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37585. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  37586. /**
  37587. A component for browsing and selecting a file or directory to open or save.
  37588. This contains a FileListComponent and adds various boxes and controls for
  37589. navigating and selecting a file. It can work in different modes so that it can
  37590. be used for loading or saving a file, or for choosing a directory.
  37591. @see FileChooserDialogBox, FileChooser, FileListComponent
  37592. */
  37593. class JUCE_API FileBrowserComponent : public Component,
  37594. public ChangeBroadcaster,
  37595. private FileBrowserListener,
  37596. private TextEditorListener,
  37597. private ButtonListener,
  37598. private ComboBoxListener
  37599. {
  37600. public:
  37601. /** Various modes that the browser can be used in.
  37602. One of these is passed into the constructor.
  37603. */
  37604. enum FileChooserMode
  37605. {
  37606. loadFileMode, /**< the component should allow the user to choose an existing
  37607. file with the intention of opening it. */
  37608. saveFileMode, /**< the component should allow the user to specify the name of
  37609. a file that will be used to save something. */
  37610. chooseDirectoryMode /**< the component should allow the user to select an existing
  37611. directory. */
  37612. };
  37613. /** Creates a FileBrowserComponent.
  37614. @param browserMode The intended purpose for the browser - see the
  37615. FileChooserMode enum for the various options
  37616. @param initialFileOrDirectory The file or directory that should be selected when
  37617. the component begins. If this is File::nonexistent,
  37618. a default directory will be chosen.
  37619. @param fileFilter an optional filter to use to determine which files
  37620. are shown. If this is 0 then all files are displayed. Note
  37621. that a pointer is kept internally to this object, so
  37622. make sure that it is not deleted before the browser object
  37623. is deleted.
  37624. @param previewComp an optional preview component that will be used to
  37625. show previews of files that the user selects
  37626. @param useTreeView if this is false, the files are shown in a list; if true,
  37627. they are shown in a treeview
  37628. @param filenameTextBoxIsReadOnly if true, the user won't be allowed to type their own
  37629. text into the filename box.
  37630. */
  37631. FileBrowserComponent (FileChooserMode browserMode,
  37632. const File& initialFileOrDirectory,
  37633. const FileFilter* fileFilter,
  37634. FilePreviewComponent* previewComp,
  37635. const bool useTreeView = false,
  37636. const bool filenameTextBoxIsReadOnly = false);
  37637. /** Destructor. */
  37638. ~FileBrowserComponent();
  37639. /**
  37640. */
  37641. const File getCurrentFile() const throw();
  37642. /** Returns true if the current file is usable.
  37643. This can be used to decide whether the user can press "ok" for the
  37644. current file. What it does depends on the mode, so for example in an "open"
  37645. mode, the current file is only valid if one has been selected and if the file
  37646. exists. In a "save" mode, a non-existent file would also be valid.
  37647. */
  37648. bool currentFileIsValid() const;
  37649. /** Returns the directory whose contents are currently being shown in the listbox. */
  37650. const File getRoot() const;
  37651. /** Changes the directory that's being shown in the listbox. */
  37652. void setRoot (const File& newRootDirectory);
  37653. /** Equivalent to pressing the "up" button to browse the parent directory. */
  37654. void goUp();
  37655. /** Refreshes the directory that's currently being listed. */
  37656. void refresh();
  37657. /** Returns the browser's current mode. */
  37658. FileChooserMode getMode() const throw() { return mode; }
  37659. /** Returns a verb to describe what should happen when the file is accepted.
  37660. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  37661. mode, it'll be "Save", etc.
  37662. */
  37663. virtual const String getActionVerb() const;
  37664. /** Adds a listener to be told when the user selects and clicks on files.
  37665. @see removeListener
  37666. */
  37667. void addListener (FileBrowserListener* const listener) throw();
  37668. /** Removes a listener.
  37669. @see addListener
  37670. */
  37671. void removeListener (FileBrowserListener* const listener) throw();
  37672. /** @internal */
  37673. void resized();
  37674. /** @internal */
  37675. void buttonClicked (Button* b);
  37676. /** @internal */
  37677. void comboBoxChanged (ComboBox*);
  37678. /** @internal */
  37679. void textEditorTextChanged (TextEditor& editor);
  37680. /** @internal */
  37681. void textEditorReturnKeyPressed (TextEditor& editor);
  37682. /** @internal */
  37683. void textEditorEscapeKeyPressed (TextEditor& editor);
  37684. /** @internal */
  37685. void textEditorFocusLost (TextEditor& editor);
  37686. /** @internal */
  37687. bool keyPressed (const KeyPress& key);
  37688. /** @internal */
  37689. void selectionChanged();
  37690. /** @internal */
  37691. void fileClicked (const File& f, const MouseEvent& e);
  37692. /** @internal */
  37693. void fileDoubleClicked (const File& f);
  37694. /** @internal */
  37695. FilePreviewComponent* getPreviewComponent() const throw();
  37696. juce_UseDebuggingNewOperator
  37697. protected:
  37698. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  37699. private:
  37700. DirectoryContentsList* fileList;
  37701. FileFilter* directoriesOnlyFilter;
  37702. FileChooserMode mode;
  37703. File currentRoot;
  37704. SortedSet <void*> listeners;
  37705. DirectoryContentsDisplayComponent* fileListComponent;
  37706. FilePreviewComponent* previewComp;
  37707. ComboBox* currentPathBox;
  37708. TextEditor* filenameBox;
  37709. Button* goUpButton;
  37710. TimeSliceThread thread;
  37711. void sendListenerChangeMessage();
  37712. FileBrowserComponent (const FileBrowserComponent&);
  37713. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  37714. };
  37715. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  37716. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  37717. #endif
  37718. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  37719. #endif
  37720. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37721. /********* Start of inlined file: juce_FileChooser.h *********/
  37722. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  37723. #define __JUCE_FILECHOOSER_JUCEHEADER__
  37724. /**
  37725. Creates a dialog box to choose a file or directory to load or save.
  37726. To use a FileChooser:
  37727. - create one (as a local stack variable is the neatest way)
  37728. - call one of its browseFor.. methods
  37729. - if this returns true, the user has selected a file, so you can retrieve it
  37730. with the getResult() method.
  37731. e.g. @code
  37732. void loadMooseFile()
  37733. {
  37734. FileChooser myChooser ("Please select the moose you want to load...",
  37735. File::getSpecialLocation (File::userHomeDirectory),
  37736. "*.moose");
  37737. if (myChooser.browseForFileToOpen())
  37738. {
  37739. File mooseFile (myChooser.getResult());
  37740. loadMoose (mooseFile);
  37741. }
  37742. }
  37743. @endcode
  37744. */
  37745. class JUCE_API FileChooser
  37746. {
  37747. public:
  37748. /** Creates a FileChooser.
  37749. After creating one of these, use one of the browseFor... methods to display it.
  37750. @param dialogBoxTitle a text string to display in the dialog box to
  37751. tell the user what's going on
  37752. @param initialFileOrDirectory the file or directory that should be selected when
  37753. the dialog box opens. If this parameter is set to
  37754. File::nonexistent, a sensible default directory
  37755. will be used instead.
  37756. @param filePatternsAllowed a set of file patterns to specify which files can be
  37757. selected - each pattern should be separated by a
  37758. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  37759. empty string means that all files are allowed
  37760. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  37761. possible; if false, then a Juce-based browser dialog
  37762. box will always be used
  37763. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  37764. */
  37765. FileChooser (const String& dialogBoxTitle,
  37766. const File& initialFileOrDirectory = File::nonexistent,
  37767. const String& filePatternsAllowed = String::empty,
  37768. const bool useOSNativeDialogBox = true);
  37769. /** Destructor. */
  37770. ~FileChooser();
  37771. /** Shows a dialog box to choose a file to open.
  37772. This will display the dialog box modally, using an "open file" mode, so that
  37773. it won't allow non-existent files or directories to be chosen.
  37774. @param previewComponent an optional component to display inside the dialog
  37775. box to show special info about the files that the user
  37776. is browsing. The component will not be deleted by this
  37777. object, so the caller must take care of it.
  37778. @returns true if the user selected a file, in which case, use the getResult()
  37779. method to find out what it was. Returns false if they cancelled instead.
  37780. @see browseForFileToSave, browseForDirectory
  37781. */
  37782. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  37783. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  37784. The files that are returned can be obtained by calling getResults(). See
  37785. browseForFileToOpen() for more info about the behaviour of this method.
  37786. */
  37787. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  37788. /** Shows a dialog box to choose a file to save.
  37789. This will display the dialog box modally, using an "save file" mode, so it
  37790. will allow non-existent files to be chosen, but not directories.
  37791. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  37792. the user if they're sure they want to overwrite a file that already
  37793. exists
  37794. @returns true if the user chose a file and pressed 'ok', in which case, use
  37795. the getResult() method to find out what the file was. Returns false
  37796. if they cancelled instead.
  37797. @see browseForFileToOpen, browseForDirectory
  37798. */
  37799. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  37800. /** Shows a dialog box to choose a directory.
  37801. This will display the dialog box modally, using an "open directory" mode, so it
  37802. will only allow directories to be returned, not files.
  37803. @returns true if the user chose a directory and pressed 'ok', in which case, use
  37804. the getResult() method to find out what they chose. Returns false
  37805. if they cancelled instead.
  37806. @see browseForFileToOpen, browseForFileToSave
  37807. */
  37808. bool browseForDirectory();
  37809. /** Returns the last file that was chosen by one of the browseFor methods.
  37810. After calling the appropriate browseFor... method, this method lets you
  37811. find out what file or directory they chose.
  37812. Note that the file returned is only valid if the browse method returned true (i.e.
  37813. if the user pressed 'ok' rather than cancelling).
  37814. If you're using a multiple-file select, then use the getResults() method instead,
  37815. to obtain the list of all files chosen.
  37816. @see getResults
  37817. */
  37818. const File getResult() const;
  37819. /** Returns a list of all the files that were chosen during the last call to a
  37820. browse method.
  37821. This array may be empty if no files were chosen, or can contain multiple entries
  37822. if multiple files were chosen.
  37823. @see getResult
  37824. */
  37825. const OwnedArray <File>& getResults() const;
  37826. juce_UseDebuggingNewOperator
  37827. private:
  37828. String title, filters;
  37829. File startingFile;
  37830. OwnedArray <File> results;
  37831. bool useNativeDialogBox;
  37832. bool showDialog (const bool isDirectory,
  37833. const bool isSave,
  37834. const bool warnAboutOverwritingExistingFiles,
  37835. const bool selectMultipleFiles,
  37836. FilePreviewComponent* const previewComponent);
  37837. static void showPlatformDialog (OwnedArray<File>& results,
  37838. const String& title,
  37839. const File& file,
  37840. const String& filters,
  37841. bool isDirectory,
  37842. bool isSave,
  37843. bool warnAboutOverwritingExistingFiles,
  37844. bool selectMultipleFiles,
  37845. FilePreviewComponent* previewComponent);
  37846. };
  37847. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  37848. /********* End of inlined file: juce_FileChooser.h *********/
  37849. #endif
  37850. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37851. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  37852. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37853. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37854. /**
  37855. A file open/save dialog box.
  37856. This is a Juce-based file dialog box; to use a native file chooser, see the
  37857. FileChooser class.
  37858. To use one of these, create it and call its show() method. e.g.
  37859. @code
  37860. {
  37861. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  37862. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37863. File::nonexistent,
  37864. &wildcardFilter,
  37865. 0);
  37866. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  37867. T("Please choose some kind of file that you want to open..."),
  37868. browser,
  37869. getLookAndFeel().alertWindowBackground);
  37870. if (dialogBox.show())
  37871. {
  37872. File selectedFile = browser.getCurrentFile();
  37873. ...
  37874. }
  37875. }
  37876. @endcode
  37877. @see FileChooser
  37878. */
  37879. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37880. public ButtonListener,
  37881. public FileBrowserListener
  37882. {
  37883. public:
  37884. /** Creates a file chooser box.
  37885. @param title the main title to show at the top of the box
  37886. @param instructions an optional longer piece of text to show below the title in
  37887. a smaller font, describing in more detail what's required.
  37888. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37889. box. Make sure you delete this after (but not before!) the
  37890. dialog box has been deleted.
  37891. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37892. if they try to select a file that already exists. (This
  37893. flag is only used when saving files)
  37894. @param backgroundColour the background colour for the top level window
  37895. @see FileBrowserComponent, FilePreviewComponent
  37896. */
  37897. FileChooserDialogBox (const String& title,
  37898. const String& instructions,
  37899. FileBrowserComponent& browserComponent,
  37900. const bool warnAboutOverwritingExistingFiles,
  37901. const Colour& backgroundColour);
  37902. /** Destructor. */
  37903. ~FileChooserDialogBox();
  37904. /** Displays and runs the dialog box modally.
  37905. This will show the box with the specified size, returning true if the user
  37906. pressed 'ok', or false if they cancelled.
  37907. Leave the width or height as 0 to use the default size
  37908. */
  37909. bool show (int width = 0,int height = 0);
  37910. /** @internal */
  37911. void buttonClicked (Button* button);
  37912. /** @internal */
  37913. void closeButtonPressed();
  37914. /** @internal */
  37915. void selectionChanged();
  37916. /** @internal */
  37917. void fileClicked (const File& file, const MouseEvent& e);
  37918. /** @internal */
  37919. void fileDoubleClicked (const File& file);
  37920. juce_UseDebuggingNewOperator
  37921. private:
  37922. class ContentComponent : public Component
  37923. {
  37924. public:
  37925. ContentComponent();
  37926. ~ContentComponent();
  37927. void paint (Graphics& g);
  37928. void resized();
  37929. String instructions;
  37930. GlyphArrangement text;
  37931. FileBrowserComponent* chooserComponent;
  37932. FilePreviewComponent* previewComponent;
  37933. TextButton* okButton;
  37934. TextButton* cancelButton;
  37935. };
  37936. ContentComponent* content;
  37937. const bool warnAboutOverwritingExistingFiles;
  37938. FileChooserDialogBox (const FileChooserDialogBox&);
  37939. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37940. };
  37941. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37942. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  37943. #endif
  37944. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37945. #endif
  37946. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37947. /********* Start of inlined file: juce_FileListComponent.h *********/
  37948. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37949. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37950. /**
  37951. A component that displays the files in a directory as a listbox.
  37952. This implements the DirectoryContentsDisplayComponent base class so that
  37953. it can be used in a FileBrowserComponent.
  37954. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37955. class and the FileBrowserListener class.
  37956. @see DirectoryContentsList, FileTreeComponent
  37957. */
  37958. class JUCE_API FileListComponent : public ListBox,
  37959. public DirectoryContentsDisplayComponent,
  37960. private ListBoxModel,
  37961. private ChangeListener
  37962. {
  37963. public:
  37964. /** Creates a listbox to show the contents of a specified directory.
  37965. */
  37966. FileListComponent (DirectoryContentsList& listToShow);
  37967. /** Destructor. */
  37968. ~FileListComponent();
  37969. /** Returns the file that the user has currently selected.
  37970. Returns File::nonexistent if none is selected.
  37971. */
  37972. const File getSelectedFile() const;
  37973. /** Scrolls to the top of the list. */
  37974. void scrollToTop();
  37975. /** @internal */
  37976. void changeListenerCallback (void*);
  37977. /** @internal */
  37978. int getNumRows();
  37979. /** @internal */
  37980. void paintListBoxItem (int, Graphics&, int, int, bool);
  37981. /** @internal */
  37982. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37983. /** @internal */
  37984. void selectedRowsChanged (int lastRowSelected);
  37985. /** @internal */
  37986. void deleteKeyPressed (int currentSelectedRow);
  37987. /** @internal */
  37988. void returnKeyPressed (int currentSelectedRow);
  37989. juce_UseDebuggingNewOperator
  37990. private:
  37991. FileListComponent (const FileListComponent&);
  37992. const FileListComponent& operator= (const FileListComponent&);
  37993. File lastDirectory;
  37994. };
  37995. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37996. /********* End of inlined file: juce_FileListComponent.h *********/
  37997. #endif
  37998. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37999. #endif
  38000. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38001. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  38002. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38003. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38004. /**
  38005. Shows a set of file paths in a list, allowing them to be added, removed or
  38006. re-ordered.
  38007. @see FileSearchPath
  38008. */
  38009. class JUCE_API FileSearchPathListComponent : public Component,
  38010. public SettableTooltipClient,
  38011. public FileDragAndDropTarget,
  38012. private ButtonListener,
  38013. private ListBoxModel
  38014. {
  38015. public:
  38016. /** Creates an empty FileSearchPathListComponent.
  38017. */
  38018. FileSearchPathListComponent();
  38019. /** Destructor. */
  38020. ~FileSearchPathListComponent();
  38021. /** Returns the path as it is currently shown. */
  38022. const FileSearchPath& getPath() const throw() { return path; }
  38023. /** Changes the current path. */
  38024. void setPath (const FileSearchPath& newPath);
  38025. /** Sets a file or directory to be the default starting point for the browser to show.
  38026. This is only used if the current file hasn't been set.
  38027. */
  38028. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  38029. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38030. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38031. methods.
  38032. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38033. */
  38034. enum ColourIds
  38035. {
  38036. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  38037. Make this transparent if you don't want the background to be filled. */
  38038. };
  38039. /** @internal */
  38040. int getNumRows();
  38041. /** @internal */
  38042. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  38043. /** @internal */
  38044. void deleteKeyPressed (int lastRowSelected);
  38045. /** @internal */
  38046. void returnKeyPressed (int lastRowSelected);
  38047. /** @internal */
  38048. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  38049. /** @internal */
  38050. void selectedRowsChanged (int lastRowSelected);
  38051. /** @internal */
  38052. void resized();
  38053. /** @internal */
  38054. void paint (Graphics& g);
  38055. /** @internal */
  38056. bool isInterestedInFileDrag (const StringArray& files);
  38057. /** @internal */
  38058. void filesDropped (const StringArray& files, int, int);
  38059. /** @internal */
  38060. void buttonClicked (Button* button);
  38061. juce_UseDebuggingNewOperator
  38062. private:
  38063. FileSearchPath path;
  38064. File defaultBrowseTarget;
  38065. ListBox* listBox;
  38066. Button* addButton;
  38067. Button* removeButton;
  38068. Button* changeButton;
  38069. Button* upButton;
  38070. Button* downButton;
  38071. void changed() throw();
  38072. void updateButtons() throw();
  38073. FileSearchPathListComponent (const FileSearchPathListComponent&);
  38074. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  38075. };
  38076. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38077. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  38078. #endif
  38079. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38080. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  38081. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38082. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38083. /**
  38084. A component that displays the files in a directory as a treeview.
  38085. This implements the DirectoryContentsDisplayComponent base class so that
  38086. it can be used in a FileBrowserComponent.
  38087. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38088. class and the FileBrowserListener class.
  38089. @see DirectoryContentsList, FileListComponent
  38090. */
  38091. class JUCE_API FileTreeComponent : public TreeView,
  38092. public DirectoryContentsDisplayComponent
  38093. {
  38094. public:
  38095. /** Creates a listbox to show the contents of a specified directory.
  38096. */
  38097. FileTreeComponent (DirectoryContentsList& listToShow);
  38098. /** Destructor. */
  38099. ~FileTreeComponent();
  38100. /** Returns the number of selected files in the tree.
  38101. */
  38102. int getNumSelectedFiles() const throw() { return TreeView::getNumSelectedItems(); }
  38103. /** Returns one of the files that the user has currently selected.
  38104. Returns File::nonexistent if none is selected.
  38105. */
  38106. const File getSelectedFile (int index) const throw();
  38107. /** Returns the first of the files that the user has currently selected.
  38108. Returns File::nonexistent if none is selected.
  38109. */
  38110. const File getSelectedFile() const;
  38111. /** Scrolls the list to the top. */
  38112. void scrollToTop();
  38113. /** Setting a name for this allows tree items to be dragged.
  38114. The string that you pass in here will be returned by the getDragSourceDescription()
  38115. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  38116. */
  38117. void setDragAndDropDescription (const String& description) throw();
  38118. /** Returns the last value that was set by setDragAndDropDescription().
  38119. */
  38120. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  38121. juce_UseDebuggingNewOperator
  38122. private:
  38123. String dragAndDropDescription;
  38124. FileTreeComponent (const FileTreeComponent&);
  38125. const FileTreeComponent& operator= (const FileTreeComponent&);
  38126. };
  38127. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38128. /********* End of inlined file: juce_FileTreeComponent.h *********/
  38129. #endif
  38130. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38131. /********* Start of inlined file: juce_FilenameComponent.h *********/
  38132. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38133. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38134. class FilenameComponent;
  38135. /**
  38136. Listens for events happening to a FilenameComponent.
  38137. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  38138. register one of these objects for event callbacks when the filename is changed.
  38139. @see FilenameComponent
  38140. */
  38141. class JUCE_API FilenameComponentListener
  38142. {
  38143. public:
  38144. /** Destructor. */
  38145. virtual ~FilenameComponentListener() {}
  38146. /** This method is called after the FilenameComponent's file has been changed. */
  38147. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  38148. };
  38149. /**
  38150. Shows a filename as an editable text box, with a 'browse' button and a
  38151. drop-down list for recently selected files.
  38152. A handy component for dialogue boxes where you want the user to be able to
  38153. select a file or directory.
  38154. Attach an FilenameComponentListener using the addListener() method, and it will
  38155. get called each time the user changes the filename, either by browsing for a file
  38156. and clicking 'ok', or by typing a new filename into the box and pressing return.
  38157. @see FileChooser, ComboBox
  38158. */
  38159. class JUCE_API FilenameComponent : public Component,
  38160. public SettableTooltipClient,
  38161. public FileDragAndDropTarget,
  38162. private AsyncUpdater,
  38163. private ButtonListener,
  38164. private ComboBoxListener
  38165. {
  38166. public:
  38167. /** Creates a FilenameComponent.
  38168. @param name the name for this component.
  38169. @param currentFile the file to initially show in the box
  38170. @param canEditFilename if true, the user can manually edit the filename; if false,
  38171. they can only change it by browsing for a new file
  38172. @param isDirectory if true, the file will be treated as a directory, and
  38173. an appropriate directory browser used
  38174. @param isForSaving if true, the file browser will allow non-existent files to
  38175. be picked, as the file is assumed to be used for saving rather
  38176. than loading
  38177. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  38178. If an empty string is passed in, then the pattern is assumed to be "*"
  38179. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  38180. to any filenames that are entered or chosen
  38181. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  38182. will only appear if the initial file isn't valid)
  38183. */
  38184. FilenameComponent (const String& name,
  38185. const File& currentFile,
  38186. const bool canEditFilename,
  38187. const bool isDirectory,
  38188. const bool isForSaving,
  38189. const String& fileBrowserWildcard,
  38190. const String& enforcedSuffix,
  38191. const String& textWhenNothingSelected);
  38192. /** Destructor. */
  38193. ~FilenameComponent();
  38194. /** Returns the currently displayed filename. */
  38195. const File getCurrentFile() const;
  38196. /** Changes the current filename.
  38197. If addToRecentlyUsedList is true, the filename will also be added to the
  38198. drop-down list of recent files.
  38199. If sendChangeNotification is false, then the listeners won't be told of the
  38200. change.
  38201. */
  38202. void setCurrentFile (File newFile,
  38203. const bool addToRecentlyUsedList,
  38204. const bool sendChangeNotification = true);
  38205. /** Changes whether the use can type into the filename box.
  38206. */
  38207. void setFilenameIsEditable (const bool shouldBeEditable);
  38208. /** Sets a file or directory to be the default starting point for the browser to show.
  38209. This is only used if the current file hasn't been set.
  38210. */
  38211. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  38212. /** Returns all the entries on the recent files list.
  38213. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  38214. state of this list.
  38215. @see setRecentlyUsedFilenames
  38216. */
  38217. const StringArray getRecentlyUsedFilenames() const;
  38218. /** Sets all the entries on the recent files list.
  38219. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  38220. state of this list.
  38221. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  38222. */
  38223. void setRecentlyUsedFilenames (const StringArray& filenames);
  38224. /** Adds an entry to the recently-used files dropdown list.
  38225. If the file is already in the list, it will be moved to the top. A limit
  38226. is also placed on the number of items that are kept in the list.
  38227. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  38228. */
  38229. void addRecentlyUsedFile (const File& file);
  38230. /** Changes the limit for the number of files that will be stored in the recent-file list.
  38231. */
  38232. void setMaxNumberOfRecentFiles (const int newMaximum);
  38233. /** Changes the text shown on the 'browse' button.
  38234. By default this button just says "..." but you can change it. The button itself
  38235. can be changed using the look-and-feel classes, so it might not actually have any
  38236. text on it.
  38237. */
  38238. void setBrowseButtonText (const String& browseButtonText);
  38239. /** Adds a listener that will be called when the selected file is changed. */
  38240. void addListener (FilenameComponentListener* const listener) throw();
  38241. /** Removes a previously-registered listener. */
  38242. void removeListener (FilenameComponentListener* const listener) throw();
  38243. /** Gives the component a tooltip. */
  38244. void setTooltip (const String& newTooltip);
  38245. /** @internal */
  38246. void paintOverChildren (Graphics& g);
  38247. /** @internal */
  38248. void resized();
  38249. /** @internal */
  38250. void lookAndFeelChanged();
  38251. /** @internal */
  38252. bool isInterestedInFileDrag (const StringArray& files);
  38253. /** @internal */
  38254. void filesDropped (const StringArray& files, int, int);
  38255. /** @internal */
  38256. void fileDragEnter (const StringArray& files, int, int);
  38257. /** @internal */
  38258. void fileDragExit (const StringArray& files);
  38259. juce_UseDebuggingNewOperator
  38260. private:
  38261. ComboBox* filenameBox;
  38262. String lastFilename;
  38263. Button* browseButton;
  38264. int maxRecentFiles;
  38265. bool isDir, isSaving, isFileDragOver;
  38266. String wildcard, enforcedSuffix, browseButtonText;
  38267. SortedSet <void*> listeners;
  38268. File defaultBrowseFile;
  38269. void comboBoxChanged (ComboBox*);
  38270. void buttonClicked (Button* button);
  38271. void handleAsyncUpdate();
  38272. FilenameComponent (const FilenameComponent&);
  38273. const FilenameComponent& operator= (const FilenameComponent&);
  38274. };
  38275. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38276. /********* End of inlined file: juce_FilenameComponent.h *********/
  38277. #endif
  38278. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38279. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  38280. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38281. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38282. /**
  38283. A simple preview component that shows thumbnails of image files.
  38284. @see FileChooserDialogBox, FilePreviewComponent
  38285. */
  38286. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  38287. private Timer
  38288. {
  38289. public:
  38290. /** Creates an ImagePreviewComponent. */
  38291. ImagePreviewComponent();
  38292. /** Destructor. */
  38293. ~ImagePreviewComponent();
  38294. /** @internal */
  38295. void selectedFileChanged (const File& newSelectedFile);
  38296. /** @internal */
  38297. void paint (Graphics& g);
  38298. /** @internal */
  38299. void timerCallback();
  38300. juce_UseDebuggingNewOperator
  38301. private:
  38302. File fileToLoad;
  38303. Image* currentThumbnail;
  38304. String currentDetails;
  38305. void getThumbSize (int& w, int& h) const;
  38306. ImagePreviewComponent (const ImagePreviewComponent&);
  38307. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  38308. };
  38309. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38310. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  38311. #endif
  38312. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38313. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  38314. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38315. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38316. /**
  38317. A type of FileFilter that works by wildcard pattern matching.
  38318. This filter only allows files that match one of the specified patterns, but
  38319. allows all directories through.
  38320. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38321. */
  38322. class JUCE_API WildcardFileFilter : public FileFilter
  38323. {
  38324. public:
  38325. /**
  38326. Creates a wildcard filter for one or more patterns.
  38327. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  38328. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  38329. or .aiff.
  38330. The description is a name to show the user in a list of possible patterns, so
  38331. for the wav/aiff example, your description might be "audio files".
  38332. */
  38333. WildcardFileFilter (const String& wildcardPatterns,
  38334. const String& description);
  38335. /** Destructor. */
  38336. ~WildcardFileFilter();
  38337. /** Returns true if the filename matches one of the patterns specified. */
  38338. bool isFileSuitable (const File& file) const;
  38339. /** This always returns true. */
  38340. bool isDirectorySuitable (const File& file) const;
  38341. juce_UseDebuggingNewOperator
  38342. private:
  38343. StringArray wildcards;
  38344. };
  38345. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38346. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  38347. #endif
  38348. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  38349. /********* Start of inlined file: juce_AlertWindow.h *********/
  38350. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  38351. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  38352. /** A window that displays a message and has buttons for the user to react to it.
  38353. For simple dialog boxes with just a couple of buttons on them, there are
  38354. some static methods for running these.
  38355. For more complex dialogs, an AlertWindow can be created, then it can have some
  38356. buttons and components added to it, and its runModalLoop() method is then used to
  38357. show it. The value returned by runModalLoop() shows which button the
  38358. user pressed to dismiss the box.
  38359. @see ThreadWithProgressWindow
  38360. */
  38361. class JUCE_API AlertWindow : public TopLevelWindow,
  38362. private ButtonListener
  38363. {
  38364. public:
  38365. /** The type of icon to show in the dialog box. */
  38366. enum AlertIconType
  38367. {
  38368. NoIcon, /**< No icon will be shown on the dialog box. */
  38369. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  38370. user to answer a question. */
  38371. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  38372. warning about something and shouldn't be ignored. */
  38373. InfoIcon /**< An icon that indicates that the dialog box is just
  38374. giving the user some information, which doesn't require
  38375. a response from them. */
  38376. };
  38377. /** Creates an AlertWindow.
  38378. @param title the headline to show at the top of the dialog box
  38379. @param message a longer, more descriptive message to show underneath the
  38380. headline
  38381. @param iconType the type of icon to display
  38382. @param associatedComponent if this is non-zero, it specifies the component that the
  38383. alert window should be associated with. Depending on the look
  38384. and feel, this might be used for positioning of the alert window.
  38385. */
  38386. AlertWindow (const String& title,
  38387. const String& message,
  38388. AlertIconType iconType,
  38389. Component* associatedComponent = 0);
  38390. /** Destroys the AlertWindow */
  38391. ~AlertWindow();
  38392. /** Returns the type of alert icon that was specified when the window
  38393. was created. */
  38394. AlertIconType getAlertType() const throw() { return alertIconType; }
  38395. /** Changes the dialog box's message.
  38396. This will also resize the window to fit the new message if required.
  38397. */
  38398. void setMessage (const String& message);
  38399. /** Adds a button to the window.
  38400. @param name the text to show on the button
  38401. @param returnValue the value that should be returned from runModalLoop()
  38402. if this is the button that the user presses.
  38403. @param shortcutKey1 an optional key that can be pressed to trigger this button
  38404. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  38405. */
  38406. void addButton (const String& name,
  38407. const int returnValue,
  38408. const KeyPress& shortcutKey1 = KeyPress(),
  38409. const KeyPress& shortcutKey2 = KeyPress());
  38410. /** Returns the number of buttons that the window currently has. */
  38411. int getNumButtons() const;
  38412. /** Adds a textbox to the window for entering strings.
  38413. @param name an internal name for the text-box. This is the name to pass to
  38414. the getTextEditorContents() method to find out what the
  38415. user typed-in.
  38416. @param initialContents a string to show in the text box when it's first shown
  38417. @param onScreenLabel if this is non-empty, it will be displayed next to the
  38418. text-box to label it.
  38419. @param isPasswordBox if true, the text editor will display asterisks instead of
  38420. the actual text
  38421. @see getTextEditorContents
  38422. */
  38423. void addTextEditor (const String& name,
  38424. const String& initialContents,
  38425. const String& onScreenLabel = String::empty,
  38426. const bool isPasswordBox = false);
  38427. /** Returns the contents of a named textbox.
  38428. After showing an AlertWindow that contains a text editor, this can be
  38429. used to find out what the user has typed into it.
  38430. @param nameOfTextEditor the name of the text box that you're interested in
  38431. @see addTextEditor
  38432. */
  38433. const String getTextEditorContents (const String& nameOfTextEditor) const;
  38434. /** Adds a drop-down list of choices to the box.
  38435. After the box has been shown, the getComboBoxComponent() method can
  38436. be used to find out which item the user picked.
  38437. @param name the label to use for the drop-down list
  38438. @param items the list of items to show in it
  38439. @param onScreenLabel if this is non-empty, it will be displayed next to the
  38440. combo-box to label it.
  38441. @see getComboBoxComponent
  38442. */
  38443. void addComboBox (const String& name,
  38444. const StringArray& items,
  38445. const String& onScreenLabel = String::empty);
  38446. /** Returns a drop-down list that was added to the AlertWindow.
  38447. @param nameOfList the name that was passed into the addComboBox() method
  38448. when creating the drop-down
  38449. @returns the ComboBox component, or 0 if none was found for the given name.
  38450. */
  38451. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  38452. /** Adds a block of text.
  38453. This is handy for adding a multi-line note next to a textbox or combo-box,
  38454. to provide more details about what's going on.
  38455. */
  38456. void addTextBlock (const String& text);
  38457. /** Adds a progress-bar to the window.
  38458. @param progressValue a variable that will be repeatedly checked while the
  38459. dialog box is visible, to see how far the process has
  38460. got. The value should be in the range 0 to 1.0
  38461. */
  38462. void addProgressBarComponent (double& progressValue);
  38463. /** Adds a user-defined component to the dialog box.
  38464. @param component the component to add - its size should be set up correctly
  38465. before it is passed in. The caller is responsible for deleting
  38466. the component later on - the AlertWindow won't delete it.
  38467. */
  38468. void addCustomComponent (Component* const component);
  38469. /** Returns the number of custom components in the dialog box.
  38470. @see getCustomComponent, addCustomComponent
  38471. */
  38472. int getNumCustomComponents() const;
  38473. /** Returns one of the custom components in the dialog box.
  38474. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  38475. will return 0
  38476. @see getNumCustomComponents, addCustomComponent
  38477. */
  38478. Component* getCustomComponent (const int index) const;
  38479. /** Removes one of the custom components in the dialog box.
  38480. Note that this won't delete it, it just removes the component from the window
  38481. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  38482. will return 0
  38483. @returns the component that was removed (or zero)
  38484. @see getNumCustomComponents, addCustomComponent
  38485. */
  38486. Component* removeCustomComponent (const int index);
  38487. /** Returns true if the window contains any components other than just buttons.*/
  38488. bool containsAnyExtraComponents() const;
  38489. // easy-to-use message box functions:
  38490. /** Shows a dialog box that just has a message and a single button to get rid of it.
  38491. The box is shown modally, and the method returns after the user
  38492. has clicked the button (or pressed the escape or return keys).
  38493. @param iconType the type of icon to show
  38494. @param title the headline to show at the top of the box
  38495. @param message a longer, more descriptive message to show underneath the
  38496. headline
  38497. @param buttonText the text to show in the button - if this string is empty, the
  38498. default string "ok" (or a localised version) will be used.
  38499. @param associatedComponent if this is non-zero, it specifies the component that the
  38500. alert window should be associated with. Depending on the look
  38501. and feel, this might be used for positioning of the alert window.
  38502. */
  38503. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  38504. const String& title,
  38505. const String& message,
  38506. const String& buttonText = String::empty,
  38507. Component* associatedComponent = 0);
  38508. /** Shows a dialog box with two buttons.
  38509. Ideal for ok/cancel or yes/no choices. The return key can also be used
  38510. to trigger the first button, and the escape key for the second button.
  38511. @param iconType the type of icon to show
  38512. @param title the headline to show at the top of the box
  38513. @param message a longer, more descriptive message to show underneath the
  38514. headline
  38515. @param button1Text the text to show in the first button - if this string is
  38516. empty, the default string "ok" (or a localised version of it)
  38517. will be used.
  38518. @param button2Text the text to show in the second button - if this string is
  38519. empty, the default string "cancel" (or a localised version of it)
  38520. will be used.
  38521. @param associatedComponent if this is non-zero, it specifies the component that the
  38522. alert window should be associated with. Depending on the look
  38523. and feel, this might be used for positioning of the alert window.
  38524. @returns true if button 1 was clicked, false if it was button 2
  38525. */
  38526. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  38527. const String& title,
  38528. const String& message,
  38529. const String& button1Text = String::empty,
  38530. const String& button2Text = String::empty,
  38531. Component* associatedComponent = 0);
  38532. /** Shows a dialog box with three buttons.
  38533. Ideal for yes/no/cancel boxes.
  38534. The escape key can be used to trigger the third button.
  38535. @param iconType the type of icon to show
  38536. @param title the headline to show at the top of the box
  38537. @param message a longer, more descriptive message to show underneath the
  38538. headline
  38539. @param button1Text the text to show in the first button - if an empty string, then
  38540. "yes" will be used (or a localised version of it)
  38541. @param button2Text the text to show in the first button - if an empty string, then
  38542. "no" will be used (or a localised version of it)
  38543. @param button3Text the text to show in the first button - if an empty string, then
  38544. "cancel" will be used (or a localised version of it)
  38545. @param associatedComponent if this is non-zero, it specifies the component that the
  38546. alert window should be associated with. Depending on the look
  38547. and feel, this might be used for positioning of the alert window.
  38548. @returns one of the following values:
  38549. - 0 if the third button was pressed (normally used for 'cancel')
  38550. - 1 if the first button was pressed (normally used for 'yes')
  38551. - 2 if the middle button was pressed (normally used for 'no')
  38552. */
  38553. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  38554. const String& title,
  38555. const String& message,
  38556. const String& button1Text = String::empty,
  38557. const String& button2Text = String::empty,
  38558. const String& button3Text = String::empty,
  38559. Component* associatedComponent = 0);
  38560. /** Shows an operating-system native dialog box.
  38561. @param title the title to use at the top
  38562. @param bodyText the longer message to show
  38563. @param isOkCancel if true, this will show an ok/cancel box, if false,
  38564. it'll show a box with just an ok button
  38565. @returns true if the ok button was pressed, false if they pressed cancel.
  38566. */
  38567. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  38568. const String& bodyText,
  38569. bool isOkCancel);
  38570. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  38571. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38572. methods.
  38573. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38574. */
  38575. enum ColourIds
  38576. {
  38577. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  38578. textColourId = 0x1001810, /**< The colour for the text. */
  38579. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  38580. };
  38581. juce_UseDebuggingNewOperator
  38582. protected:
  38583. /** @internal */
  38584. void paint (Graphics& g);
  38585. /** @internal */
  38586. void mouseDown (const MouseEvent& e);
  38587. /** @internal */
  38588. void mouseDrag (const MouseEvent& e);
  38589. /** @internal */
  38590. bool keyPressed (const KeyPress& key);
  38591. /** @internal */
  38592. void buttonClicked (Button* button);
  38593. /** @internal */
  38594. void lookAndFeelChanged();
  38595. /** @internal */
  38596. void userTriedToCloseWindow();
  38597. /** @internal */
  38598. int getDesktopWindowStyleFlags() const;
  38599. private:
  38600. String text;
  38601. TextLayout textLayout;
  38602. AlertIconType alertIconType;
  38603. ComponentBoundsConstrainer constrainer;
  38604. ComponentDragger dragger;
  38605. Rectangle textArea;
  38606. VoidArray buttons, textBoxes, comboBoxes;
  38607. VoidArray progressBars, customComps, textBlocks, allComps;
  38608. StringArray textboxNames, comboBoxNames;
  38609. Font font;
  38610. Component* associatedComponent;
  38611. void updateLayout (const bool onlyIncreaseSize);
  38612. // disable copy constructor
  38613. AlertWindow (const AlertWindow&);
  38614. const AlertWindow& operator= (const AlertWindow&);
  38615. };
  38616. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  38617. /********* End of inlined file: juce_AlertWindow.h *********/
  38618. #endif
  38619. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  38620. #endif
  38621. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  38622. /********* Start of inlined file: juce_DialogWindow.h *********/
  38623. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  38624. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  38625. /**
  38626. A dialog-box style window.
  38627. This class is a convenient way of creating a DocumentWindow with a close button
  38628. that can be triggered by pressing the escape key.
  38629. Any of the methods available to a DocumentWindow or ResizableWindow are also
  38630. available to this, so it can be made resizable, have a menu bar, etc.
  38631. To add items to the box, see the ResizableWindow::setContentComponent() method.
  38632. Don't add components directly to this class - always put them in a content component!
  38633. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  38634. the user clicking the close button - for more info, see the DocumentWindow
  38635. help.
  38636. @see DocumentWindow, ResizableWindow
  38637. */
  38638. class JUCE_API DialogWindow : public DocumentWindow
  38639. {
  38640. public:
  38641. /** Creates a DialogWindow.
  38642. @param name the name to give the component - this is also
  38643. the title shown at the top of the window. To change
  38644. this later, use setName()
  38645. @param backgroundColour the colour to use for filling the window's background.
  38646. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  38647. close button to be triggered
  38648. @param addToDesktop if true, the window will be automatically added to the
  38649. desktop; if false, you can use it as a child component
  38650. */
  38651. DialogWindow (const String& name,
  38652. const Colour& backgroundColour,
  38653. const bool escapeKeyTriggersCloseButton,
  38654. const bool addToDesktop = true);
  38655. /** Destructor.
  38656. If a content component has been set with setContentComponent(), it
  38657. will be deleted.
  38658. */
  38659. ~DialogWindow();
  38660. /** Easy way of quickly showing a dialog box containing a given component.
  38661. This will open and display a DialogWindow containing a given component, returning
  38662. when the user clicks its close button.
  38663. It returns the value that was returned by the dialog box's runModalLoop() call.
  38664. To close the dialog programatically, you should call exitModalState (returnValue) on
  38665. the DialogWindow that is created. To find a pointer to this window from your
  38666. contentComponent, you can do something like this:
  38667. @code
  38668. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  38669. if (dw != 0)
  38670. dw->exitModalState (1234);
  38671. @endcode
  38672. @param dialogTitle the dialog box's title
  38673. @param contentComponent the content component for the dialog box. Make sure
  38674. that this has been set to the size you want it to
  38675. be before calling this method. The component won't
  38676. be deleted by this call, so you can re-use it or delete
  38677. it afterwards
  38678. @param componentToCentreAround if this is non-zero, it indicates a component that
  38679. you'd like to show this dialog box in front of. See the
  38680. DocumentWindow::centreAroundComponent() method for more
  38681. info on this parameter
  38682. @param backgroundColour a colour to use for the dialog box's background colour
  38683. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  38684. close button to be triggered
  38685. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  38686. a corner resizer
  38687. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  38688. to use a border or corner resizer component. See ResizableWindow::setResizable()
  38689. */
  38690. static int showModalDialog (const String& dialogTitle,
  38691. Component* contentComponent,
  38692. Component* componentToCentreAround,
  38693. const Colour& backgroundColour,
  38694. const bool escapeKeyTriggersCloseButton,
  38695. const bool shouldBeResizable = false,
  38696. const bool useBottomRightCornerResizer = false);
  38697. juce_UseDebuggingNewOperator
  38698. protected:
  38699. /** @internal */
  38700. void resized();
  38701. private:
  38702. bool escapeKeyTriggersCloseButton;
  38703. DialogWindow (const DialogWindow&);
  38704. const DialogWindow& operator= (const DialogWindow&);
  38705. };
  38706. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  38707. /********* End of inlined file: juce_DialogWindow.h *********/
  38708. #endif
  38709. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38710. #endif
  38711. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  38712. #endif
  38713. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38714. /********* Start of inlined file: juce_SplashScreen.h *********/
  38715. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  38716. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  38717. /** A component for showing a splash screen while your app starts up.
  38718. This will automatically position itself, and delete itself when the app has
  38719. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  38720. this).
  38721. To use it, just create one of these in your JUCEApplication::initialise() method,
  38722. call its show() method and let the object delete itself later.
  38723. E.g. @code
  38724. void MyApp::initialise (const String& commandLine)
  38725. {
  38726. SplashScreen* splash = new SplashScreen();
  38727. splash->show (T("welcome to my app"),
  38728. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  38729. 4000, false);
  38730. .. no need to delete the splash screen - it'll do that itself.
  38731. }
  38732. @endcode
  38733. */
  38734. class JUCE_API SplashScreen : public Component,
  38735. public Timer,
  38736. private DeletedAtShutdown
  38737. {
  38738. public:
  38739. /** Creates a SplashScreen object.
  38740. After creating one of these (or your subclass of it), call one of the show()
  38741. methods to display it.
  38742. */
  38743. SplashScreen();
  38744. /** Destructor. */
  38745. ~SplashScreen();
  38746. /** Creates a SplashScreen object that will display an image.
  38747. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38748. screen. This method will also dispatch any pending messages to make sure that when
  38749. it returns, the splash screen has been completely drawn, and your initialisation
  38750. code can carry on.
  38751. @param title the name to give the component
  38752. @param backgroundImage an image to draw on the component. The component's size
  38753. will be set to the size of this image, and if the image is
  38754. semi-transparent, the component will be made semi-transparent
  38755. too. This image will be deleted (or released from the ImageCache
  38756. if that's how it was created) by the splash screen object when
  38757. it is itself deleted.
  38758. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38759. should stay visible for. If the initialisation takes longer than
  38760. this time, the splash screen will wait for it to finish before
  38761. disappearing, but if initialisation is very quick, this lets
  38762. you make sure that people get a good look at your splash.
  38763. @param useDropShadow if true, the window will have a drop shadow
  38764. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38765. the mouse (anywhere)
  38766. */
  38767. void show (const String& title,
  38768. Image* const backgroundImage,
  38769. const int minimumTimeToDisplayFor,
  38770. const bool useDropShadow,
  38771. const bool removeOnMouseClick = true);
  38772. /** Creates a SplashScreen object with a specified size.
  38773. For a custom splash screen, you can use this method to display it at a certain size
  38774. and then override the paint() method yourself to do whatever's necessary.
  38775. As soon as this is called, the SplashScreen will be displayed in the centre of the
  38776. screen. This method will also dispatch any pending messages to make sure that when
  38777. it returns, the splash screen has been completely drawn, and your initialisation
  38778. code can carry on.
  38779. @param title the name to give the component
  38780. @param width the width to use
  38781. @param height the height to use
  38782. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  38783. should stay visible for. If the initialisation takes longer than
  38784. this time, the splash screen will wait for it to finish before
  38785. disappearing, but if initialisation is very quick, this lets
  38786. you make sure that people get a good look at your splash.
  38787. @param useDropShadow if true, the window will have a drop shadow
  38788. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  38789. the mouse (anywhere)
  38790. */
  38791. void show (const String& title,
  38792. const int width,
  38793. const int height,
  38794. const int minimumTimeToDisplayFor,
  38795. const bool useDropShadow,
  38796. const bool removeOnMouseClick = true);
  38797. /** @internal */
  38798. void paint (Graphics& g);
  38799. /** @internal */
  38800. void timerCallback();
  38801. juce_UseDebuggingNewOperator
  38802. private:
  38803. Image* backgroundImage;
  38804. Time earliestTimeToDelete;
  38805. int originalClickCounter;
  38806. bool isImageInCache;
  38807. SplashScreen (const SplashScreen&);
  38808. const SplashScreen& operator= (const SplashScreen&);
  38809. };
  38810. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  38811. /********* End of inlined file: juce_SplashScreen.h *********/
  38812. #endif
  38813. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38814. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  38815. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38816. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38817. /**
  38818. A thread that automatically pops up a modal dialog box with a progress bar
  38819. and cancel button while it's busy running.
  38820. These are handy for performing some sort of task while giving the user feedback
  38821. about how long there is to go, etc.
  38822. E.g. @code
  38823. class MyTask : public ThreadWithProgressWindow
  38824. {
  38825. public:
  38826. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  38827. {
  38828. }
  38829. ~MyTask()
  38830. {
  38831. }
  38832. void run()
  38833. {
  38834. for (int i = 0; i < thingsToDo; ++i)
  38835. {
  38836. // must check this as often as possible, because this is
  38837. // how we know if the user's pressed 'cancel'
  38838. if (threadShouldExit())
  38839. break;
  38840. // this will update the progress bar on the dialog box
  38841. setProgress (i / (double) thingsToDo);
  38842. // ... do the business here...
  38843. }
  38844. }
  38845. };
  38846. void doTheTask()
  38847. {
  38848. MyTask m;
  38849. if (m.runThread())
  38850. {
  38851. // thread finished normally..
  38852. }
  38853. else
  38854. {
  38855. // user pressed the cancel button..
  38856. }
  38857. }
  38858. @endcode
  38859. @see Thread, AlertWindow
  38860. */
  38861. class JUCE_API ThreadWithProgressWindow : public Thread,
  38862. private Timer
  38863. {
  38864. public:
  38865. /** Creates the thread.
  38866. Initially, the dialog box won't be visible, it'll only appear when the
  38867. runThread() method is called.
  38868. @param windowTitle the title to go at the top of the dialog box
  38869. @param hasProgressBar whether the dialog box should have a progress bar (see
  38870. setProgress() )
  38871. @param hasCancelButton whether the dialog box should have a cancel button
  38872. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  38873. the thread to stop before killing it forcibly (see
  38874. Thread::stopThread() )
  38875. @param cancelButtonText the text that should be shown in the cancel button
  38876. (if it has one)
  38877. */
  38878. ThreadWithProgressWindow (const String& windowTitle,
  38879. const bool hasProgressBar,
  38880. const bool hasCancelButton,
  38881. const int timeOutMsWhenCancelling = 10000,
  38882. const String& cancelButtonText = JUCE_T("Cancel"));
  38883. /** Destructor. */
  38884. ~ThreadWithProgressWindow();
  38885. /** Starts the thread and waits for it to finish.
  38886. This will start the thread, make the dialog box appear, and wait until either
  38887. the thread finishes normally, or until the cancel button is pressed.
  38888. Before returning, the dialog box will be hidden.
  38889. @param threadPriority the priority to use when starting the thread - see
  38890. Thread::startThread() for values
  38891. @returns true if the thread finished normally; false if the user pressed cancel
  38892. */
  38893. bool runThread (const int threadPriority = 5);
  38894. /** The thread should call this periodically to update the position of the progress bar.
  38895. @param newProgress the progress, from 0.0 to 1.0
  38896. @see setStatusMessage
  38897. */
  38898. void setProgress (const double newProgress);
  38899. /** The thread can call this to change the message that's displayed in the dialog box.
  38900. */
  38901. void setStatusMessage (const String& newStatusMessage);
  38902. juce_UseDebuggingNewOperator
  38903. private:
  38904. void timerCallback();
  38905. double progress;
  38906. AlertWindow* alertWindow;
  38907. String message;
  38908. CriticalSection messageLock;
  38909. const int timeOutMsWhenCancelling;
  38910. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  38911. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  38912. };
  38913. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  38914. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  38915. #endif
  38916. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  38917. #endif
  38918. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  38919. #endif
  38920. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38921. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  38922. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38923. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38924. #if JUCE_WIN32 || DOXYGEN
  38925. /**
  38926. A Windows-specific class that can create and embed an ActiveX control inside
  38927. itself.
  38928. To use it, create one of these, put it in place and make sure it's visible in a
  38929. window, then use createControl() to instantiate an ActiveX control. The control
  38930. will then be moved and resized to follow the movements of this component.
  38931. Of course, since the control is a heavyweight window, it'll obliterate any
  38932. juce components that may overlap this component, but that's life.
  38933. */
  38934. class JUCE_API ActiveXControlComponent : public Component
  38935. {
  38936. public:
  38937. /** Create an initially-empty container. */
  38938. ActiveXControlComponent();
  38939. /** Destructor. */
  38940. ~ActiveXControlComponent();
  38941. /** Tries to create an ActiveX control and embed it in this peer.
  38942. The peer controlIID is a pointer to an IID structure - it's treated
  38943. as a void* because when including the Juce headers, you might not always
  38944. have included windows.h first, in which case IID wouldn't be defined.
  38945. e.g. @code
  38946. const IID myIID = __uuidof (QTControl);
  38947. myControlComp->createControl (&myIID);
  38948. @endcode
  38949. */
  38950. bool createControl (const void* controlIID);
  38951. /** Deletes the ActiveX control, if one has been created.
  38952. */
  38953. void deleteControl();
  38954. /** Returns true if a control is currently in use. */
  38955. bool isControlOpen() const throw() { return control != 0; }
  38956. /** Does a QueryInterface call on the embedded control object.
  38957. This allows you to cast the control to whatever type of COM object you need.
  38958. The iid parameter is a pointer to an IID structure - it's treated
  38959. as a void* because when including the Juce headers, you might not always
  38960. have included windows.h first, in which case IID wouldn't be defined, but
  38961. you should just pass a pointer to an IID.
  38962. e.g. @code
  38963. const IID iid = __uuidof (IOleWindow);
  38964. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  38965. if (oleWindow != 0)
  38966. {
  38967. HWND hwnd;
  38968. oleWindow->GetWindow (&hwnd);
  38969. ...
  38970. oleWindow->Release();
  38971. }
  38972. @endcode
  38973. */
  38974. void* queryInterface (const void* iid) const;
  38975. /** Set this to false to stop mouse events being allowed through to the control.
  38976. */
  38977. void setMouseEventsAllowed (const bool eventsCanReachControl);
  38978. /** Returns true if mouse events are allowed to get through to the control.
  38979. */
  38980. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  38981. /** @internal */
  38982. void paint (Graphics& g);
  38983. /** @internal */
  38984. void* originalWndProc;
  38985. juce_UseDebuggingNewOperator
  38986. private:
  38987. friend class ActiveXControlData;
  38988. void* control;
  38989. bool mouseEventsAllowed;
  38990. ActiveXControlComponent (const ActiveXControlComponent&);
  38991. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  38992. void setControlBounds (const Rectangle& bounds) const;
  38993. void setControlVisible (const bool b) const;
  38994. };
  38995. #endif
  38996. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  38997. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  38998. #endif
  38999. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39000. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39001. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39002. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39003. class MidiInputSelectorComponentListBox;
  39004. /**
  39005. A component containing controls to let the user change the audio settings of
  39006. an AudioDeviceManager object.
  39007. Very easy to use - just create one of these and show it to the user.
  39008. @see AudioDeviceManager
  39009. */
  39010. class JUCE_API AudioDeviceSelectorComponent : public Component,
  39011. public ComboBoxListener,
  39012. public ButtonListener,
  39013. public ChangeListener
  39014. {
  39015. public:
  39016. /** Creates the component.
  39017. If your app needs only output channels, you might ask for a maximum of 0 input
  39018. channels, and the component won't display any options for choosing the input
  39019. channels. And likewise if you're doing an input-only app.
  39020. @param deviceManager the device manager that this component should control
  39021. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  39022. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  39023. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  39024. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  39025. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  39026. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  39027. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  39028. treated as a set of separate mono channels.
  39029. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  39030. are shown, with an "advanced" button that shows the rest of them
  39031. */
  39032. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  39033. const int minAudioInputChannels,
  39034. const int maxAudioInputChannels,
  39035. const int minAudioOutputChannels,
  39036. const int maxAudioOutputChannels,
  39037. const bool showMidiInputOptions,
  39038. const bool showMidiOutputSelector,
  39039. const bool showChannelsAsStereoPairs,
  39040. const bool hideAdvancedOptionsWithButton);
  39041. /** Destructor */
  39042. ~AudioDeviceSelectorComponent();
  39043. /** @internal */
  39044. void resized();
  39045. /** @internal */
  39046. void comboBoxChanged (ComboBox*);
  39047. /** @internal */
  39048. void buttonClicked (Button*);
  39049. /** @internal */
  39050. void changeListenerCallback (void*);
  39051. juce_UseDebuggingNewOperator
  39052. private:
  39053. AudioDeviceManager& deviceManager;
  39054. ComboBox* deviceTypeDropDown;
  39055. Label* deviceTypeDropDownLabel;
  39056. Component* audioDeviceSettingsComp;
  39057. String audioDeviceSettingsCompType;
  39058. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  39059. const bool showChannelsAsStereoPairs;
  39060. const bool hideAdvancedOptionsWithButton;
  39061. MidiInputSelectorComponentListBox* midiInputsList;
  39062. Label* midiInputsLabel;
  39063. ComboBox* midiOutputSelector;
  39064. Label* midiOutputLabel;
  39065. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  39066. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  39067. };
  39068. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39069. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39070. #endif
  39071. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39072. /********* Start of inlined file: juce_BubbleComponent.h *********/
  39073. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39074. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39075. /**
  39076. A component for showing a message or other graphics inside a speech-bubble-shaped
  39077. outline, pointing at a location on the screen.
  39078. This is a base class that just draws and positions the bubble shape, but leaves
  39079. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  39080. that draws a text message.
  39081. To use it, create your subclass, then either add it to a parent component or
  39082. put it on the desktop with addToDesktop (0), use setPosition() to
  39083. resize and position it, then make it visible.
  39084. @see BubbleMessageComponent
  39085. */
  39086. class JUCE_API BubbleComponent : public Component
  39087. {
  39088. protected:
  39089. /** Creates a BubbleComponent.
  39090. Your subclass will need to implement the getContentSize() and paintContent()
  39091. methods to draw the bubble's contents.
  39092. */
  39093. BubbleComponent();
  39094. public:
  39095. /** Destructor. */
  39096. ~BubbleComponent();
  39097. /** A list of permitted placements for the bubble, relative to the co-ordinates
  39098. at which it should be pointing.
  39099. @see setAllowedPlacement
  39100. */
  39101. enum BubblePlacement
  39102. {
  39103. above = 1,
  39104. below = 2,
  39105. left = 4,
  39106. right = 8
  39107. };
  39108. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  39109. point at which it's pointing.
  39110. By default when setPosition() is called, the bubble will place itself either
  39111. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  39112. the values in BubblePlacement to restrict this choice.
  39113. E.g. if you only want your bubble to appear above or below the target area,
  39114. use setAllowedPlacement (above | below);
  39115. @see BubblePlacement
  39116. */
  39117. void setAllowedPlacement (const int newPlacement);
  39118. /** Moves and resizes the bubble to point at a given component.
  39119. This will resize the bubble to fit its content, then find a position for it
  39120. so that it's next to, but doesn't overlap the given component.
  39121. It'll put itself either above, below, or to the side of the component depending
  39122. on where there's the most space, honouring any restrictions that were set
  39123. with setAllowedPlacement().
  39124. */
  39125. void setPosition (Component* componentToPointTo);
  39126. /** Moves and resizes the bubble to point at a given point.
  39127. This will resize the bubble to fit its content, then position it
  39128. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  39129. are relative to either the bubble component's parent component if it has one, or
  39130. they are screen co-ordinates if not.
  39131. It'll put itself either above, below, or to the side of this point, depending
  39132. on where there's the most space, honouring any restrictions that were set
  39133. with setAllowedPlacement().
  39134. */
  39135. void setPosition (const int arrowTipX,
  39136. const int arrowTipY);
  39137. /** Moves and resizes the bubble to point at a given rectangle.
  39138. This will resize the bubble to fit its content, then find a position for it
  39139. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  39140. co-ordinates are relative to either the bubble component's parent component
  39141. if it has one, or they are screen co-ordinates if not.
  39142. It'll put itself either above, below, or to the side of the component depending
  39143. on where there's the most space, honouring any restrictions that were set
  39144. with setAllowedPlacement().
  39145. */
  39146. void setPosition (const Rectangle& rectangleToPointTo);
  39147. protected:
  39148. /** Subclasses should override this to return the size of the content they
  39149. want to draw inside the bubble.
  39150. */
  39151. virtual void getContentSize (int& width, int& height) = 0;
  39152. /** Subclasses should override this to draw their bubble's contents.
  39153. The graphics object's clip region and the dimensions passed in here are
  39154. set up to paint just the rectangle inside the bubble.
  39155. */
  39156. virtual void paintContent (Graphics& g, int width, int height) = 0;
  39157. public:
  39158. /** @internal */
  39159. void paint (Graphics& g);
  39160. juce_UseDebuggingNewOperator
  39161. private:
  39162. Rectangle content;
  39163. int side, allowablePlacements;
  39164. float arrowTipX, arrowTipY;
  39165. DropShadowEffect shadow;
  39166. BubbleComponent (const BubbleComponent&);
  39167. const BubbleComponent& operator= (const BubbleComponent&);
  39168. };
  39169. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39170. /********* End of inlined file: juce_BubbleComponent.h *********/
  39171. #endif
  39172. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39173. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  39174. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39175. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39176. /**
  39177. A speech-bubble component that displays a short message.
  39178. This can be used to show a message with the tail of the speech bubble
  39179. pointing to a particular component or location on the screen.
  39180. @see BubbleComponent
  39181. */
  39182. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  39183. private Timer
  39184. {
  39185. public:
  39186. /** Creates a bubble component.
  39187. After creating one a BubbleComponent, do the following:
  39188. - add it to an appropriate parent component, or put it on the
  39189. desktop with Component::addToDesktop (0).
  39190. - use the showAt() method to show a message.
  39191. - it will make itself invisible after it times-out (and can optionally
  39192. also delete itself), or you can reuse it somewhere else by calling
  39193. showAt() again.
  39194. */
  39195. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  39196. /** Destructor. */
  39197. ~BubbleMessageComponent();
  39198. /** Shows a message bubble at a particular position.
  39199. This shows the bubble with its stem pointing to the given location
  39200. (co-ordinates being relative to its parent component).
  39201. For details about exactly how it decides where to position itself, see
  39202. BubbleComponent::updatePosition().
  39203. @param x the x co-ordinate of end of the bubble's tail
  39204. @param y the y co-ordinate of end of the bubble's tail
  39205. @param message the text to display
  39206. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39207. from its parent compnent. If this is 0 or less, it
  39208. will stay there until manually removed.
  39209. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39210. mouse button is pressed (anywhere on the screen)
  39211. @param deleteSelfAfterUse if true, then the component will delete itself after
  39212. it becomes invisible
  39213. */
  39214. void showAt (int x, int y,
  39215. const String& message,
  39216. const int numMillisecondsBeforeRemoving,
  39217. const bool removeWhenMouseClicked = true,
  39218. const bool deleteSelfAfterUse = false);
  39219. /** Shows a message bubble next to a particular component.
  39220. This shows the bubble with its stem pointing at the given component.
  39221. For details about exactly how it decides where to position itself, see
  39222. BubbleComponent::updatePosition().
  39223. @param component the component that you want to point at
  39224. @param message the text to display
  39225. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39226. from its parent compnent. If this is 0 or less, it
  39227. will stay there until manually removed.
  39228. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39229. mouse button is pressed (anywhere on the screen)
  39230. @param deleteSelfAfterUse if true, then the component will delete itself after
  39231. it becomes invisible
  39232. */
  39233. void showAt (Component* const component,
  39234. const String& message,
  39235. const int numMillisecondsBeforeRemoving,
  39236. const bool removeWhenMouseClicked = true,
  39237. const bool deleteSelfAfterUse = false);
  39238. /** @internal */
  39239. void getContentSize (int& w, int& h);
  39240. /** @internal */
  39241. void paintContent (Graphics& g, int w, int h);
  39242. /** @internal */
  39243. void timerCallback();
  39244. juce_UseDebuggingNewOperator
  39245. private:
  39246. int fadeOutLength, mouseClickCounter;
  39247. TextLayout textLayout;
  39248. int64 expiryTime;
  39249. bool deleteAfterUse;
  39250. void init (const int numMillisecondsBeforeRemoving,
  39251. const bool removeWhenMouseClicked,
  39252. const bool deleteSelfAfterUse);
  39253. BubbleMessageComponent (const BubbleMessageComponent&);
  39254. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  39255. };
  39256. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39257. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  39258. #endif
  39259. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39260. /********* Start of inlined file: juce_ColourSelector.h *********/
  39261. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39262. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  39263. /**
  39264. A component that lets the user choose a colour.
  39265. This shows RGB sliders and a colourspace that the user can pick colours from.
  39266. This class is also a ChangeBroadcaster, so listeners can register to be told
  39267. when the colour changes.
  39268. */
  39269. class JUCE_API ColourSelector : public Component,
  39270. public ChangeBroadcaster,
  39271. protected SliderListener
  39272. {
  39273. public:
  39274. /** Options for the type of selector to show. These are passed into the constructor. */
  39275. enum ColourSelectorOptions
  39276. {
  39277. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  39278. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  39279. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  39280. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  39281. };
  39282. /** Creates a ColourSelector object.
  39283. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  39284. which of the selector's features should be visible.
  39285. The edgeGap value specifies the amount of space to leave around the edge.
  39286. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  39287. colourspace and hue selector components.
  39288. */
  39289. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  39290. const int edgeGap = 4,
  39291. const int gapAroundColourSpaceComponent = 7);
  39292. /** Destructor. */
  39293. ~ColourSelector();
  39294. /** Returns the colour that the user has currently selected.
  39295. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  39296. register to be told when the colour changes.
  39297. @see setCurrentColour
  39298. */
  39299. const Colour getCurrentColour() const;
  39300. /** Changes the colour that is currently being shown.
  39301. */
  39302. void setCurrentColour (const Colour& newColour);
  39303. /** Tells the selector how many preset colour swatches you want to have on the component.
  39304. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39305. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39306. their values.
  39307. */
  39308. virtual int getNumSwatches() const;
  39309. /** Called by the selector to find out the colour of one of the swatches.
  39310. Your subclass should return the colour of the swatch with the given index.
  39311. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39312. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39313. their values.
  39314. */
  39315. virtual const Colour getSwatchColour (const int index) const;
  39316. /** Called by the selector when the user puts a new colour into one of the swatches.
  39317. Your subclass should change the colour of the swatch with the given index.
  39318. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39319. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39320. their values.
  39321. */
  39322. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  39323. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39324. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39325. methods.
  39326. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39327. */
  39328. enum ColourIds
  39329. {
  39330. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  39331. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  39332. };
  39333. juce_UseDebuggingNewOperator
  39334. private:
  39335. friend class ColourSpaceView;
  39336. friend class HueSelectorComp;
  39337. Colour colour;
  39338. float h, s, v;
  39339. Slider* sliders[4];
  39340. Component* colourSpace;
  39341. Component* hueSelector;
  39342. VoidArray swatchComponents;
  39343. const int flags;
  39344. int topSpace, edgeGap;
  39345. void setHue (float newH);
  39346. void setSV (float newS, float newV);
  39347. void updateHSV();
  39348. void update();
  39349. void sliderValueChanged (Slider*);
  39350. void paint (Graphics& g);
  39351. void resized();
  39352. ColourSelector (const ColourSelector&);
  39353. const ColourSelector& operator= (const ColourSelector&);
  39354. // this constructor is here temporarily to prevent old code compiling, because the parameters
  39355. // have changed - if you get an error here, update your code to use the new constructor instead..
  39356. // (xxx - note to self: remember to remove this at some point in the future)
  39357. ColourSelector (const bool);
  39358. };
  39359. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  39360. /********* End of inlined file: juce_ColourSelector.h *********/
  39361. #endif
  39362. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  39363. #endif
  39364. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39365. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  39366. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39367. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39368. /**
  39369. A component that contains another component, and can magnify or shrink it.
  39370. This component will continually update its size so that it fits the zoomed
  39371. version of the content component that you put inside it, so don't try to
  39372. change the size of this component directly - instead change that of the
  39373. content component.
  39374. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  39375. to remap mouse events correctly. This means that the content component won't
  39376. appear to be a direct child of this component, and instead will think its
  39377. on the desktop.
  39378. */
  39379. class JUCE_API MagnifierComponent : public Component
  39380. {
  39381. public:
  39382. /** Creates a MagnifierComponent.
  39383. This component will continually update its size so that it fits the zoomed
  39384. version of the content component that you put inside it, so don't try to
  39385. change the size of this component directly - instead change that of the
  39386. content component.
  39387. @param contentComponent the component to add as the magnified one
  39388. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  39389. be deleted when this component is deleted. If false,
  39390. it's the caller's responsibility to delete it later.
  39391. */
  39392. MagnifierComponent (Component* const contentComponent,
  39393. const bool deleteContentCompWhenNoLongerNeeded);
  39394. /** Destructor. */
  39395. ~MagnifierComponent();
  39396. /** Returns the current content component. */
  39397. Component* getContentComponent() const throw() { return content; }
  39398. /** Changes the zoom level.
  39399. The scale factor must be greater than zero. Values less than 1 will shrink the
  39400. image; values greater than 1 will multiply its size by this amount.
  39401. When this is called, this component will change its size to fit the full extent
  39402. of the newly zoomed content.
  39403. */
  39404. void setScaleFactor (double newScaleFactor);
  39405. /** Returns the current zoom factor. */
  39406. double getScaleFactor() const throw() { return scaleFactor; }
  39407. /** Changes the quality setting used to rescale the graphics.
  39408. */
  39409. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  39410. juce_UseDebuggingNewOperator
  39411. /** @internal */
  39412. void childBoundsChanged (Component*);
  39413. private:
  39414. Component* content;
  39415. Component* holderComp;
  39416. double scaleFactor;
  39417. ComponentPeer* peer;
  39418. bool deleteContent;
  39419. Graphics::ResamplingQuality quality;
  39420. void paint (Graphics& g);
  39421. void mouseDown (const MouseEvent& e);
  39422. void mouseUp (const MouseEvent& e);
  39423. void mouseDrag (const MouseEvent& e);
  39424. void mouseMove (const MouseEvent& e);
  39425. void mouseEnter (const MouseEvent& e);
  39426. void mouseExit (const MouseEvent& e);
  39427. void mouseWheelMove (const MouseEvent& e, float, float);
  39428. int scaleInt (const int n) const throw();
  39429. MagnifierComponent (const MagnifierComponent&);
  39430. const MagnifierComponent& operator= (const MagnifierComponent&);
  39431. };
  39432. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39433. /********* End of inlined file: juce_MagnifierComponent.h *********/
  39434. #endif
  39435. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39436. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  39437. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39438. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39439. /**
  39440. A component that displays a piano keyboard, whose notes can be clicked on.
  39441. This component will mimic a physical midi keyboard, showing the current state of
  39442. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  39443. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  39444. Another feature is that the computer keyboard can also be used to play notes. By
  39445. default it maps the top two rows of a standard querty keyboard to the notes, but
  39446. these can be remapped if needed. It will only respond to keypresses when it has
  39447. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  39448. The component is also a ChangeBroadcaster, so if you want to be informed when the
  39449. keyboard is scrolled, you can register a ChangeListener for callbacks.
  39450. @see MidiKeyboardState
  39451. */
  39452. class JUCE_API MidiKeyboardComponent : public Component,
  39453. public MidiKeyboardStateListener,
  39454. public ChangeBroadcaster,
  39455. private Timer,
  39456. private AsyncUpdater
  39457. {
  39458. public:
  39459. /** The direction of the keyboard.
  39460. @see setOrientation
  39461. */
  39462. enum Orientation
  39463. {
  39464. horizontalKeyboard,
  39465. verticalKeyboardFacingLeft,
  39466. verticalKeyboardFacingRight,
  39467. };
  39468. /** Creates a MidiKeyboardComponent.
  39469. @param state the midi keyboard model that this component will represent
  39470. @param orientation whether the keyboard is horizonal or vertical
  39471. */
  39472. MidiKeyboardComponent (MidiKeyboardState& state,
  39473. const Orientation orientation);
  39474. /** Destructor. */
  39475. ~MidiKeyboardComponent();
  39476. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  39477. on the component.
  39478. Values are 0 to 1.0, where 1.0 is the heaviest.
  39479. @see setMidiChannel
  39480. */
  39481. void setVelocity (const float velocity);
  39482. /** Changes the midi channel number that will be used for events triggered by clicking
  39483. on the component.
  39484. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  39485. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  39486. Although this is the channel used for outgoing events, the component can display
  39487. incoming events from more than one channel - see setMidiChannelsToDisplay()
  39488. @see setVelocity
  39489. */
  39490. void setMidiChannel (const int midiChannelNumber);
  39491. /** Returns the midi channel that the keyboard is using for midi messages.
  39492. @see setMidiChannel
  39493. */
  39494. int getMidiChannel() const throw() { return midiChannel; }
  39495. /** Sets a mask to indicate which incoming midi channels should be represented by
  39496. key movements.
  39497. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  39498. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  39499. in this mask, the on-screen keys will also go down.
  39500. By default, this mask is set to 0xffff (all channels displayed).
  39501. @see setMidiChannel
  39502. */
  39503. void setMidiChannelsToDisplay (const int midiChannelMask);
  39504. /** Returns the current set of midi channels represented by the component.
  39505. This is the value that was set with setMidiChannelsToDisplay().
  39506. */
  39507. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  39508. /** Changes the width used to draw the white keys. */
  39509. void setKeyWidth (const float widthInPixels);
  39510. /** Returns the width that was set by setKeyWidth(). */
  39511. float getKeyWidth() const throw() { return keyWidth; }
  39512. /** Changes the keyboard's current direction. */
  39513. void setOrientation (const Orientation newOrientation);
  39514. /** Returns the keyboard's current direction. */
  39515. const Orientation getOrientation() const throw() { return orientation; }
  39516. /** Sets the range of midi notes that the keyboard will be limited to.
  39517. By default the range is 0 to 127 (inclusive), but you can limit this if you
  39518. only want a restricted set of the keys to be shown.
  39519. Note that the values here are inclusive and must be between 0 and 127.
  39520. */
  39521. void setAvailableRange (const int lowestNote,
  39522. const int highestNote);
  39523. /** Returns the first note in the available range.
  39524. @see setAvailableRange
  39525. */
  39526. int getRangeStart() const throw() { return rangeStart; }
  39527. /** Returns the last note in the available range.
  39528. @see setAvailableRange
  39529. */
  39530. int getRangeEnd() const throw() { return rangeEnd; }
  39531. /** If the keyboard extends beyond the size of the component, this will scroll
  39532. it to show the given key at the start.
  39533. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  39534. base class to send a callback to any ChangeListeners that have been registered.
  39535. */
  39536. void setLowestVisibleKey (int noteNumber);
  39537. /** Returns the number of the first key shown in the component.
  39538. @see setLowestVisibleKey
  39539. */
  39540. int getLowestVisibleKey() const throw() { return firstKey; }
  39541. /** Returns the length of the black notes.
  39542. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  39543. */
  39544. int getBlackNoteLength() const throw() { return blackNoteLength; }
  39545. /** If set to true, then scroll buttons will appear at either end of the keyboard
  39546. if there are too many notes to fit them all in the component at once.
  39547. */
  39548. void setScrollButtonsVisible (const bool canScroll);
  39549. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39550. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39551. methods.
  39552. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39553. */
  39554. enum ColourIds
  39555. {
  39556. whiteNoteColourId = 0x1005000,
  39557. blackNoteColourId = 0x1005001,
  39558. keySeparatorLineColourId = 0x1005002,
  39559. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  39560. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  39561. textLabelColourId = 0x1005005,
  39562. upDownButtonBackgroundColourId = 0x1005006,
  39563. upDownButtonArrowColourId = 0x1005007
  39564. };
  39565. /** Returns the position within the component of the left-hand edge of a key.
  39566. Depending on the keyboard's orientation, this may be a horizontal or vertical
  39567. distance, in either direction.
  39568. */
  39569. int getKeyStartPosition (const int midiNoteNumber) const;
  39570. /** Deletes all key-mappings.
  39571. @see setKeyPressForNote
  39572. */
  39573. void clearKeyMappings();
  39574. /** Maps a key-press to a given note.
  39575. @param key the key that should trigger the note
  39576. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  39577. be. The actual midi note that gets played will be
  39578. this value + (12 * the current base octave). To change
  39579. the base octave, see setKeyPressBaseOctave()
  39580. */
  39581. void setKeyPressForNote (const KeyPress& key,
  39582. const int midiNoteOffsetFromC);
  39583. /** Removes any key-mappings for a given note.
  39584. For a description of what the note number means, see setKeyPressForNote().
  39585. */
  39586. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  39587. /** Changes the base note above which key-press-triggered notes are played.
  39588. The set of key-mappings that trigger notes can be moved up and down to cover
  39589. the entire scale using this method.
  39590. The value passed in is an octave number between 0 and 10 (inclusive), and
  39591. indicates which C is the base note to which the key-mapped notes are
  39592. relative.
  39593. */
  39594. void setKeyPressBaseOctave (const int newOctaveNumber);
  39595. /** This sets the octave number which is shown as the octave number for middle C.
  39596. This affects only the default implementation of getWhiteNoteText(), which
  39597. passes this octave number to MidiMessage::getMidiNoteName() in order to
  39598. get the note text. See MidiMessage::getMidiNoteName() for more info about
  39599. the parameter.
  39600. By default this value is set to 3.
  39601. @see getOctaveForMiddleC
  39602. */
  39603. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  39604. /** This returns the value set by setOctaveForMiddleC().
  39605. @see setOctaveForMiddleC
  39606. */
  39607. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  39608. /** @internal */
  39609. void paint (Graphics& g);
  39610. /** @internal */
  39611. void resized();
  39612. /** @internal */
  39613. void mouseMove (const MouseEvent& e);
  39614. /** @internal */
  39615. void mouseDrag (const MouseEvent& e);
  39616. /** @internal */
  39617. void mouseDown (const MouseEvent& e);
  39618. /** @internal */
  39619. void mouseUp (const MouseEvent& e);
  39620. /** @internal */
  39621. void mouseEnter (const MouseEvent& e);
  39622. /** @internal */
  39623. void mouseExit (const MouseEvent& e);
  39624. /** @internal */
  39625. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39626. /** @internal */
  39627. void timerCallback();
  39628. /** @internal */
  39629. bool keyStateChanged (const bool isKeyDown);
  39630. /** @internal */
  39631. void focusLost (FocusChangeType cause);
  39632. /** @internal */
  39633. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  39634. /** @internal */
  39635. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  39636. /** @internal */
  39637. void handleAsyncUpdate();
  39638. /** @internal */
  39639. void colourChanged();
  39640. juce_UseDebuggingNewOperator
  39641. protected:
  39642. friend class MidiKeyboardUpDownButton;
  39643. /** Draws a white note in the given rectangle.
  39644. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39645. currently pressed down.
  39646. When doing this, be sure to note the keyboard's orientation.
  39647. */
  39648. virtual void drawWhiteNote (int midiNoteNumber,
  39649. Graphics& g,
  39650. int x, int y, int w, int h,
  39651. bool isDown, bool isOver,
  39652. const Colour& lineColour,
  39653. const Colour& textColour);
  39654. /** Draws a black note in the given rectangle.
  39655. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39656. currently pressed down.
  39657. When doing this, be sure to note the keyboard's orientation.
  39658. */
  39659. virtual void drawBlackNote (int midiNoteNumber,
  39660. Graphics& g,
  39661. int x, int y, int w, int h,
  39662. bool isDown, bool isOver,
  39663. const Colour& noteFillColour);
  39664. /** Allows text to be drawn on the white notes.
  39665. By default this is used to label the C in each octave, but could be used for other things.
  39666. @see setOctaveForMiddleC
  39667. */
  39668. virtual const String getWhiteNoteText (const int midiNoteNumber);
  39669. /** Draws the up and down buttons that change the base note. */
  39670. virtual void drawUpDownButton (Graphics& g, int w, int h,
  39671. const bool isMouseOver,
  39672. const bool isButtonPressed,
  39673. const bool movesOctavesUp);
  39674. /** Callback when the mouse is clicked on a key.
  39675. You could use this to do things like handle right-clicks on keys, etc.
  39676. Return true if you want the click to trigger the note, or false if you
  39677. want to handle it yourself and not have the note played.
  39678. @see mouseDraggedToKey
  39679. */
  39680. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  39681. /** Callback when the mouse is dragged from one key onto another.
  39682. @see mouseDownOnKey
  39683. */
  39684. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  39685. /** Calculates the positon of a given midi-note.
  39686. This can be overridden to create layouts with custom key-widths.
  39687. @param midiNoteNumber the note to find
  39688. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  39689. @param x the x position of the left-hand edge of the key (this method
  39690. always works in terms of a horizontal keyboard)
  39691. @param w the width of the key
  39692. */
  39693. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  39694. int& x, int& w) const;
  39695. private:
  39696. MidiKeyboardState& state;
  39697. int xOffset, blackNoteLength;
  39698. float keyWidth;
  39699. Orientation orientation;
  39700. int midiChannel, midiInChannelMask;
  39701. float velocity;
  39702. int noteUnderMouse, mouseDownNote;
  39703. BitArray keysPressed, keysCurrentlyDrawnDown;
  39704. int rangeStart, rangeEnd, firstKey;
  39705. bool canScroll, mouseDragging;
  39706. Button* scrollDown;
  39707. Button* scrollUp;
  39708. Array <KeyPress> keyPresses;
  39709. Array <int> keyPressNotes;
  39710. int keyMappingOctave;
  39711. int octaveNumForMiddleC;
  39712. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  39713. int xyToNote (int x, int y);
  39714. int remappedXYToNote (int x, int y) const;
  39715. void resetAnyKeysInUse();
  39716. void updateNoteUnderMouse (int x, int y);
  39717. void repaintNote (const int midiNoteNumber);
  39718. MidiKeyboardComponent (const MidiKeyboardComponent&);
  39719. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  39720. };
  39721. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39722. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  39723. #endif
  39724. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39725. /********* Start of inlined file: juce_NSViewComponent.h *********/
  39726. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39727. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39728. #if ! DOXYGEN
  39729. class NSViewComponentInternal;
  39730. #endif
  39731. #if JUCE_MAC || DOXYGEN
  39732. /**
  39733. A Mac-specific class that can create and embed an NSView inside itself.
  39734. To use it, create one of these, put it in place and make sure it's visible in a
  39735. window, then use setView() to assign an NSView to it. The view will then be
  39736. moved and resized to follow the movements of this component.
  39737. Of course, since the view is a native object, it'll obliterate any
  39738. juce components that may overlap this component, but that's life.
  39739. */
  39740. class JUCE_API NSViewComponent : public Component
  39741. {
  39742. public:
  39743. /** Create an initially-empty container. */
  39744. NSViewComponent();
  39745. /** Destructor. */
  39746. ~NSViewComponent();
  39747. /** Assigns an NSView to this peer.
  39748. The view will be retained and released by this component for as long as
  39749. it is needed. To remove the current view, just call setView (0).
  39750. Note: a void* is used here to avoid including the cocoa headers as
  39751. part of the juce.h, but the method expects an NSView*.
  39752. */
  39753. void setView (void* nsView);
  39754. /** Returns the current NSView.
  39755. Note: a void* is returned here to avoid including the cocoa headers as
  39756. a requirement of juce.h, so you should just cast the object to an NSView*.
  39757. */
  39758. void* getView() const;
  39759. /** @internal */
  39760. void paint (Graphics& g);
  39761. juce_UseDebuggingNewOperator
  39762. private:
  39763. friend class NSViewComponentInternal;
  39764. NSViewComponentInternal* info;
  39765. NSViewComponent (const NSViewComponent&);
  39766. const NSViewComponent& operator= (const NSViewComponent&);
  39767. };
  39768. #endif
  39769. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  39770. /********* End of inlined file: juce_NSViewComponent.h *********/
  39771. #endif
  39772. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39773. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  39774. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39775. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39776. // this is used to disable OpenGL, and is defined in juce_Config.h
  39777. #if JUCE_OPENGL || DOXYGEN
  39778. class OpenGLComponentWatcher;
  39779. /**
  39780. Represents the various properties of an OpenGL bitmap format.
  39781. @see OpenGLComponent::setPixelFormat
  39782. */
  39783. struct OpenGLPixelFormat
  39784. {
  39785. /** Creates an OpenGLPixelFormat.
  39786. The default constructor just initialises the object as a simple 8-bit
  39787. RGBA format.
  39788. */
  39789. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  39790. const int alphaBits = 8,
  39791. const int depthBufferBits = 16,
  39792. const int stencilBufferBits = 0) throw();
  39793. int redBits; /**< The number of bits per pixel to use for the red channel. */
  39794. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  39795. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  39796. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  39797. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  39798. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  39799. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  39800. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  39801. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  39802. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  39803. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  39804. /** Returns a list of all the pixel formats that can be used in this system.
  39805. A reference component is needed in case there are multiple screens with different
  39806. capabilities - in which case, the one that the component is on will be used.
  39807. */
  39808. static void getAvailablePixelFormats (Component* component,
  39809. OwnedArray <OpenGLPixelFormat>& results);
  39810. bool operator== (const OpenGLPixelFormat&) const throw();
  39811. juce_UseDebuggingNewOperator
  39812. };
  39813. /**
  39814. A base class for types of OpenGL context.
  39815. An OpenGLComponent will supply its own context for drawing in its window.
  39816. */
  39817. class OpenGLContext
  39818. {
  39819. public:
  39820. /** Destructor. */
  39821. virtual ~OpenGLContext();
  39822. /** Makes this context the currently active one. */
  39823. virtual bool makeActive() const throw() = 0;
  39824. /** If this context is currently active, it is disactivated. */
  39825. virtual bool makeInactive() const throw() = 0;
  39826. /** Returns true if this context is currently active. */
  39827. virtual bool isActive() const throw() = 0;
  39828. /** Swaps the buffers (if the context can do this). */
  39829. virtual void swapBuffers() = 0;
  39830. /** Sets whether the context checks the vertical sync before swapping.
  39831. The value is the number of frames to allow between buffer-swapping. This is
  39832. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  39833. and greater numbers indicate that it should swap less often.
  39834. Returns true if it sets the value successfully.
  39835. */
  39836. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  39837. /** Returns the current swap-sync interval.
  39838. See setSwapInterval() for info about the value returned.
  39839. */
  39840. virtual int getSwapInterval() const = 0;
  39841. /** Returns the pixel format being used by this context. */
  39842. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  39843. /** For windowed contexts, this moves the context within the bounds of
  39844. its parent window.
  39845. */
  39846. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  39847. /** For windowed contexts, this triggers a repaint of the window.
  39848. (Not relevent on all platforms).
  39849. */
  39850. virtual void repaint() = 0;
  39851. /** Returns an OS-dependent handle to the raw GL context.
  39852. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  39853. a GLXContext.
  39854. */
  39855. virtual void* getRawContext() const throw() = 0;
  39856. /** This tries to create a context that can be used for drawing into the
  39857. area occupied by the specified component.
  39858. Note that you probably shouldn't use this method directly unless you know what
  39859. you're doing - the OpenGLComponent calls this and manages the context for you.
  39860. */
  39861. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  39862. const OpenGLPixelFormat& pixelFormat,
  39863. const OpenGLContext* const contextToShareWith);
  39864. /** Returns the context that's currently in active use by the calling thread.
  39865. Returns 0 if there isn't an active context.
  39866. */
  39867. static OpenGLContext* getCurrentContext();
  39868. juce_UseDebuggingNewOperator
  39869. protected:
  39870. OpenGLContext() throw();
  39871. };
  39872. /**
  39873. A component that contains an OpenGL canvas.
  39874. Override this, add it to whatever component you want to, and use the renderOpenGL()
  39875. method to draw its contents.
  39876. */
  39877. class JUCE_API OpenGLComponent : public Component
  39878. {
  39879. public:
  39880. /** Creates an OpenGLComponent.
  39881. */
  39882. OpenGLComponent();
  39883. /** Destructor. */
  39884. ~OpenGLComponent();
  39885. /** Changes the pixel format used by this component.
  39886. @see OpenGLPixelFormat::getAvailablePixelFormats()
  39887. */
  39888. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  39889. /** Returns the pixel format that this component is currently using. */
  39890. const OpenGLPixelFormat getPixelFormat() const;
  39891. /** Specifies an OpenGL context which should be shared with the one that this
  39892. component is using.
  39893. This is an OpenGL feature that lets two contexts share their texture data.
  39894. Note that this pointer is stored by the component, and when the component
  39895. needs to recreate its internal context for some reason, the same context
  39896. will be used again to share lists. So if you pass a context in here,
  39897. don't delete the context while this component is still using it! You can
  39898. call shareWith (0) to stop this component from sharing with it.
  39899. */
  39900. void shareWith (OpenGLContext* contextToShareListsWith);
  39901. /** Returns the context that this component is sharing with.
  39902. @see shareWith
  39903. */
  39904. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  39905. /** Flips the openGL buffers over. */
  39906. void swapBuffers();
  39907. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  39908. When this is called, makeCurrentContextActive() will already have been called
  39909. for you, so you just need to draw.
  39910. */
  39911. virtual void renderOpenGL() = 0;
  39912. /** This method is called when the component creates a new OpenGL context.
  39913. A new context may be created when the component is first used, or when it
  39914. is moved to a different window, or when the window is hidden and re-shown,
  39915. etc.
  39916. You can use this callback as an opportunity to set up things like textures
  39917. that your context needs.
  39918. New contexts are created on-demand by the makeCurrentContextActive() method - so
  39919. if the context is deleted, e.g. by changing the pixel format or window, no context
  39920. will be created until the next call to makeCurrentContextActive(), which will
  39921. synchronously create one and call this method. This means that if you're using
  39922. a non-GUI thread for rendering, you can make sure this method is be called by
  39923. your renderer thread.
  39924. When this callback happens, the context will already have been made current
  39925. using the makeCurrentContextActive() method, so there's no need to call it
  39926. again in your code.
  39927. */
  39928. virtual void newOpenGLContextCreated() = 0;
  39929. /** Returns the context that will draw into this component.
  39930. This may return 0 if the component is currently invisible or hasn't currently
  39931. got a context. The context object can be deleted and a new one created during
  39932. the lifetime of this component, and there may be times when it doesn't have one.
  39933. @see newOpenGLContextCreated()
  39934. */
  39935. OpenGLContext* getCurrentContext() const throw() { return context; }
  39936. /** Makes this component the current openGL context.
  39937. You might want to use this in things like your resize() method, before calling
  39938. GL commands.
  39939. If this returns false, then the context isn't active, so you should avoid
  39940. making any calls.
  39941. This call may actually create a context if one isn't currently initialised. If
  39942. it does this, it will also synchronously call the newOpenGLContextCreated()
  39943. method to let you initialise it as necessary.
  39944. @see OpenGLContext::makeActive
  39945. */
  39946. bool makeCurrentContextActive();
  39947. /** Stops the current component being the active OpenGL context.
  39948. This is the opposite of makeCurrentContextActive()
  39949. @see OpenGLContext::makeInactive
  39950. */
  39951. void makeCurrentContextInactive();
  39952. /** Returns true if this component is the active openGL context for the
  39953. current thread.
  39954. @see OpenGLContext::isActive
  39955. */
  39956. bool isActiveContext() const throw();
  39957. /** Calls the rendering callback, and swaps the buffers afterwards.
  39958. This is called automatically by paint() when the component needs to be rendered.
  39959. It can be overridden if you need to decouple the rendering from the paint callback
  39960. and render with a custom thread.
  39961. Returns true if the operation succeeded.
  39962. */
  39963. virtual bool renderAndSwapBuffers();
  39964. /** This returns a critical section that can be used to lock the current context.
  39965. Because the context that is used by this component can change, e.g. when the
  39966. component is shown or hidden, then if you're rendering to it on a background
  39967. thread, this allows you to lock the context for the duration of your rendering
  39968. routine.
  39969. */
  39970. CriticalSection& getContextLock() throw() { return contextLock; }
  39971. /** @internal */
  39972. void paint (Graphics& g);
  39973. /** Returns the native handle of an embedded heavyweight window, if there is one.
  39974. E.g. On windows, this will return the HWND of the sub-window containing
  39975. the opengl context, on the mac it'll be the NSOpenGLView.
  39976. */
  39977. void* getNativeWindowHandle() const;
  39978. juce_UseDebuggingNewOperator
  39979. private:
  39980. friend class OpenGLComponentWatcher;
  39981. OpenGLComponentWatcher* componentWatcher;
  39982. OpenGLContext* context;
  39983. OpenGLContext* contextToShareListsWith;
  39984. CriticalSection contextLock;
  39985. OpenGLPixelFormat preferredPixelFormat;
  39986. bool needToUpdateViewport;
  39987. void deleteContext();
  39988. void updateContextPosition();
  39989. void internalRepaint (int x, int y, int w, int h);
  39990. OpenGLComponent (const OpenGLComponent&);
  39991. const OpenGLComponent& operator= (const OpenGLComponent&);
  39992. };
  39993. #endif
  39994. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  39995. /********* End of inlined file: juce_OpenGLComponent.h *********/
  39996. #endif
  39997. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  39998. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  39999. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40000. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40001. /**
  40002. A component with a set of buttons at the top for changing between pages of
  40003. preferences.
  40004. This is just a handy way of writing a Mac-style preferences panel where you
  40005. have a row of buttons along the top for the different preference categories,
  40006. each button having an icon above its name. Clicking these will show an
  40007. appropriate prefs page below it.
  40008. You can either put one of these inside your own component, or just use the
  40009. showInDialogBox() method to show it in a window and run it modally.
  40010. To use it, just add a set of named pages with the addSettingsPage() method,
  40011. and implement the createComponentForPage() method to create suitable components
  40012. for each of these pages.
  40013. */
  40014. class JUCE_API PreferencesPanel : public Component,
  40015. private ButtonListener
  40016. {
  40017. public:
  40018. /** Creates an empty panel.
  40019. Use addSettingsPage() to add some pages to it in your constructor.
  40020. */
  40021. PreferencesPanel();
  40022. /** Destructor. */
  40023. ~PreferencesPanel();
  40024. /** Creates a page using a set of drawables to define the page's icon.
  40025. Note that the other version of this method is much easier if you're using
  40026. an image instead of a custom drawable.
  40027. @param pageTitle the name of this preferences page - you'll need to
  40028. make sure your createComponentForPage() method creates
  40029. a suitable component when it is passed this name
  40030. @param normalIcon the drawable to display in the page's button normally
  40031. @param overIcon the drawable to display in the page's button when the mouse is over
  40032. @param downIcon the drawable to display in the page's button when the button is down
  40033. @see DrawableButton
  40034. */
  40035. void addSettingsPage (const String& pageTitle,
  40036. const Drawable* normalIcon,
  40037. const Drawable* overIcon,
  40038. const Drawable* downIcon);
  40039. /** Creates a page using a set of drawables to define the page's icon.
  40040. The other version of this method gives you more control over the icon, but this
  40041. one is much easier if you're just loading it from a file.
  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 imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  40046. For this to look good, you'll probably want to use a nice
  40047. transparent png file.
  40048. @param imageDataSize the size of the image data, in bytes
  40049. */
  40050. void addSettingsPage (const String& pageTitle,
  40051. const char* imageData,
  40052. const int imageDataSize);
  40053. /** Utility method to display this panel in a DialogWindow.
  40054. Calling this will create a DialogWindow containing this panel with the
  40055. given size and title, and will run it modally, returning when the user
  40056. closes the dialog box.
  40057. */
  40058. void showInDialogBox (const String& dialogtitle,
  40059. int dialogWidth,
  40060. int dialogHeight,
  40061. const Colour& backgroundColour = Colours::white);
  40062. /** Subclasses must override this to return a component for each preferences page.
  40063. The subclass should return a pointer to a new component representing the named
  40064. page, which the panel will then display.
  40065. The panel will delete the component later when the user goes to another page
  40066. or deletes the panel.
  40067. */
  40068. virtual Component* createComponentForPage (const String& pageName) = 0;
  40069. /** Changes the current page being displayed. */
  40070. void setCurrentPage (const String& pageName);
  40071. /** @internal */
  40072. void resized();
  40073. /** @internal */
  40074. void paint (Graphics& g);
  40075. /** @internal */
  40076. void buttonClicked (Button* button);
  40077. juce_UseDebuggingNewOperator
  40078. private:
  40079. String currentPageName;
  40080. Component* currentPage;
  40081. int buttonSize;
  40082. PreferencesPanel (const PreferencesPanel&);
  40083. const PreferencesPanel& operator= (const PreferencesPanel&);
  40084. };
  40085. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40086. /********* End of inlined file: juce_PreferencesPanel.h *********/
  40087. #endif
  40088. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40089. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  40090. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40091. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40092. // this is used to disable QuickTime, and is defined in juce_Config.h
  40093. #if JUCE_QUICKTIME || DOXYGEN
  40094. #if JUCE_WIN32
  40095. typedef ActiveXControlComponent QTCompBaseClass;
  40096. #else
  40097. typedef NSViewComponent QTCompBaseClass;
  40098. #endif
  40099. /**
  40100. A window that can play back a QuickTime movie.
  40101. */
  40102. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  40103. {
  40104. public:
  40105. /** Creates a QuickTimeMovieComponent, initially blank.
  40106. Use the loadMovie() method to load a movie once you've added the
  40107. component to a window, (or put it on the desktop as a heavyweight window).
  40108. Loading a movie when the component isn't visible can cause problems, as
  40109. QuickTime needs a window handle to initialise properly.
  40110. */
  40111. QuickTimeMovieComponent();
  40112. /** Destructor. */
  40113. ~QuickTimeMovieComponent();
  40114. /** Returns true if QT is installed and working on this machine.
  40115. */
  40116. static bool isQuickTimeAvailable() throw();
  40117. /** Tries to load a QuickTime movie into the player.
  40118. It's best to call this function once you've added the component to a window,
  40119. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40120. component isn't visible can cause problems, because QuickTime needs a window
  40121. handle to do its stuff.
  40122. @param movieFile the .mov file to open
  40123. @param isControllerVisible whether to show a controller bar at the bottom
  40124. @returns true if the movie opens successfully
  40125. */
  40126. bool loadMovie (const File& movieFile,
  40127. const bool isControllerVisible);
  40128. bool loadMovie (InputStream* movieStream,
  40129. const bool isControllerVisible);
  40130. /** Closes the movie, if one is open. */
  40131. void closeMovie();
  40132. /** Returns the movie file that is currently open.
  40133. If there isn't one, this returns File::nonexistent
  40134. */
  40135. const File getCurrentMovieFile() const;
  40136. /** Returns true if there's currently a movie open. */
  40137. bool isMovieOpen() const;
  40138. /** Returns the length of the movie, in seconds. */
  40139. double getMovieDuration() const;
  40140. /** Returns the movie's natural size, in pixels.
  40141. You can use this to resize the component to show the movie at its preferred
  40142. scale.
  40143. If no movie is loaded, the size returned will be 0 x 0.
  40144. */
  40145. void getMovieNormalSize (int& width, int& height) const;
  40146. /** This will position the component within a given area, keeping its aspect
  40147. ratio correct according to the movie's normal size.
  40148. The component will be made as large as it can go within the space, and will
  40149. be aligned according to the justification value if this means there are gaps at
  40150. the top or sides.
  40151. */
  40152. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  40153. const RectanglePlacement& placement);
  40154. /** Starts the movie playing. */
  40155. void play();
  40156. /** Stops the movie playing. */
  40157. void stop();
  40158. /** Returns true if the movie is currently playing. */
  40159. bool isPlaying() const;
  40160. /** Moves the movie's position back to the start. */
  40161. void goToStart();
  40162. /** Sets the movie's position to a given time. */
  40163. void setPosition (const double seconds);
  40164. /** Returns the current play position of the movie. */
  40165. double getPosition() const;
  40166. /** Changes the movie playback rate.
  40167. A value of 1 is normal speed, greater values play it proportionately faster,
  40168. smaller values play it slower.
  40169. */
  40170. void setSpeed (const float newSpeed);
  40171. /** Changes the movie's playback volume.
  40172. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  40173. */
  40174. void setMovieVolume (const float newVolume);
  40175. /** Returns the movie's playback volume.
  40176. @returns the volume in the range 0 (silent) to 1.0 (full)
  40177. */
  40178. float getMovieVolume() const;
  40179. /** Tells the movie whether it should loop. */
  40180. void setLooping (const bool shouldLoop);
  40181. /** Returns true if the movie is currently looping.
  40182. @see setLooping
  40183. */
  40184. bool isLooping() const;
  40185. /** True if the native QuickTime controller bar is shown in the window.
  40186. @see loadMovie
  40187. */
  40188. bool isControllerVisible() const;
  40189. /** @internal */
  40190. void paint (Graphics& g);
  40191. juce_UseDebuggingNewOperator
  40192. private:
  40193. File movieFile;
  40194. bool movieLoaded, controllerVisible, looping;
  40195. #if JUCE_WIN32
  40196. /** @internal */
  40197. void parentHierarchyChanged();
  40198. /** @internal */
  40199. void visibilityChanged();
  40200. void createControlIfNeeded();
  40201. bool isControlCreated() const;
  40202. void* internal;
  40203. #else
  40204. void* movie;
  40205. #endif
  40206. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  40207. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  40208. };
  40209. #endif
  40210. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40211. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  40212. #endif
  40213. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40214. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  40215. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40216. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40217. #if JUCE_WIN32 || JUCE_LINUX
  40218. /**
  40219. On Windows only, this component sits in the taskbar tray as a small icon.
  40220. To use it, just create one of these components, but don't attempt to make it
  40221. visible, add it to a parent, or put it on the desktop.
  40222. You can then call setIconImage() to create an icon for it in the taskbar.
  40223. To change the icon's tooltip, you can use setIconTooltip().
  40224. To respond to mouse-events, you can override the normal mouseDown(),
  40225. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  40226. position will not be valid, you can use this to respond to clicks. Traditionally
  40227. you'd use a left-click to show your application's window, and a right-click
  40228. to show a pop-up menu.
  40229. */
  40230. class JUCE_API SystemTrayIconComponent : public Component
  40231. {
  40232. public:
  40233. SystemTrayIconComponent();
  40234. /** Destructor. */
  40235. ~SystemTrayIconComponent();
  40236. /** Changes the image shown in the taskbar.
  40237. */
  40238. void setIconImage (const Image& newImage);
  40239. /** Changes the tooltip that Windows shows above the icon. */
  40240. void setIconTooltip (const String& tooltip);
  40241. #if JUCE_LINUX
  40242. /** @internal */
  40243. void paint (Graphics& g);
  40244. #endif
  40245. juce_UseDebuggingNewOperator
  40246. private:
  40247. SystemTrayIconComponent (const SystemTrayIconComponent&);
  40248. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  40249. };
  40250. #endif
  40251. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40252. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  40253. #endif
  40254. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40255. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  40256. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40257. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40258. #if JUCE_WEB_BROWSER
  40259. class WebBrowserComponentInternal;
  40260. /**
  40261. A component that displays an embedded web browser.
  40262. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  40263. Windows, probably IE.
  40264. */
  40265. class JUCE_API WebBrowserComponent : public Component
  40266. {
  40267. public:
  40268. /** Creates a WebBrowserComponent.
  40269. Once it's created and visible, send the browser to a URL using goToURL().
  40270. */
  40271. WebBrowserComponent();
  40272. /** Destructor. */
  40273. ~WebBrowserComponent();
  40274. /** Sends the browser to a particular URL.
  40275. @param url the URL to go to.
  40276. @param headers an optional set of parameters to put in the HTTP header. If
  40277. you supply this, it should be a set of string in the form
  40278. "HeaderKey: HeaderValue"
  40279. @param postData an optional block of data that will be attached to the HTTP
  40280. POST request
  40281. */
  40282. void goToURL (const String& url,
  40283. const StringArray* headers = 0,
  40284. const MemoryBlock* postData = 0);
  40285. /** Stops the current page loading.
  40286. */
  40287. void stop();
  40288. /** Sends the browser back one page.
  40289. */
  40290. void goBack();
  40291. /** Sends the browser forward one page.
  40292. */
  40293. void goForward();
  40294. /** Refreshes the browser.
  40295. */
  40296. void refresh();
  40297. /** This callback is called when the browser is about to navigate
  40298. to a new location.
  40299. You can override this method to perform some action when the user
  40300. tries to go to a particular URL. To allow the operation to carry on,
  40301. return true, or return false to stop the navigation happening.
  40302. */
  40303. virtual bool pageAboutToLoad (const String& newURL);
  40304. /** @internal */
  40305. void paint (Graphics& g);
  40306. /** @internal */
  40307. void resized();
  40308. /** @internal */
  40309. void parentHierarchyChanged();
  40310. /** @internal */
  40311. void visibilityChanged();
  40312. juce_UseDebuggingNewOperator
  40313. private:
  40314. WebBrowserComponentInternal* browser;
  40315. bool blankPageShown;
  40316. String lastURL;
  40317. StringArray lastHeaders;
  40318. MemoryBlock lastPostData;
  40319. void reloadLastURL();
  40320. void checkWindowAssociation();
  40321. WebBrowserComponent (const WebBrowserComponent&);
  40322. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  40323. };
  40324. #endif
  40325. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40326. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  40327. #endif
  40328. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40329. /********* Start of inlined file: juce_LookAndFeel.h *********/
  40330. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40331. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  40332. class ToggleButton;
  40333. class TextButton;
  40334. class AlertWindow;
  40335. class TextLayout;
  40336. class ScrollBar;
  40337. class BubbleComponent;
  40338. class ComboBox;
  40339. class Button;
  40340. class FilenameComponent;
  40341. class DocumentWindow;
  40342. class ResizableWindow;
  40343. class GroupComponent;
  40344. class MenuBarComponent;
  40345. class DropShadower;
  40346. class GlyphArrangement;
  40347. class PropertyComponent;
  40348. class TableHeaderComponent;
  40349. class Toolbar;
  40350. class ToolbarItemComponent;
  40351. class PopupMenu;
  40352. class ProgressBar;
  40353. class FileBrowserComponent;
  40354. class DirectoryContentsDisplayComponent;
  40355. class FilePreviewComponent;
  40356. class ImageButton;
  40357. /**
  40358. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  40359. can be used to apply different 'skins' to the application.
  40360. */
  40361. class JUCE_API LookAndFeel
  40362. {
  40363. public:
  40364. /** Creates the default JUCE look and feel. */
  40365. LookAndFeel();
  40366. /** Destructor. */
  40367. virtual ~LookAndFeel();
  40368. /** Returns the current default look-and-feel for a component to use when it
  40369. hasn't got one explicitly set.
  40370. @see setDefaultLookAndFeel
  40371. */
  40372. static LookAndFeel& getDefaultLookAndFeel() throw();
  40373. /** Changes the default look-and-feel.
  40374. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  40375. set to 0, it will revert to using the default one. The
  40376. object passed-in must be deleted by the caller when
  40377. it's no longer needed.
  40378. @see getDefaultLookAndFeel
  40379. */
  40380. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  40381. /** Looks for a colour that has been registered with the given colour ID number.
  40382. If a colour has been set for this ID number using setColour(), then it is
  40383. returned. If none has been set, it will just return Colours::black.
  40384. The colour IDs for various purposes are stored as enums in the components that
  40385. they are relevent to - for an example, see Slider::ColourIds,
  40386. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  40387. If you're looking up a colour for use in drawing a component, it's usually
  40388. best not to call this directly, but to use the Component::findColour() method
  40389. instead. That will first check whether a suitable colour has been registered
  40390. directly with the component, and will fall-back on calling the component's
  40391. LookAndFeel's findColour() method if none is found.
  40392. @see setColour, Component::findColour, Component::setColour
  40393. */
  40394. const Colour findColour (const int colourId) const throw();
  40395. /** Registers a colour to be used for a particular purpose.
  40396. For more details, see the comments for findColour().
  40397. @see findColour, Component::findColour, Component::setColour
  40398. */
  40399. void setColour (const int colourId, const Colour& colour) throw();
  40400. /** Returns true if the specified colour ID has been explicitly set using the
  40401. setColour() method.
  40402. */
  40403. bool isColourSpecified (const int colourId) const throw();
  40404. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  40405. /** Allows you to change the default sans-serif font.
  40406. If you need to supply your own Typeface object for any of the default fonts, rather
  40407. than just supplying the name (e.g. if you want to use an embedded font), then
  40408. you should instead override getTypefaceForFont() to create and return the typeface.
  40409. */
  40410. void setDefaultSansSerifTypefaceName (const String& newName);
  40411. /** Draws the lozenge-shaped background for a standard button. */
  40412. virtual void drawButtonBackground (Graphics& g,
  40413. Button& button,
  40414. const Colour& backgroundColour,
  40415. bool isMouseOverButton,
  40416. bool isButtonDown);
  40417. virtual const Font getFontForTextButton (TextButton& button);
  40418. /** Draws the text for a TextButton. */
  40419. virtual void drawButtonText (Graphics& g,
  40420. TextButton& button,
  40421. bool isMouseOverButton,
  40422. bool isButtonDown);
  40423. /** Draws the contents of a standard ToggleButton. */
  40424. virtual void drawToggleButton (Graphics& g,
  40425. ToggleButton& button,
  40426. bool isMouseOverButton,
  40427. bool isButtonDown);
  40428. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  40429. virtual void drawTickBox (Graphics& g,
  40430. Component& component,
  40431. int x, int y, int w, int h,
  40432. const bool ticked,
  40433. const bool isEnabled,
  40434. const bool isMouseOverButton,
  40435. const bool isButtonDown);
  40436. /* AlertWindow handling..
  40437. */
  40438. virtual AlertWindow* createAlertWindow (const String& title,
  40439. const String& message,
  40440. const String& button1,
  40441. const String& button2,
  40442. const String& button3,
  40443. AlertWindow::AlertIconType iconType,
  40444. int numButtons,
  40445. Component* associatedComponent);
  40446. virtual void drawAlertBox (Graphics& g,
  40447. AlertWindow& alert,
  40448. const Rectangle& textArea,
  40449. TextLayout& textLayout);
  40450. virtual int getAlertBoxWindowFlags();
  40451. virtual int getAlertWindowButtonHeight();
  40452. virtual const Font getAlertWindowFont();
  40453. /** Draws a progress bar.
  40454. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  40455. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  40456. isn't known). It can use the current time as a basis for playing an animation.
  40457. (Used by progress bars in AlertWindow).
  40458. */
  40459. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40460. int width, int height,
  40461. double progress, const String& textToShow);
  40462. // Draws a small image that spins to indicate that something's happening..
  40463. // This method should use the current time to animate itself, so just keep
  40464. // repainting it every so often.
  40465. virtual void drawSpinningWaitAnimation (Graphics& g, int x, int y, int w, int h);
  40466. /** Draws one of the buttons on a scrollbar.
  40467. @param g the context to draw into
  40468. @param scrollbar the bar itself
  40469. @param width the width of the button
  40470. @param height the height of the button
  40471. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  40472. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40473. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  40474. @param isButtonDown whether the mouse button's held down
  40475. */
  40476. virtual void drawScrollbarButton (Graphics& g,
  40477. ScrollBar& scrollbar,
  40478. int width, int height,
  40479. int buttonDirection,
  40480. bool isScrollbarVertical,
  40481. bool isMouseOverButton,
  40482. bool isButtonDown);
  40483. /** Draws the thumb area of a scrollbar.
  40484. @param g the context to draw into
  40485. @param scrollbar the bar itself
  40486. @param x the x position of the left edge of the thumb area to draw in
  40487. @param y the y position of the top edge of the thumb area to draw in
  40488. @param width the width of the thumb area to draw in
  40489. @param height the height of the thumb area to draw in
  40490. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40491. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  40492. thumb, or its x position for horizontal bars
  40493. @param thumbSize for vertical bars, the height of the thumb, or its width for
  40494. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  40495. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  40496. currently dragging the thumb
  40497. @param isMouseDown whether the mouse is currently dragging the scrollbar
  40498. */
  40499. virtual void drawScrollbar (Graphics& g,
  40500. ScrollBar& scrollbar,
  40501. int x, int y,
  40502. int width, int height,
  40503. bool isScrollbarVertical,
  40504. int thumbStartPosition,
  40505. int thumbSize,
  40506. bool isMouseOver,
  40507. bool isMouseDown);
  40508. /** Returns the component effect to use for a scrollbar */
  40509. virtual ImageEffectFilter* getScrollbarEffect();
  40510. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  40511. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  40512. /** Returns the default thickness to use for a scrollbar. */
  40513. virtual int getDefaultScrollbarWidth();
  40514. /** Returns the length in pixels to use for a scrollbar button. */
  40515. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  40516. /** Returns a tick shape for use in yes/no boxes, etc. */
  40517. virtual const Path getTickShape (const float height);
  40518. /** Returns a cross shape for use in yes/no boxes, etc. */
  40519. virtual const Path getCrossShape (const float height);
  40520. /** Draws the + or - box in a treeview. */
  40521. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  40522. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  40523. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  40524. // these return an image from the ImageCache, so use ImageCache::release() to free it
  40525. virtual Image* getDefaultFolderImage();
  40526. virtual Image* getDefaultDocumentFileImage();
  40527. virtual void createFileChooserHeaderText (const String& title,
  40528. const String& instructions,
  40529. GlyphArrangement& destArrangement,
  40530. int width);
  40531. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  40532. const String& filename, Image* icon,
  40533. const String& fileSizeDescription,
  40534. const String& fileTimeDescription,
  40535. const bool isDirectory,
  40536. const bool isItemSelected,
  40537. const int itemIndex);
  40538. virtual Button* createFileBrowserGoUpButton();
  40539. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  40540. DirectoryContentsDisplayComponent* fileListComponent,
  40541. FilePreviewComponent* previewComp,
  40542. ComboBox* currentPathBox,
  40543. TextEditor* filenameBox,
  40544. Button* goUpButton);
  40545. virtual void drawBubble (Graphics& g,
  40546. float tipX, float tipY,
  40547. float boxX, float boxY, float boxW, float boxH);
  40548. /** Fills the background of a popup menu component. */
  40549. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40550. /** Draws one of the items in a popup menu. */
  40551. virtual void drawPopupMenuItem (Graphics& g,
  40552. int width, int height,
  40553. const bool isSeparator,
  40554. const bool isActive,
  40555. const bool isHighlighted,
  40556. const bool isTicked,
  40557. const bool hasSubMenu,
  40558. const String& text,
  40559. const String& shortcutKeyText,
  40560. Image* image,
  40561. const Colour* const textColour);
  40562. /** Returns the size and style of font to use in popup menus. */
  40563. virtual const Font getPopupMenuFont();
  40564. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40565. int width, int height,
  40566. bool isScrollUpArrow);
  40567. /** Finds the best size for an item in a popup menu. */
  40568. virtual void getIdealPopupMenuItemSize (const String& text,
  40569. const bool isSeparator,
  40570. int standardMenuItemHeight,
  40571. int& idealWidth,
  40572. int& idealHeight);
  40573. virtual int getMenuWindowFlags();
  40574. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40575. bool isMouseOverBar,
  40576. MenuBarComponent& menuBar);
  40577. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40578. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40579. virtual void drawMenuBarItem (Graphics& g,
  40580. int width, int height,
  40581. int itemIndex,
  40582. const String& itemText,
  40583. bool isMouseOverItem,
  40584. bool isMenuOpen,
  40585. bool isMouseOverBar,
  40586. MenuBarComponent& menuBar);
  40587. virtual void drawComboBox (Graphics& g, int width, int height,
  40588. const bool isButtonDown,
  40589. int buttonX, int buttonY,
  40590. int buttonW, int buttonH,
  40591. ComboBox& box);
  40592. virtual const Font getComboBoxFont (ComboBox& box);
  40593. virtual Label* createComboBoxTextBox (ComboBox& box);
  40594. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40595. virtual void drawLabel (Graphics& g, Label& label);
  40596. virtual void drawLinearSlider (Graphics& g,
  40597. int x, int y,
  40598. int width, int height,
  40599. float sliderPos,
  40600. float minSliderPos,
  40601. float maxSliderPos,
  40602. const Slider::SliderStyle style,
  40603. Slider& slider);
  40604. virtual void drawLinearSliderBackground (Graphics& g,
  40605. int x, int y,
  40606. int width, int height,
  40607. float sliderPos,
  40608. float minSliderPos,
  40609. float maxSliderPos,
  40610. const Slider::SliderStyle style,
  40611. Slider& slider);
  40612. virtual void drawLinearSliderThumb (Graphics& g,
  40613. int x, int y,
  40614. int width, int height,
  40615. float sliderPos,
  40616. float minSliderPos,
  40617. float maxSliderPos,
  40618. const Slider::SliderStyle style,
  40619. Slider& slider);
  40620. virtual int getSliderThumbRadius (Slider& slider);
  40621. virtual void drawRotarySlider (Graphics& g,
  40622. int x, int y,
  40623. int width, int height,
  40624. float sliderPosProportional,
  40625. const float rotaryStartAngle,
  40626. const float rotaryEndAngle,
  40627. Slider& slider);
  40628. virtual Button* createSliderButton (const bool isIncrement);
  40629. virtual Label* createSliderTextBox (Slider& slider);
  40630. virtual ImageEffectFilter* getSliderEffect();
  40631. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40632. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40633. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40634. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40635. ComboBox* filenameBox, Button* browseButton);
  40636. virtual void drawCornerResizer (Graphics& g,
  40637. int w, int h,
  40638. bool isMouseOver,
  40639. bool isMouseDragging);
  40640. virtual void drawResizableFrame (Graphics& g,
  40641. int w, int h,
  40642. const BorderSize& borders);
  40643. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  40644. const BorderSize& border,
  40645. ResizableWindow& window);
  40646. virtual void drawResizableWindowBorder (Graphics& g,
  40647. int w, int h,
  40648. const BorderSize& border,
  40649. ResizableWindow& window);
  40650. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40651. Graphics& g, int w, int h,
  40652. int titleSpaceX, int titleSpaceW,
  40653. const Image* icon,
  40654. bool drawTitleTextOnLeft);
  40655. virtual Button* createDocumentWindowButton (int buttonType);
  40656. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40657. int titleBarX, int titleBarY,
  40658. int titleBarW, int titleBarH,
  40659. Button* minimiseButton,
  40660. Button* maximiseButton,
  40661. Button* closeButton,
  40662. bool positionTitleBarButtonsOnLeft);
  40663. virtual int getDefaultMenuBarHeight();
  40664. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40665. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40666. int w, int h,
  40667. bool isVerticalBar,
  40668. bool isMouseOver,
  40669. bool isMouseDragging);
  40670. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40671. const String& text,
  40672. const Justification& position,
  40673. GroupComponent& group);
  40674. virtual void createTabButtonShape (Path& p,
  40675. int width, int height,
  40676. int tabIndex,
  40677. const String& text,
  40678. Button& button,
  40679. TabbedButtonBar::Orientation orientation,
  40680. const bool isMouseOver,
  40681. const bool isMouseDown,
  40682. const bool isFrontTab);
  40683. virtual void fillTabButtonShape (Graphics& g,
  40684. const Path& path,
  40685. const Colour& preferredBackgroundColour,
  40686. int tabIndex,
  40687. const String& text,
  40688. Button& button,
  40689. TabbedButtonBar::Orientation orientation,
  40690. const bool isMouseOver,
  40691. const bool isMouseDown,
  40692. const bool isFrontTab);
  40693. virtual void drawTabButtonText (Graphics& g,
  40694. int x, int y, int w, int h,
  40695. const Colour& preferredBackgroundColour,
  40696. int tabIndex,
  40697. const String& text,
  40698. Button& button,
  40699. TabbedButtonBar::Orientation orientation,
  40700. const bool isMouseOver,
  40701. const bool isMouseDown,
  40702. const bool isFrontTab);
  40703. virtual int getTabButtonOverlap (int tabDepth);
  40704. virtual int getTabButtonSpaceAroundImage();
  40705. virtual int getTabButtonBestWidth (int tabIndex,
  40706. const String& text,
  40707. int tabDepth,
  40708. Button& button);
  40709. virtual void drawTabButton (Graphics& g,
  40710. int w, int h,
  40711. const Colour& preferredColour,
  40712. int tabIndex,
  40713. const String& text,
  40714. Button& button,
  40715. TabbedButtonBar::Orientation orientation,
  40716. const bool isMouseOver,
  40717. const bool isMouseDown,
  40718. const bool isFrontTab);
  40719. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40720. int w, int h,
  40721. TabbedButtonBar& tabBar,
  40722. TabbedButtonBar::Orientation orientation);
  40723. virtual Button* createTabBarExtrasButton();
  40724. virtual void drawImageButton (Graphics& g, Image* image,
  40725. int imageX, int imageY, int imageW, int imageH,
  40726. const Colour& overlayColour,
  40727. float imageOpacity,
  40728. ImageButton& button);
  40729. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40730. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40731. int width, int height,
  40732. bool isMouseOver, bool isMouseDown,
  40733. int columnFlags);
  40734. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40735. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40736. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40737. bool isMouseOver, bool isMouseDown,
  40738. ToolbarItemComponent& component);
  40739. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40740. const String& text, ToolbarItemComponent& component);
  40741. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40742. bool isOpen, int width, int height);
  40743. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40744. PropertyComponent& component);
  40745. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40746. PropertyComponent& component);
  40747. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  40748. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40749. /**
  40750. */
  40751. virtual void playAlertSound();
  40752. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40753. static void drawGlassSphere (Graphics& g,
  40754. const float x, const float y,
  40755. const float diameter,
  40756. const Colour& colour,
  40757. const float outlineThickness) throw();
  40758. static void drawGlassPointer (Graphics& g,
  40759. const float x, const float y,
  40760. const float diameter,
  40761. const Colour& colour, const float outlineThickness,
  40762. const int direction) throw();
  40763. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40764. static void drawGlassLozenge (Graphics& g,
  40765. const float x, const float y,
  40766. const float width, const float height,
  40767. const Colour& colour,
  40768. const float outlineThickness,
  40769. const float cornerSize,
  40770. const bool flatOnLeft, const bool flatOnRight,
  40771. const bool flatOnTop, const bool flatOnBottom) throw();
  40772. juce_UseDebuggingNewOperator
  40773. protected:
  40774. // xxx the following methods are only here to cause a compiler error, because they've been
  40775. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  40776. // error if you try to build a subclass with the old versions.
  40777. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  40778. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  40779. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  40780. virtual void getTabButtonBestWidth (int, const String&, int) {}
  40781. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  40782. private:
  40783. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40784. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40785. Array <int> colourIds;
  40786. Array <Colour> colours;
  40787. // default typeface names
  40788. String defaultSans, defaultSerif, defaultFixed;
  40789. void drawShinyButtonShape (Graphics& g,
  40790. float x, float y, float w, float h, float maxCornerSize,
  40791. const Colour& baseColour,
  40792. const float strokeWidth,
  40793. const bool flatOnLeft,
  40794. const bool flatOnRight,
  40795. const bool flatOnTop,
  40796. const bool flatOnBottom) throw();
  40797. LookAndFeel (const LookAndFeel&);
  40798. const LookAndFeel& operator= (const LookAndFeel&);
  40799. };
  40800. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40801. /********* End of inlined file: juce_LookAndFeel.h *********/
  40802. #endif
  40803. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40804. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40805. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40806. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40807. /**
  40808. The original Juce look-and-feel.
  40809. */
  40810. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40811. {
  40812. public:
  40813. /** Creates the default JUCE look and feel. */
  40814. OldSchoolLookAndFeel();
  40815. /** Destructor. */
  40816. virtual ~OldSchoolLookAndFeel();
  40817. /** Draws the lozenge-shaped background for a standard button. */
  40818. virtual void drawButtonBackground (Graphics& g,
  40819. Button& button,
  40820. const Colour& backgroundColour,
  40821. bool isMouseOverButton,
  40822. bool isButtonDown);
  40823. /** Draws the contents of a standard ToggleButton. */
  40824. virtual void drawToggleButton (Graphics& g,
  40825. ToggleButton& button,
  40826. bool isMouseOverButton,
  40827. bool isButtonDown);
  40828. virtual void drawTickBox (Graphics& g,
  40829. Component& component,
  40830. int x, int y, int w, int h,
  40831. const bool ticked,
  40832. const bool isEnabled,
  40833. const bool isMouseOverButton,
  40834. const bool isButtonDown);
  40835. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40836. int width, int height,
  40837. double progress, const String& textToShow);
  40838. virtual void drawScrollbarButton (Graphics& g,
  40839. ScrollBar& scrollbar,
  40840. int width, int height,
  40841. int buttonDirection,
  40842. bool isScrollbarVertical,
  40843. bool isMouseOverButton,
  40844. bool isButtonDown);
  40845. virtual void drawScrollbar (Graphics& g,
  40846. ScrollBar& scrollbar,
  40847. int x, int y,
  40848. int width, int height,
  40849. bool isScrollbarVertical,
  40850. int thumbStartPosition,
  40851. int thumbSize,
  40852. bool isMouseOver,
  40853. bool isMouseDown);
  40854. virtual ImageEffectFilter* getScrollbarEffect();
  40855. virtual void drawTextEditorOutline (Graphics& g,
  40856. int width, int height,
  40857. TextEditor& textEditor);
  40858. /** Fills the background of a popup menu component. */
  40859. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40860. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40861. bool isMouseOverBar,
  40862. MenuBarComponent& menuBar);
  40863. virtual void drawComboBox (Graphics& g, int width, int height,
  40864. const bool isButtonDown,
  40865. int buttonX, int buttonY,
  40866. int buttonW, int buttonH,
  40867. ComboBox& box);
  40868. virtual const Font getComboBoxFont (ComboBox& box);
  40869. virtual void drawLinearSlider (Graphics& g,
  40870. int x, int y,
  40871. int width, int height,
  40872. float sliderPos,
  40873. float minSliderPos,
  40874. float maxSliderPos,
  40875. const Slider::SliderStyle style,
  40876. Slider& slider);
  40877. virtual int getSliderThumbRadius (Slider& slider);
  40878. virtual Button* createSliderButton (const bool isIncrement);
  40879. virtual ImageEffectFilter* getSliderEffect();
  40880. virtual void drawCornerResizer (Graphics& g,
  40881. int w, int h,
  40882. bool isMouseOver,
  40883. bool isMouseDragging);
  40884. virtual Button* createDocumentWindowButton (int buttonType);
  40885. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40886. int titleBarX, int titleBarY,
  40887. int titleBarW, int titleBarH,
  40888. Button* minimiseButton,
  40889. Button* maximiseButton,
  40890. Button* closeButton,
  40891. bool positionTitleBarButtonsOnLeft);
  40892. juce_UseDebuggingNewOperator
  40893. private:
  40894. DropShadowEffect scrollbarShadow;
  40895. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40896. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40897. };
  40898. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40899. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  40900. #endif
  40901. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  40902. #endif
  40903. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40904. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  40905. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40906. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  40907. /**
  40908. A class to take care of the logic involved with the loading/saving of some kind
  40909. of document.
  40910. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  40911. functions you need for documents that get saved to a file, so this class attempts
  40912. to abstract most of the boring stuff.
  40913. Your subclass should just implement all the pure virtual methods, and you can
  40914. then use the higher-level public methods to do the load/save dialogs, to warn the user
  40915. about overwriting files, etc.
  40916. The document object keeps track of whether it has changed since it was last saved or
  40917. loaded, so when you change something, call its changed() method. This will set a
  40918. flag so it knows it needs saving, and will also broadcast a change message using the
  40919. ChangeBroadcaster base class.
  40920. @see ChangeBroadcaster
  40921. */
  40922. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  40923. {
  40924. public:
  40925. /** Creates a FileBasedDocument.
  40926. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  40927. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  40928. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  40929. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  40930. */
  40931. FileBasedDocument (const String& fileExtension,
  40932. const String& fileWildCard,
  40933. const String& openFileDialogTitle,
  40934. const String& saveFileDialogTitle);
  40935. /** Destructor. */
  40936. virtual ~FileBasedDocument();
  40937. /** Returns true if the changed() method has been called since the file was
  40938. last saved or loaded.
  40939. @see resetChangedFlag, changed
  40940. */
  40941. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  40942. /** Called to indicate that the document has changed and needs saving.
  40943. This method will also trigger a change message to be sent out using the
  40944. ChangeBroadcaster base class.
  40945. After calling the method, the hasChangedSinceSaved() method will return true, until
  40946. it is reset either by saving to a file or using the resetChangedFlag() method.
  40947. @see hasChangedSinceSaved, resetChangedFlag
  40948. */
  40949. virtual void changed();
  40950. /** Sets the state of the 'changed' flag.
  40951. The 'changed' flag is set to true when the changed() method is called - use this method
  40952. to reset it or to set it without also broadcasting a change message.
  40953. @see changed, hasChangedSinceSaved
  40954. */
  40955. void setChangedFlag (const bool hasChanged);
  40956. /** Tries to open a file.
  40957. If the file opens correctly, the document's file (see the getFile() method) is set
  40958. to this new one; if it fails, the document's file is left unchanged, and optionally
  40959. a message box is shown telling the user there was an error.
  40960. @returns true if the new file loaded successfully
  40961. @see loadDocument, loadFromUserSpecifiedFile
  40962. */
  40963. bool loadFrom (const File& fileToLoadFrom,
  40964. const bool showMessageOnFailure);
  40965. /** Asks the user for a file and tries to load it.
  40966. This will pop up a dialog box using the title, file extension and
  40967. wildcard specified in the document's constructor, and asks the user
  40968. for a file. If they pick one, the loadFrom() method is used to
  40969. try to load it, optionally showing a message if it fails.
  40970. @returns true if a file was loaded; false if the user cancelled or if they
  40971. picked a file which failed to load correctly
  40972. @see loadFrom
  40973. */
  40974. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  40975. /** A set of possible outcomes of one of the save() methods
  40976. */
  40977. enum SaveResult
  40978. {
  40979. savedOk = 0, /**< indicates that a file was saved successfully. */
  40980. userCancelledSave, /**< indicates that the user aborted the save operation. */
  40981. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  40982. };
  40983. /** Tries to save the document to the last file it was saved or loaded from.
  40984. This will always try to write to the file, even if the document isn't flagged as
  40985. having changed.
  40986. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  40987. true, it will prompt the user to pick a file, as if
  40988. saveAsInteractive() was called.
  40989. @param showMessageOnFailure if true it will show a warning message when if the
  40990. save operation fails
  40991. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  40992. */
  40993. SaveResult save (const bool askUserForFileIfNotSpecified,
  40994. const bool showMessageOnFailure);
  40995. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  40996. it if they say yes.
  40997. If you've got a document open and want to close it (e.g. to quit the app), this is the
  40998. method to call.
  40999. If the document doesn't need saving it'll return the value savedOk so
  41000. you can go ahead and delete the document.
  41001. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  41002. return savedOk, so again, you can safely delete the document.
  41003. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  41004. close-document operation.
  41005. And if they click "save changes", it'll try to save and either return savedOk, or
  41006. failedToWriteToFile if there was a problem.
  41007. @see save, saveAs, saveAsInteractive
  41008. */
  41009. SaveResult saveIfNeededAndUserAgrees();
  41010. /** Tries to save the document to a specified file.
  41011. If this succeeds, it'll also change the document's internal file (as returned by
  41012. the getFile() method). If it fails, the file will be left unchanged.
  41013. @param newFile the file to try to write to
  41014. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  41015. the user first if they want to overwrite it
  41016. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  41017. use the saveAsInteractive() method to ask the user for a
  41018. filename
  41019. @param showMessageOnFailure if true and the write operation fails, it'll show
  41020. a message box to warn the user
  41021. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  41022. */
  41023. SaveResult saveAs (const File& newFile,
  41024. const bool warnAboutOverwritingExistingFiles,
  41025. const bool askUserForFileIfNotSpecified,
  41026. const bool showMessageOnFailure);
  41027. /** Prompts the user for a filename and tries to save to it.
  41028. This will pop up a dialog box using the title, file extension and
  41029. wildcard specified in the document's constructor, and asks the user
  41030. for a file. If they pick one, the saveAs() method is used to try to save
  41031. to this file.
  41032. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  41033. the user first if they want to overwrite it
  41034. @see saveIfNeededAndUserAgrees, save, saveAs
  41035. */
  41036. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  41037. /** Returns the file that this document was last successfully saved or loaded from.
  41038. When the document object is created, this will be set to File::nonexistent.
  41039. It is changed when one of the load or save methods is used, or when setFile()
  41040. is used to explicitly set it.
  41041. */
  41042. const File getFile() const throw() { return documentFile; }
  41043. /** Sets the file that this document thinks it was loaded from.
  41044. This won't actually load anything - it just changes the file stored internally.
  41045. @see getFile
  41046. */
  41047. void setFile (const File& newFile);
  41048. protected:
  41049. /** Overload this to return the title of the document.
  41050. This is used in message boxes, filenames and file choosers, so it should be
  41051. something sensible.
  41052. */
  41053. virtual const String getDocumentTitle() = 0;
  41054. /** This method should try to load your document from the given file.
  41055. If it fails, it should return an error message. If it succeeds, it should return
  41056. an empty string.
  41057. */
  41058. virtual const String loadDocument (const File& file) = 0;
  41059. /** This method should try to write your document to the given file.
  41060. If it fails, it should return an error message. If it succeeds, it should return
  41061. an empty string.
  41062. */
  41063. virtual const String saveDocument (const File& file) = 0;
  41064. /** This is used for dialog boxes to make them open at the last folder you
  41065. were using.
  41066. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  41067. the last document that was used - you might want to store this value
  41068. in a static variable, or even in your application's properties. It should
  41069. be a global setting rather than a property of this object.
  41070. This method works very well in conjunction with a RecentlyOpenedFilesList
  41071. object to manage your recent-files list.
  41072. As a default value, it's ok to return File::nonexistent, and the document
  41073. object will use a sensible one instead.
  41074. @see RecentlyOpenedFilesList
  41075. */
  41076. virtual const File getLastDocumentOpened() = 0;
  41077. /** This is used for dialog boxes to make them open at the last folder you
  41078. were using.
  41079. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  41080. the last document that was used - you might want to store this value
  41081. in a static variable, or even in your application's properties. It should
  41082. be a global setting rather than a property of this object.
  41083. This method works very well in conjunction with a RecentlyOpenedFilesList
  41084. object to manage your recent-files list.
  41085. @see RecentlyOpenedFilesList
  41086. */
  41087. virtual void setLastDocumentOpened (const File& file) = 0;
  41088. public:
  41089. juce_UseDebuggingNewOperator
  41090. private:
  41091. File documentFile;
  41092. bool changedSinceSave;
  41093. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  41094. FileBasedDocument (const FileBasedDocument&);
  41095. const FileBasedDocument& operator= (const FileBasedDocument&);
  41096. };
  41097. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  41098. /********* End of inlined file: juce_FileBasedDocument.h *********/
  41099. #endif
  41100. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  41101. #endif
  41102. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41103. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  41104. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41105. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41106. /**
  41107. Manages a set of files for use as a list of recently-opened documents.
  41108. This is a handy class for holding your list of recently-opened documents, with
  41109. helpful methods for things like purging any non-existent files, automatically
  41110. adding them to a menu, and making persistence easy.
  41111. @see File, FileBasedDocument
  41112. */
  41113. class JUCE_API RecentlyOpenedFilesList
  41114. {
  41115. public:
  41116. /** Creates an empty list.
  41117. */
  41118. RecentlyOpenedFilesList();
  41119. /** Destructor. */
  41120. ~RecentlyOpenedFilesList();
  41121. /** Sets a limit for the number of files that will be stored in the list.
  41122. When addFile() is called, then if there is no more space in the list, the
  41123. least-recently added file will be dropped.
  41124. @see getMaxNumberOfItems
  41125. */
  41126. void setMaxNumberOfItems (const int newMaxNumber);
  41127. /** Returns the number of items that this list will store.
  41128. @see setMaxNumberOfItems
  41129. */
  41130. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  41131. /** Returns the number of files in the list.
  41132. The most recently added file is always at index 0.
  41133. */
  41134. int getNumFiles() const;
  41135. /** Returns one of the files in the list.
  41136. The most recently added file is always at index 0.
  41137. */
  41138. const File getFile (const int index) const;
  41139. /** Returns an array of all the absolute pathnames in the list.
  41140. */
  41141. const StringArray& getAllFilenames() const throw() { return files; }
  41142. /** Clears all the files from the list. */
  41143. void clear();
  41144. /** Adds a file to the list.
  41145. The file will be added at index 0. If this file is already in the list, it will
  41146. be moved up to index 0, but a file can only appear once in the list.
  41147. If the list already contains the maximum number of items that is permitted, the
  41148. least-recently added file will be dropped from the end.
  41149. */
  41150. void addFile (const File& file);
  41151. /** Checks each of the files in the list, removing any that don't exist.
  41152. You might want to call this after reloading a list of files, or before putting them
  41153. on a menu.
  41154. */
  41155. void removeNonExistentFiles();
  41156. /** Adds entries to a menu, representing each of the files in the list.
  41157. This is handy for creating an "open recent file..." menu in your app. The
  41158. menu items are numbered consecutively starting with the baseItemId value,
  41159. and can either be added as complete pathnames, or just the last part of the
  41160. filename.
  41161. If dontAddNonExistentFiles is true, then each file will be checked and only those
  41162. that exist will be added.
  41163. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  41164. pointers to file objects. Any files that appear in this list will not be added to the
  41165. menu - the reason for this is that you might have a number of files already open, so
  41166. might not want these to be shown in the menu.
  41167. It returns the number of items that were added.
  41168. */
  41169. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  41170. const int baseItemId,
  41171. const bool showFullPaths,
  41172. const bool dontAddNonExistentFiles,
  41173. const File** filesToAvoid = 0);
  41174. /** Returns a string that encapsulates all the files in the list.
  41175. The string that is returned can later be passed into restoreFromString() in
  41176. order to recreate the list. This is handy for persisting your list, e.g. in
  41177. a PropertiesFile object.
  41178. @see restoreFromString
  41179. */
  41180. const String toString() const;
  41181. /** Restores the list from a previously stringified version of the list.
  41182. Pass in a stringified version created with toString() in order to persist/restore
  41183. your list.
  41184. @see toString
  41185. */
  41186. void restoreFromString (const String& stringifiedVersion);
  41187. juce_UseDebuggingNewOperator
  41188. private:
  41189. StringArray files;
  41190. int maxNumberOfItems;
  41191. };
  41192. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  41193. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  41194. #endif
  41195. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  41196. #endif
  41197. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41198. /********* Start of inlined file: juce_SystemClipboard.h *********/
  41199. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41200. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41201. /**
  41202. Handles reading/writing to the system's clipboard.
  41203. */
  41204. class JUCE_API SystemClipboard
  41205. {
  41206. public:
  41207. /** Copies a string of text onto the clipboard */
  41208. static void copyTextToClipboard (const String& text) throw();
  41209. /** Gets the current clipboard's contents.
  41210. Obviously this might have come from another app, so could contain
  41211. anything..
  41212. */
  41213. static const String getTextFromClipboard() throw();
  41214. };
  41215. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  41216. /********* End of inlined file: juce_SystemClipboard.h *********/
  41217. #endif
  41218. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  41219. #endif
  41220. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  41221. #endif
  41222. #endif
  41223. /********* End of inlined file: juce_app_includes.h *********/
  41224. #endif
  41225. #if JUCE_MSVC
  41226. #pragma warning (pop)
  41227. #pragma pack (pop)
  41228. #endif
  41229. #if JUCE_MAC
  41230. #pragma align=reset
  41231. #endif
  41232. END_JUCE_NAMESPACE
  41233. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  41234. #ifdef JUCE_NAMESPACE
  41235. // this will obviously save a lot of typing, but can be disabled by
  41236. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  41237. using namespace JUCE_NAMESPACE;
  41238. /* On the Mac, these symbols are defined in the Mac libraries, so
  41239. these macros make it easier to reference them without writing out
  41240. the namespace every time.
  41241. If you run into difficulties where these macros interfere with the contents
  41242. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  41243. the comments in that file for more information.
  41244. */
  41245. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  41246. #define Component JUCE_NAMESPACE::Component
  41247. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  41248. #define Point JUCE_NAMESPACE::Point
  41249. #define Button JUCE_NAMESPACE::Button
  41250. #endif
  41251. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  41252. it easier to use the juce version explicitly.
  41253. If you run into difficulties where this macro interferes with other 3rd party header
  41254. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  41255. file for more information.
  41256. */
  41257. #if JUCE_WIN32 && ! JUCE_DONT_DEFINE_MACROS
  41258. #define Rectangle JUCE_NAMESPACE::Rectangle
  41259. #endif
  41260. #endif
  41261. #endif
  41262. /* Easy autolinking to the right JUCE libraries under win32.
  41263. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  41264. including this header file.
  41265. */
  41266. #if JUCE_MSVC
  41267. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  41268. /** If you want your application to link to Juce as a DLL instead of
  41269. a static library (on win32), just define the JUCE_DLL macro before
  41270. including juce.h
  41271. */
  41272. #ifdef JUCE_DLL
  41273. #ifdef JUCE_DEBUG
  41274. #define AUTOLINKEDLIB "JUCE_debug.lib"
  41275. #else
  41276. #define AUTOLINKEDLIB "JUCE.lib"
  41277. #endif
  41278. #else
  41279. #ifdef JUCE_DEBUG
  41280. #ifdef _WIN64
  41281. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  41282. #else
  41283. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  41284. #endif
  41285. #else
  41286. #ifdef _WIN64
  41287. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  41288. #else
  41289. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  41290. #endif
  41291. #endif
  41292. #endif
  41293. #pragma comment(lib, AUTOLINKEDLIB)
  41294. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  41295. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  41296. #endif
  41297. // Auto-link the other win32 libs that are needed by library calls..
  41298. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  41299. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  41300. // Auto-links to various win32 libs that are needed by library calls..
  41301. #pragma comment(lib, "kernel32.lib")
  41302. #pragma comment(lib, "user32.lib")
  41303. #pragma comment(lib, "shell32.lib")
  41304. #pragma comment(lib, "gdi32.lib")
  41305. #pragma comment(lib, "vfw32.lib")
  41306. #pragma comment(lib, "comdlg32.lib")
  41307. #pragma comment(lib, "winmm.lib")
  41308. #pragma comment(lib, "wininet.lib")
  41309. #pragma comment(lib, "ole32.lib")
  41310. #pragma comment(lib, "advapi32.lib")
  41311. #pragma comment(lib, "ws2_32.lib")
  41312. #pragma comment(lib, "comsupp.lib")
  41313. #pragma comment(lib, "version.lib")
  41314. #if JUCE_OPENGL
  41315. #pragma comment(lib, "OpenGL32.Lib")
  41316. #pragma comment(lib, "GlU32.Lib")
  41317. #endif
  41318. #if JUCE_QUICKTIME
  41319. #pragma comment (lib, "QTMLClient.lib")
  41320. #endif
  41321. #if JUCE_USE_CAMERA
  41322. #pragma comment (lib, "Strmiids.lib")
  41323. #endif
  41324. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  41325. #endif
  41326. #endif
  41327. #endif
  41328. /*
  41329. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  41330. AppSubClass is the name of a class derived from JUCEApplication.
  41331. See the JUCEApplication class documentation (juce_Application.h) for more details.
  41332. */
  41333. #if defined (JUCE_GCC) || defined (__MWERKS__)
  41334. #define START_JUCE_APPLICATION(AppClass) \
  41335. int main (int argc, char* argv[]) \
  41336. { \
  41337. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  41338. }
  41339. #elif JUCE_WIN32
  41340. #ifdef _CONSOLE
  41341. #define START_JUCE_APPLICATION(AppClass) \
  41342. int main (int, char* argv[]) \
  41343. { \
  41344. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41345. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41346. }
  41347. #elif ! defined (_AFXDLL)
  41348. #ifdef _WINDOWS_
  41349. #define START_JUCE_APPLICATION(AppClass) \
  41350. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  41351. { \
  41352. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41353. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41354. }
  41355. #else
  41356. #define START_JUCE_APPLICATION(AppClass) \
  41357. int __stdcall WinMain (int, int, const char*, int) \
  41358. { \
  41359. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  41360. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  41361. }
  41362. #endif
  41363. #endif
  41364. #endif
  41365. #endif // __JUCE_JUCEHEADER__
  41366. /********* End of inlined file: juce.h *********/
  41367. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__