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.

56844 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_TargetPlatform.h *********/
  52. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  53. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  54. /* This file figures out which platform is being built, and defines some macros
  55. that the rest of the code can use for OS-specific compilation.
  56. Macros that will be set here are:
  57. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  58. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  59. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  60. - Either JUCE_INTEL or JUCE_PPC
  61. - Either JUCE_GCC or JUCE_MSVC
  62. */
  63. #if (defined (_WIN32) || defined (_WIN64))
  64. #define JUCE_WIN32 1
  65. #define JUCE_WINDOWS 1
  66. #elif defined (LINUX) || defined (__linux__)
  67. #define JUCE_LINUX 1
  68. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  69. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  70. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  71. #define JUCE_IPHONE 1
  72. #else
  73. #define JUCE_MAC 1
  74. #endif
  75. #else
  76. #error "Unknown platform!"
  77. #endif
  78. #if JUCE_WINDOWS
  79. #ifdef _MSC_VER
  80. #ifdef _WIN64
  81. #define JUCE_64BIT 1
  82. #else
  83. #define JUCE_32BIT 1
  84. #endif
  85. #endif
  86. #ifdef _DEBUG
  87. #define JUCE_DEBUG 1
  88. #endif
  89. /** If defined, this indicates that the processor is little-endian. */
  90. #define JUCE_LITTLE_ENDIAN 1
  91. #define JUCE_INTEL 1
  92. #endif
  93. #if JUCE_MAC
  94. #ifndef NDEBUG
  95. #define JUCE_DEBUG 1
  96. #endif
  97. #ifdef __LITTLE_ENDIAN__
  98. #define JUCE_LITTLE_ENDIAN 1
  99. #else
  100. #define JUCE_BIG_ENDIAN 1
  101. #endif
  102. #if defined (__ppc__) || defined (__ppc64__)
  103. #define JUCE_PPC 1
  104. #else
  105. #define JUCE_INTEL 1
  106. #endif
  107. #ifdef __LP64__
  108. #define JUCE_64BIT 1
  109. #else
  110. #define JUCE_32BIT 1
  111. #endif
  112. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  113. #error "Building for OSX 10.3 is no longer supported!"
  114. #endif
  115. #ifndef MAC_OS_X_VERSION_10_5
  116. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  117. #endif
  118. #endif
  119. #if JUCE_IPHONE
  120. #ifndef NDEBUG
  121. #define JUCE_DEBUG 1
  122. #endif
  123. #ifdef __LITTLE_ENDIAN__
  124. #define JUCE_LITTLE_ENDIAN 1
  125. #else
  126. #define JUCE_BIG_ENDIAN 1
  127. #endif
  128. #endif
  129. #if JUCE_LINUX
  130. #ifdef _DEBUG
  131. #define JUCE_DEBUG 1
  132. #endif
  133. // Allow override for big-endian Linux platforms
  134. #ifndef JUCE_BIG_ENDIAN
  135. #define JUCE_LITTLE_ENDIAN 1
  136. #endif
  137. #if defined (__LP64__) || defined (_LP64)
  138. #define JUCE_64BIT 1
  139. #else
  140. #define JUCE_32BIT 1
  141. #endif
  142. #define JUCE_INTEL 1
  143. #endif
  144. // Compiler type macros.
  145. #ifdef __GNUC__
  146. #define JUCE_GCC 1
  147. #elif defined (_MSC_VER)
  148. #define JUCE_MSVC 1
  149. #if _MSC_VER >= 1400
  150. #define JUCE_USE_INTRINSICS 1
  151. #endif
  152. #else
  153. #error unknown compiler
  154. #endif
  155. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  156. /********* End of inlined file: juce_TargetPlatform.h *********/
  157. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  158. /********* Start of inlined file: juce_Config.h *********/
  159. #ifndef __JUCE_CONFIG_JUCEHEADER__
  160. #define __JUCE_CONFIG_JUCEHEADER__
  161. /*
  162. This file contains macros that enable/disable various JUCE features.
  163. */
  164. /** The name of the namespace that all Juce classes and functions will be
  165. put inside. If this is not defined, no namespace will be used.
  166. */
  167. #ifndef JUCE_NAMESPACE
  168. #define JUCE_NAMESPACE juce
  169. #endif
  170. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  171. but if you define this value, you can override this can force it to be true or
  172. false.
  173. */
  174. #ifndef JUCE_FORCE_DEBUG
  175. //#define JUCE_FORCE_DEBUG 1
  176. #endif
  177. /** If this flag is enabled, the the jassert and jassertfalse macros will
  178. always use Logger::writeToLog() to write a message when an assertion happens.
  179. Enabling it will also leave this turned on in release builds. When it's disabled,
  180. however, the jassert and jassertfalse macros will not be compiled in a
  181. release build.
  182. @see jassert, jassertfalse, Logger
  183. */
  184. #ifndef JUCE_LOG_ASSERTIONS
  185. // #define JUCE_LOG_ASSERTIONS 1
  186. #endif
  187. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  188. which the ASIOAudioIODevice class can't be built. See the comments in the
  189. ASIOAudioIODevice class's header file for more info about this.
  190. (This only affects a Win32 build)
  191. */
  192. #ifndef JUCE_ASIO
  193. #define JUCE_ASIO 1
  194. #endif
  195. /** Comment out this macro to disable the Windows WASAPI audio device type.
  196. */
  197. #ifndef JUCE_WASAPI
  198. // #define JUCE_WASAPI 1
  199. #endif
  200. /** Comment out this macro to disable the Windows WASAPI audio device type.
  201. */
  202. #ifndef JUCE_DIRECTSOUND
  203. #define JUCE_DIRECTSOUND 1
  204. #endif
  205. /** Comment out this macro to disable building of ALSA device support on Linux.
  206. */
  207. #ifndef JUCE_ALSA
  208. #define JUCE_ALSA 1
  209. #endif
  210. /** Comment out this macro to disable building of JACK device support on Linux.
  211. */
  212. #ifndef JUCE_JACK
  213. #define JUCE_JACK 1
  214. #endif
  215. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  216. have the SDK installed.
  217. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  218. classes will be unavailable.
  219. On Windows, if you enable this, you'll need to have the QuickTime SDK
  220. installed, and its header files will need to be on your include path.
  221. */
  222. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  223. #define JUCE_QUICKTIME 1
  224. #endif
  225. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  226. have the appropriate headers and libraries available. If it's not enabled, the
  227. OpenGLComponent class will be unavailable.
  228. */
  229. #ifndef JUCE_OPENGL
  230. #define JUCE_OPENGL 1
  231. #endif
  232. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  233. If you're not going to need either of these formats, turn off the flags to
  234. avoid bloating your codebase with them.
  235. */
  236. #ifndef JUCE_USE_FLAC
  237. #define JUCE_USE_FLAC 1
  238. #endif
  239. #ifndef JUCE_USE_OGGVORBIS
  240. #define JUCE_USE_OGGVORBIS 1
  241. #endif
  242. /** This flag lets you enable the AudioCDBurner class. You might want to disable
  243. it to build without the MS SDK under windows.
  244. */
  245. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  246. #define JUCE_USE_CDBURNER 1
  247. #endif
  248. /** This flag lets you enable support for the AudioCDReader class. You might want to disable
  249. it to build without the MS SDK under windows.
  250. */
  251. #ifndef JUCE_USE_CDREADER
  252. #define JUCE_USE_CDREADER 1
  253. #endif
  254. /** Enabling this provides support for cameras, using the CameraDevice class
  255. */
  256. #if JUCE_QUICKTIME && ! defined (JUCE_USE_CAMERA)
  257. // #define JUCE_USE_CAMERA 1
  258. #endif
  259. /** Enabling this macro means that all regions that get repainted will have a coloured
  260. line drawn around them.
  261. This is handy if you're trying to optimise drawing, because it lets you easily see
  262. when anything is being repainted unnecessarily.
  263. */
  264. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  265. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  266. #endif
  267. /** Enable this under Linux to use Xinerama for multi-monitor support.
  268. */
  269. #ifndef JUCE_USE_XINERAMA
  270. #define JUCE_USE_XINERAMA 1
  271. #endif
  272. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  273. */
  274. #ifndef JUCE_USE_XSHM
  275. #define JUCE_USE_XSHM 1
  276. #endif
  277. /** Enabling this builds support for VST audio plugins.
  278. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  279. */
  280. #ifndef JUCE_PLUGINHOST_VST
  281. // #define JUCE_PLUGINHOST_VST 1
  282. #endif
  283. /** Enabling this builds support for AudioUnit audio plugins.
  284. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  285. */
  286. #ifndef JUCE_PLUGINHOST_AU
  287. // #define JUCE_PLUGINHOST_AU 1
  288. #endif
  289. /** Enabling this will avoid including any UI code in the build. This is handy for
  290. writing command-line utilities, e.g. on linux boxes which don't have some
  291. of the UI libraries installed.
  292. */
  293. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  294. //#define JUCE_ONLY_BUILD_CORE_LIBRARY 1
  295. #endif
  296. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  297. */
  298. #ifndef JUCE_WEB_BROWSER
  299. #define JUCE_WEB_BROWSER 1
  300. #endif
  301. /** Setting this allows the build to use old Carbon libraries that will be
  302. deprecated in newer versions of OSX. This is handy for some backwards-compatibility
  303. reasons.
  304. */
  305. #ifndef JUCE_SUPPORT_CARBON
  306. #define JUCE_SUPPORT_CARBON 1
  307. #endif
  308. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  309. codebase - you might need to use this if you're linking to some of these libraries
  310. yourself.
  311. */
  312. #ifndef JUCE_INCLUDE_ZLIB_CODE
  313. #define JUCE_INCLUDE_ZLIB_CODE 1
  314. #endif
  315. #ifndef JUCE_INCLUDE_FLAC_CODE
  316. #define JUCE_INCLUDE_FLAC_CODE 1
  317. #endif
  318. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  319. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  320. #endif
  321. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  322. #define JUCE_INCLUDE_PNGLIB_CODE 1
  323. #endif
  324. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  325. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  326. #endif
  327. /** Enable this to add extra memory-leak info to the new and delete operators.
  328. (Currently, this only affects Windows builds in debug mode).
  329. */
  330. #ifndef JUCE_CHECK_MEMORY_LEAKS
  331. #define JUCE_CHECK_MEMORY_LEAKS 1
  332. #endif
  333. /** Enable this to turn on juce's internal catching of exceptions.
  334. Turning it off will avoid any exception catching. With it on, all exceptions
  335. are passed to the JUCEApplication::unhandledException() callback for logging.
  336. */
  337. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  338. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  339. #endif
  340. /** If this macro is set, the Juce String class will use unicode as its
  341. internal representation. If it isn't set, it'll use ANSI.
  342. */
  343. #ifndef JUCE_STRINGS_ARE_UNICODE
  344. #define JUCE_STRINGS_ARE_UNICODE 1
  345. #endif
  346. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  347. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  348. #undef JUCE_QUICKTIME
  349. #define JUCE_QUICKTIME 0
  350. #undef JUCE_OPENGL
  351. #define JUCE_OPENGL 0
  352. #undef JUCE_USE_CDBURNER
  353. #define JUCE_USE_CDBURNER 0
  354. #undef JUCE_USE_CDREADER
  355. #define JUCE_USE_CDREADER 0
  356. #undef JUCE_WEB_BROWSER
  357. #define JUCE_WEB_BROWSER 0
  358. #undef JUCE_PLUGINHOST_AU
  359. #define JUCE_PLUGINHOST_AU 0
  360. #undef JUCE_PLUGINHOST_VST
  361. #define JUCE_PLUGINHOST_VST 0
  362. #endif
  363. #endif
  364. /********* End of inlined file: juce_Config.h *********/
  365. #ifdef JUCE_NAMESPACE
  366. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  367. #define END_JUCE_NAMESPACE }
  368. #else
  369. #define BEGIN_JUCE_NAMESPACE
  370. #define END_JUCE_NAMESPACE
  371. #endif
  372. /********* Start of inlined file: juce_PlatformDefs.h *********/
  373. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  374. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  375. /* This file defines miscellaneous macros for debugging, assertions, etc.
  376. */
  377. #ifdef JUCE_FORCE_DEBUG
  378. #undef JUCE_DEBUG
  379. #if JUCE_FORCE_DEBUG
  380. #define JUCE_DEBUG 1
  381. #endif
  382. #endif
  383. /** This macro defines the C calling convention used as the standard for Juce calls. */
  384. #if JUCE_MSVC
  385. #define JUCE_CALLTYPE __stdcall
  386. #else
  387. #define JUCE_CALLTYPE
  388. #endif
  389. // Debugging and assertion macros
  390. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  391. #if JUCE_LOG_ASSERTIONS
  392. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  393. #elif defined (JUCE_DEBUG)
  394. #define juce_LogCurrentAssertion fprintf (stderr, "JUCE Assertion failure in %s, line %d\n", __FILE__, __LINE__);
  395. #else
  396. #define juce_LogCurrentAssertion
  397. #endif
  398. #ifdef JUCE_DEBUG
  399. // If debugging is enabled..
  400. /** Writes a string to the standard error stream.
  401. This is only compiled in a debug build.
  402. @see Logger::outputDebugString
  403. */
  404. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  405. /** Printf's a string to the standard error stream.
  406. This is only compiled in a debug build.
  407. @see Logger::outputDebugString
  408. */
  409. #define DBG_PRINTF(dbgprintf) Logger::outputDebugPrintf dbgprintf;
  410. // Assertions..
  411. #if JUCE_WINDOWS || DOXYGEN
  412. #if JUCE_USE_INTRINSICS
  413. #pragma intrinsic (__debugbreak)
  414. /** This will try to break the debugger if one is currently hosting this app.
  415. @see jassert()
  416. */
  417. #define juce_breakDebugger __debugbreak();
  418. #elif JUCE_GCC
  419. /** This will try to break the debugger if one is currently hosting this app.
  420. @see jassert()
  421. */
  422. #define juce_breakDebugger asm("int $3");
  423. #else
  424. /** This will try to break the debugger if one is currently hosting this app.
  425. @see jassert()
  426. */
  427. #define juce_breakDebugger { __asm int 3 }
  428. #endif
  429. #elif JUCE_MAC
  430. #define juce_breakDebugger Debugger();
  431. #elif JUCE_IPHONE
  432. #define juce_breakDebugger kill (0, SIGTRAP);
  433. #elif JUCE_LINUX
  434. #define juce_breakDebugger kill (0, SIGTRAP);
  435. #endif
  436. /** This will always cause an assertion failure.
  437. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  438. in juce_Config.h).
  439. @see jassert()
  440. */
  441. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  442. /** Platform-independent assertion macro.
  443. This gets optimised out when not being built with debugging turned on.
  444. Be careful not to call any functions within its arguments that are vital to
  445. the behaviour of the program, because these won't get called in the release
  446. build.
  447. @see jassertfalse
  448. */
  449. #define jassert(expression) { if (! (expression)) jassertfalse }
  450. #else
  451. // If debugging is disabled, these dummy debug and assertion macros are used..
  452. #define DBG(dbgtext)
  453. #define DBG_PRINTF(dbgprintf)
  454. #define jassertfalse { juce_LogCurrentAssertion }
  455. #if JUCE_LOG_ASSERTIONS
  456. #define jassert(expression) { if (! (expression)) jassertfalse }
  457. #else
  458. #define jassert(a) { }
  459. #endif
  460. #endif
  461. #ifndef DOXYGEN
  462. template <bool b> struct JuceStaticAssert;
  463. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  464. #endif
  465. /** A compile-time assertion macro.
  466. If the expression parameter is false, the macro will cause a compile error.
  467. */
  468. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  469. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  470. #define JUCE_TRY try
  471. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  472. object so they can be logged by the application if it wants to.
  473. */
  474. #define JUCE_CATCH_EXCEPTION \
  475. catch (const std::exception& e) \
  476. { \
  477. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  478. } \
  479. catch (...) \
  480. { \
  481. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  482. }
  483. #define JUCE_CATCH_ALL catch (...) {}
  484. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse }
  485. #else
  486. #define JUCE_TRY
  487. #define JUCE_CATCH_EXCEPTION
  488. #define JUCE_CATCH_ALL
  489. #define JUCE_CATCH_ALL_ASSERT
  490. #endif
  491. // Macros for inlining.
  492. #if JUCE_MSVC
  493. /** A platform-independent way of forcing an inline function.
  494. Use the syntax: @code
  495. forcedinline void myfunction (int x)
  496. @endcode
  497. */
  498. #ifdef JUCE_DEBUG
  499. #define forcedinline __forceinline
  500. #else
  501. #define forcedinline inline
  502. #endif
  503. /** A platform-independent way of stopping the compiler inlining a function.
  504. Use the syntax: @code
  505. juce_noinline void myfunction (int x)
  506. @endcode
  507. */
  508. #define juce_noinline
  509. #else
  510. /** A platform-independent way of forcing an inline function.
  511. Use the syntax: @code
  512. forcedinline void myfunction (int x)
  513. @endcode
  514. */
  515. #ifndef JUCE_DEBUG
  516. #define forcedinline inline __attribute__((always_inline))
  517. #else
  518. #define forcedinline inline
  519. #endif
  520. /** A platform-independent way of stopping the compiler inlining a function.
  521. Use the syntax: @code
  522. juce_noinline void myfunction (int x)
  523. @endcode
  524. */
  525. #define juce_noinline __attribute__((noinline))
  526. #endif
  527. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  528. /********* End of inlined file: juce_PlatformDefs.h *********/
  529. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  530. #if JUCE_MSVC
  531. #pragma warning (push)
  532. #pragma warning (disable: 4514 4245 4100)
  533. #endif
  534. #include <cstdlib>
  535. #include <cstdarg>
  536. #include <climits>
  537. #include <cmath>
  538. #include <cwchar>
  539. #include <stdexcept>
  540. #include <typeinfo>
  541. #include <cstring>
  542. #include <cstdio>
  543. #if JUCE_USE_INTRINSICS
  544. #include <intrin.h>
  545. #endif
  546. #if JUCE_MAC
  547. #include <libkern/OSAtomic.h>
  548. #endif
  549. #if JUCE_LINUX
  550. #include <signal.h>
  551. #endif
  552. #if JUCE_MSVC && JUCE_DEBUG
  553. #include <crtdbg.h>
  554. #endif
  555. #if JUCE_MSVC
  556. #include <malloc.h>
  557. #pragma warning (pop)
  558. #endif
  559. // DLL building settings on Win32
  560. #if JUCE_MSVC
  561. #ifdef JUCE_DLL_BUILD
  562. #define JUCE_API __declspec (dllexport)
  563. #pragma warning (disable: 4251)
  564. #elif defined (JUCE_DLL)
  565. #define JUCE_API __declspec (dllimport)
  566. #pragma warning (disable: 4251)
  567. #endif
  568. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  569. #ifdef JUCE_DLL_BUILD
  570. #define JUCE_API __attribute__ ((visibility("default")))
  571. #endif
  572. #endif
  573. #ifndef JUCE_API
  574. /** This macro is added to all juce public class declarations. */
  575. #define JUCE_API
  576. #endif
  577. /** This macro is added to all juce public function declarations. */
  578. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  579. // Now include some basics that are needed by most of the Juce classes...
  580. BEGIN_JUCE_NAMESPACE
  581. extern bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw();
  582. #if JUCE_LOG_ASSERTIONS
  583. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  584. #endif
  585. /********* Start of inlined file: juce_Memory.h *********/
  586. #ifndef __JUCE_MEMORY_JUCEHEADER__
  587. #define __JUCE_MEMORY_JUCEHEADER__
  588. /*
  589. This file defines the various juce_malloc(), juce_free() macros that should be used in
  590. preference to the standard calls.
  591. */
  592. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  593. #ifndef JUCE_DLL
  594. // Win32 debug non-DLL versions..
  595. /** This should be used instead of calling malloc directly.
  596. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  597. */
  598. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  599. /** This should be used instead of calling calloc directly.
  600. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  601. */
  602. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  603. /** This should be used instead of calling realloc directly.
  604. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  605. */
  606. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  607. /** This should be used instead of calling free directly.
  608. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  609. */
  610. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  611. #else
  612. // Win32 debug DLL versions..
  613. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  614. // way all juce calls in the DLL and in the host API will all use the same allocator.
  615. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  616. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  617. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  618. extern JUCE_API void juce_DebugFree (void* const block);
  619. /** This should be used instead of calling malloc directly.
  620. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  621. */
  622. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  623. /** This should be used instead of calling calloc directly.
  624. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  625. */
  626. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  627. /** This should be used instead of calling realloc directly.
  628. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  629. */
  630. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  631. /** This should be used instead of calling free directly.
  632. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  633. */
  634. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  635. #endif
  636. #if ! defined (_AFXDLL)
  637. /** This macro can be added to classes to add extra debugging information to the memory
  638. allocated for them, so you can see the type of objects involved when there's a dump
  639. of leaked objects at program shutdown. (Only works on win32 at the moment).
  640. */
  641. #define juce_UseDebuggingNewOperator \
  642. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  643. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  644. static void operator delete (void* p) { juce_free (p); }
  645. #endif
  646. #elif defined (JUCE_DLL)
  647. // Win32 DLL (release) versions..
  648. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  649. // way all juce calls in the DLL and in the host API will all use the same allocator.
  650. extern JUCE_API void* juce_Malloc (const int size);
  651. extern JUCE_API void* juce_Calloc (const int size);
  652. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  653. extern JUCE_API void juce_Free (void* const block);
  654. /** This should be used instead of calling malloc directly.
  655. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  656. */
  657. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  658. /** This should be used instead of calling calloc directly.
  659. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  660. */
  661. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  662. /** This should be used instead of calling realloc directly.
  663. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  664. */
  665. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  666. /** This should be used instead of calling free directly.
  667. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  668. */
  669. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  670. #define juce_UseDebuggingNewOperator \
  671. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  672. static void* operator new (size_t sz, void* p) { return ::operator new (sz, p); } \
  673. static void operator delete (void* p) { juce_free (p); }
  674. #else
  675. // Mac, Linux and Win32 (release) versions..
  676. /** This should be used instead of calling malloc directly.
  677. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  678. */
  679. #define juce_malloc(numBytes) malloc (numBytes)
  680. /** This should be used instead of calling calloc directly.
  681. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  682. */
  683. #define juce_calloc(numBytes) calloc (1, numBytes)
  684. /** This should be used instead of calling realloc directly.
  685. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  686. */
  687. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  688. /** This should be used instead of calling free directly.
  689. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  690. */
  691. #define juce_free(location) free (location)
  692. #endif
  693. /** This macro can be added to classes to add extra debugging information to the memory
  694. allocated for them, so you can see the type of objects involved when there's a dump
  695. of leaked objects at program shutdown. (Only works on win32 at the moment).
  696. Note that if you create a class that inherits from a class that uses this macro,
  697. your class must also use the macro, otherwise you'll probably get compile errors
  698. because of ambiguous new operators.
  699. Most of the JUCE classes use it, so see these for examples of where it should go.
  700. */
  701. #ifndef juce_UseDebuggingNewOperator
  702. #define juce_UseDebuggingNewOperator
  703. #endif
  704. #if JUCE_MSVC
  705. /** This is a compiler-indenpendent way of declaring a variable as being thread-local.
  706. E.g.
  707. @code
  708. juce_ThreadLocal int myVariable;
  709. @endcode
  710. */
  711. #define juce_ThreadLocal __declspec(thread)
  712. #else
  713. #define juce_ThreadLocal __thread
  714. #endif
  715. /** Clears a block of memory. */
  716. #define zeromem(memory, numBytes) memset (memory, 0, numBytes)
  717. /** Clears a reference to a local structure. */
  718. #define zerostruct(structure) memset (&structure, 0, sizeof (structure))
  719. /** A handy macro that calls delete on a pointer if it's non-zero, and
  720. then sets the pointer to null.
  721. */
  722. #define deleteAndZero(pointer) { delete (pointer); (pointer) = 0; }
  723. #endif // __JUCE_MEMORY_JUCEHEADER__
  724. /********* End of inlined file: juce_Memory.h *********/
  725. /********* Start of inlined file: juce_MathsFunctions.h *********/
  726. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  727. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  728. /*
  729. This file sets up some handy mathematical typdefs and functions.
  730. */
  731. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  732. /** A platform-independent 8-bit signed integer type. */
  733. typedef signed char int8;
  734. /** A platform-independent 8-bit unsigned integer type. */
  735. typedef unsigned char uint8;
  736. /** A platform-independent 16-bit signed integer type. */
  737. typedef signed short int16;
  738. /** A platform-independent 16-bit unsigned integer type. */
  739. typedef unsigned short uint16;
  740. /** A platform-independent 32-bit signed integer type. */
  741. typedef signed int int32;
  742. /** A platform-independent 32-bit unsigned integer type. */
  743. typedef unsigned int uint32;
  744. #if JUCE_MSVC
  745. /** A platform-independent 64-bit integer type. */
  746. typedef __int64 int64;
  747. /** A platform-independent 64-bit unsigned integer type. */
  748. typedef unsigned __int64 uint64;
  749. /** A platform-independent macro for writing 64-bit literals, needed because
  750. different compilers have different syntaxes for this.
  751. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  752. GCC, or 0x1000000000 for MSVC.
  753. */
  754. #define literal64bit(longLiteral) ((__int64) longLiteral)
  755. #else
  756. /** A platform-independent 64-bit integer type. */
  757. typedef long long int64;
  758. /** A platform-independent 64-bit unsigned integer type. */
  759. typedef unsigned long long uint64;
  760. /** A platform-independent macro for writing 64-bit literals, needed because
  761. different compilers have different syntaxes for this.
  762. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  763. GCC, or 0x1000000000 for MSVC.
  764. */
  765. #define literal64bit(longLiteral) (longLiteral##LL)
  766. #endif
  767. #if JUCE_64BIT
  768. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  769. typedef int64 pointer_sized_int;
  770. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  771. typedef uint64 pointer_sized_uint;
  772. #elif _MSC_VER >= 1300
  773. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  774. typedef _W64 int pointer_sized_int;
  775. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  776. typedef _W64 unsigned int pointer_sized_uint;
  777. #else
  778. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  779. typedef int pointer_sized_int;
  780. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  781. typedef unsigned int pointer_sized_uint;
  782. #endif
  783. /** A platform-independent unicode character type. */
  784. typedef wchar_t juce_wchar;
  785. // Some indispensible min/max functions
  786. /** Returns the larger of two values. */
  787. forcedinline int jmax (const int a, const int b) throw() { return (a < b) ? b : a; }
  788. /** Returns the larger of two values. */
  789. forcedinline int64 jmax (const int64 a, const int64 b) throw() { return (a < b) ? b : a; }
  790. /** Returns the larger of two values. */
  791. forcedinline float jmax (const float a, const float b) throw() { return (a < b) ? b : a; }
  792. /** Returns the larger of two values. */
  793. forcedinline double jmax (const double a, const double b) throw() { return (a < b) ? b : a; }
  794. /** Returns the larger of three values. */
  795. inline int jmax (const int a, const int b, const int c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  796. /** Returns the larger of three values. */
  797. inline int64 jmax (const int64 a, const int64 b, const int64 c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  798. /** Returns the larger of three values. */
  799. inline float jmax (const float a, const float b, const float c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  800. /** Returns the larger of three values. */
  801. inline double jmax (const double a, const double b, const double c) throw() { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  802. /** Returns the larger of four values. */
  803. inline int jmax (const int a, const int b, const int c, const int d) throw() { return jmax (a, jmax (b, c, d)); }
  804. /** Returns the larger of four values. */
  805. inline int64 jmax (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmax (a, jmax (b, c, d)); }
  806. /** Returns the larger of four values. */
  807. inline float jmax (const float a, const float b, const float c, const float d) throw() { return jmax (a, jmax (b, c, d)); }
  808. /** Returns the larger of four values. */
  809. inline double jmax (const double a, const double b, const double c, const double d) throw() { return jmax (a, jmax (b, c, d)); }
  810. /** Returns the smaller of two values. */
  811. inline int jmin (const int a, const int b) throw() { return (a > b) ? b : a; }
  812. /** Returns the smaller of two values. */
  813. inline int64 jmin (const int64 a, const int64 b) throw() { return (a > b) ? b : a; }
  814. /** Returns the smaller of two values. */
  815. inline float jmin (const float a, const float b) throw() { return (a > b) ? b : a; }
  816. /** Returns the smaller of two values. */
  817. inline double jmin (const double a, const double b) throw() { return (a > b) ? b : a; }
  818. /** Returns the smaller of three values. */
  819. inline int jmin (const int a, const int b, const int c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  820. /** Returns the smaller of three values. */
  821. inline int64 jmin (const int64 a, const int64 b, const int64 c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  822. /** Returns the smaller of three values. */
  823. inline float jmin (const float a, const float b, const float c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  824. /** Returns the smaller of three values. */
  825. inline double jmin (const double a, const double b, const double c) throw() { return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a); }
  826. /** Returns the smaller of four values. */
  827. inline int jmin (const int a, const int b, const int c, const int d) throw() { return jmin (a, jmin (b, c, d)); }
  828. /** Returns the smaller of four values. */
  829. inline int64 jmin (const int64 a, const int64 b, const int64 c, const int64 d) throw() { return jmin (a, jmin (b, c, d)); }
  830. /** Returns the smaller of four values. */
  831. inline float jmin (const float a, const float b, const float c, const float d) throw() { return jmin (a, jmin (b, c, d)); }
  832. /** Returns the smaller of four values. */
  833. inline double jmin (const double a, const double b, const double c, const double d) throw() { return jmin (a, jmin (b, c, d)); }
  834. /** Constrains a value to keep it within a given range.
  835. This will check that the specified value lies between the lower and upper bounds
  836. specified, and if not, will return the nearest value that would be in-range. Effectively,
  837. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  838. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  839. the results will be unpredictable.
  840. @param lowerLimit the minimum value to return
  841. @param upperLimit the maximum value to return
  842. @param valueToConstrain the value to try to return
  843. @returns the closest value to valueToConstrain which lies between lowerLimit
  844. and upperLimit (inclusive)
  845. @see jlimit0To, jmin, jmax
  846. */
  847. template <class Type>
  848. inline Type jlimit (const Type lowerLimit,
  849. const Type upperLimit,
  850. const Type valueToConstrain) throw()
  851. {
  852. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  853. return (valueToConstrain < lowerLimit) ? lowerLimit
  854. : ((valueToConstrain > upperLimit) ? upperLimit
  855. : valueToConstrain);
  856. }
  857. /** Handy function to swap two values over.
  858. */
  859. template <class Type>
  860. inline void swapVariables (Type& variable1, Type& variable2) throw()
  861. {
  862. const Type tempVal = variable1;
  863. variable1 = variable2;
  864. variable2 = tempVal;
  865. }
  866. /** Handy macro for getting the number of elements in a simple const C array.
  867. E.g.
  868. @code
  869. static int myArray[] = { 1, 2, 3 };
  870. int numElements = numElementsInArray (myArray) // returns 3
  871. @endcode
  872. */
  873. #define numElementsInArray(a) ((int) (sizeof (a) / sizeof ((a)[0])))
  874. // Some useful maths functions that aren't always present with all compilers and build settings.
  875. #if JUCE_WINDOWS || defined (DOXYGEN)
  876. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  877. versions of these functions of various platforms and compilers. */
  878. forcedinline double juce_hypot (double a, double b) { return _hypot (a, b); }
  879. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  880. versions of these functions of various platforms and compilers. */
  881. forcedinline float juce_hypotf (float a, float b) { return (float) _hypot (a, b); }
  882. #else
  883. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  884. versions of these functions of various platforms and compilers. */
  885. forcedinline double juce_hypot (double a, double b) { return hypot (a, b); }
  886. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  887. versions of these functions of various platforms and compilers. */
  888. forcedinline float juce_hypotf (float a, float b) { return hypotf (a, b); }
  889. #endif
  890. inline int64 abs64 (const int64 n) throw() { return (n >= 0) ? n : -n; }
  891. /** A predefined value for Pi, at double-precision.
  892. @see float_Pi
  893. */
  894. const double double_Pi = 3.1415926535897932384626433832795;
  895. /** A predefined value for Pi, at sngle-precision.
  896. @see double_Pi
  897. */
  898. const float float_Pi = 3.14159265358979323846f;
  899. /** The isfinite() method seems to vary greatly between platforms, so this is a
  900. platform-independent macro for it.
  901. */
  902. #if JUCE_LINUX || JUCE_MAC || JUCE_IPHONE
  903. #define juce_isfinite(v) std::isfinite(v)
  904. #elif JUCE_WINDOWS && ! defined (isfinite)
  905. #define juce_isfinite(v) _finite(v)
  906. #else
  907. #define juce_isfinite(v) isfinite(v)
  908. #endif
  909. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  910. /********* End of inlined file: juce_MathsFunctions.h *********/
  911. /********* Start of inlined file: juce_DataConversions.h *********/
  912. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  913. #define __JUCE_DATACONVERSIONS_JUCEHEADER__
  914. #if JUCE_USE_INTRINSICS
  915. #pragma intrinsic (_byteswap_ulong)
  916. #endif
  917. // Endianness conversions..
  918. #if JUCE_IPHONE
  919. // a gcc compiler error seems to mean that these functions only work properly
  920. // on the iPhone if they are declared static..
  921. static forcedinline uint32 swapByteOrder (uint32 n) throw();
  922. static inline uint16 swapByteOrder (const uint16 n) throw();
  923. static inline uint64 swapByteOrder (const uint64 value) throw();
  924. #endif
  925. /** Swaps the byte-order in an integer from little to big-endianness or vice-versa. */
  926. forcedinline uint32 swapByteOrder (uint32 n) throw()
  927. {
  928. #if JUCE_MAC || JUCE_IPHONE
  929. // Mac version
  930. return OSSwapInt32 (n);
  931. #elif JUCE_GCC
  932. // Inpenetrable GCC version..
  933. asm("bswap %%eax" : "=a"(n) : "a"(n));
  934. return n;
  935. #elif JUCE_USE_INTRINSICS
  936. // Win32 intrinsics version..
  937. return _byteswap_ulong (n);
  938. #else
  939. // Win32 version..
  940. __asm {
  941. mov eax, n
  942. bswap eax
  943. mov n, eax
  944. }
  945. return n;
  946. #endif
  947. }
  948. /** Swaps the byte-order of a 16-bit short. */
  949. inline uint16 swapByteOrder (const uint16 n) throw()
  950. {
  951. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  952. // Win32 intrinsics version..
  953. return (uint16) _byteswap_ushort (n);
  954. #else
  955. return (uint16) ((n << 8) | (n >> 8));
  956. #endif
  957. }
  958. inline uint64 swapByteOrder (const uint64 value) throw()
  959. {
  960. #if JUCE_MAC || JUCE_IPHONE
  961. return OSSwapInt64 (value);
  962. #elif JUCE_USE_INTRINSICS
  963. return _byteswap_uint64 (value);
  964. #else
  965. return (((int64) swapByteOrder ((uint32) value)) << 32)
  966. | swapByteOrder ((uint32) (value >> 32));
  967. #endif
  968. }
  969. #if JUCE_LITTLE_ENDIAN
  970. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  971. inline uint16 swapIfBigEndian (const uint16 v) throw() { return v; }
  972. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  973. inline uint32 swapIfBigEndian (const uint32 v) throw() { return v; }
  974. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  975. inline uint64 swapIfBigEndian (const uint64 v) throw() { return v; }
  976. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  977. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return swapByteOrder (v); }
  978. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  979. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return swapByteOrder (v); }
  980. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  981. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return swapByteOrder (v); }
  982. /** Turns 4 bytes into a little-endian integer. */
  983. inline uint32 littleEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  984. /** Turns 2 bytes into a little-endian integer. */
  985. inline uint16 littleEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  986. /** Turns 4 bytes into a big-endian integer. */
  987. inline uint32 bigEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  988. /** Turns 2 bytes into a big-endian integer. */
  989. inline uint16 bigEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  990. #else
  991. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  992. inline uint16 swapIfBigEndian (const uint16 v) throw() { return swapByteOrder (v); }
  993. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  994. inline uint32 swapIfBigEndian (const uint32 v) throw() { return swapByteOrder (v); }
  995. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  996. inline uint64 swapIfBigEndian (const uint64 v) throw() { return swapByteOrder (v); }
  997. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  998. inline uint16 swapIfLittleEndian (const uint16 v) throw() { return v; }
  999. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1000. inline uint32 swapIfLittleEndian (const uint32 v) throw() { return v; }
  1001. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1002. inline uint64 swapIfLittleEndian (const uint64 v) throw() { return v; }
  1003. /** Turns 4 bytes into a little-endian integer. */
  1004. inline uint32 littleEndianInt (const char* const bytes) throw() { return swapByteOrder (*(uint32*) bytes); }
  1005. /** Turns 2 bytes into a little-endian integer. */
  1006. inline uint16 littleEndianShort (const char* const bytes) throw() { return swapByteOrder (*(uint16*) bytes); }
  1007. /** Turns 4 bytes into a big-endian integer. */
  1008. inline uint32 bigEndianInt (const char* const bytes) throw() { return *(uint32*) bytes; }
  1009. /** Turns 2 bytes into a big-endian integer. */
  1010. inline uint16 bigEndianShort (const char* const bytes) throw() { return *(uint16*) bytes; }
  1011. #endif
  1012. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1013. inline int littleEndian24Bit (const char* const bytes) throw() { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1014. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1015. inline int bigEndian24Bit (const char* const bytes) throw() { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1016. /** Copies a 24-bit number to 3 little-endian bytes. */
  1017. 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); }
  1018. /** Copies a 24-bit number to 3 big-endian bytes. */
  1019. 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); }
  1020. /** Fast floating-point-to-integer conversion.
  1021. This is faster than using the normal c++ cast to convert a double to an int, and
  1022. it will round the value to the nearest integer, rather than rounding it down
  1023. like the normal cast does.
  1024. Note that this routine gets its speed at the expense of some accuracy, and when
  1025. rounding values whose floating point component is exactly 0.5, odd numbers and
  1026. even numbers will be rounded up or down differently. For a more accurate conversion,
  1027. see roundDoubleToIntAccurate().
  1028. */
  1029. inline int roundDoubleToInt (const double value) throw()
  1030. {
  1031. union { int asInt[2]; double asDouble; } n;
  1032. n.asDouble = value + 6755399441055744.0;
  1033. #if JUCE_BIG_ENDIAN
  1034. return n.asInt [1];
  1035. #else
  1036. return n.asInt [0];
  1037. #endif
  1038. }
  1039. /** Fast floating-point-to-integer conversion.
  1040. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  1041. fine for values above zero, but negative numbers are rounded the wrong way.
  1042. */
  1043. inline int roundDoubleToIntAccurate (const double value) throw()
  1044. {
  1045. return roundDoubleToInt (value + 1.5e-8);
  1046. }
  1047. /** Fast floating-point-to-integer conversion.
  1048. This is faster than using the normal c++ cast to convert a float to an int, and
  1049. it will round the value to the nearest integer, rather than rounding it down
  1050. like the normal cast does.
  1051. Note that this routine gets its speed at the expense of some accuracy, and when
  1052. rounding values whose floating point component is exactly 0.5, odd numbers and
  1053. even numbers will be rounded up or down differently.
  1054. */
  1055. inline int roundFloatToInt (const float value) throw()
  1056. {
  1057. union { int asInt[2]; double asDouble; } n;
  1058. n.asDouble = value + 6755399441055744.0;
  1059. #if JUCE_BIG_ENDIAN
  1060. return n.asInt [1];
  1061. #else
  1062. return n.asInt [0];
  1063. #endif
  1064. }
  1065. #endif // __JUCE_DATACONVERSIONS_JUCEHEADER__
  1066. /********* End of inlined file: juce_DataConversions.h *********/
  1067. /********* Start of inlined file: juce_Logger.h *********/
  1068. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1069. #define __JUCE_LOGGER_JUCEHEADER__
  1070. /********* Start of inlined file: juce_String.h *********/
  1071. #ifndef __JUCE_STRING_JUCEHEADER__
  1072. #define __JUCE_STRING_JUCEHEADER__
  1073. /********* Start of inlined file: juce_CharacterFunctions.h *********/
  1074. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1075. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1076. /* The String class can either use wchar_t unicode characters, or 8-bit characters
  1077. (in the default system encoding) as its internal representation.
  1078. To use unicode, define the JUCE_STRINGS_ARE_UNICODE macro in juce_Config.h
  1079. Be sure to use "tchar" for characters rather than "char", and always wrap string
  1080. literals in the T("abcd") macro, so that it all works nicely either way round.
  1081. */
  1082. #if JUCE_STRINGS_ARE_UNICODE
  1083. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1084. typedef juce_wchar tchar;
  1085. #define juce_tcharToWideChar(c) (c)
  1086. #else
  1087. #define JUCE_T(stringLiteral) (stringLiteral)
  1088. typedef char tchar;
  1089. #define juce_tcharToWideChar(c) ((juce_wchar) (unsigned char) (c))
  1090. #endif
  1091. #if ! JUCE_DONT_DEFINE_MACROS
  1092. /** The 'T' macro allows a literal string to be compiled using either 8-bit characters
  1093. or unicode.
  1094. If you write your string literals in the form T("xyz"), this will either be compiled
  1095. as "xyz" for non-unicode builds, or L"xyz" for unicode builds, depending on whether the
  1096. JUCE_STRINGS_ARE_UNICODE macro has been set in juce_Config.h
  1097. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1098. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1099. the juce/src directory) to avoid defining this macro. See the comments in
  1100. juce_withoutMacros.h for more info.
  1101. */
  1102. #define T(stringLiteral) JUCE_T(stringLiteral)
  1103. #endif
  1104. /**
  1105. A set of methods for manipulating characters and character strings, with
  1106. duplicate methods to handle 8-bit and unicode characters.
  1107. These are defined as wrappers around the basic C string handlers, to provide
  1108. a clean, cross-platform layer, (because various platforms differ in the
  1109. range of C library calls that they provide).
  1110. @see String
  1111. */
  1112. class JUCE_API CharacterFunctions
  1113. {
  1114. public:
  1115. static int length (const char* const s) throw();
  1116. static int length (const juce_wchar* const s) throw();
  1117. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1118. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1119. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1120. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1121. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1122. static void append (char* dest, const char* src) throw();
  1123. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1124. static int compare (const char* const s1, const char* const s2) throw();
  1125. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1126. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1127. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1128. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1129. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1130. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1131. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1132. static const char* find (const char* const haystack, const char* const needle) throw();
  1133. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1134. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1135. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1136. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1137. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1138. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1139. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1140. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1141. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1142. static int getIntValue (const char* const s) throw();
  1143. static int getIntValue (const juce_wchar* s) throw();
  1144. static int64 getInt64Value (const char* s) throw();
  1145. static int64 getInt64Value (const juce_wchar* s) throw();
  1146. static double getDoubleValue (const char* const s) throw();
  1147. static double getDoubleValue (const juce_wchar* const s) throw();
  1148. static char toUpperCase (const char character) throw();
  1149. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1150. static void toUpperCase (char* s) throw();
  1151. static void toUpperCase (juce_wchar* s) throw();
  1152. static bool isUpperCase (const char character) throw();
  1153. static bool isUpperCase (const juce_wchar character) throw();
  1154. static char toLowerCase (const char character) throw();
  1155. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1156. static void toLowerCase (char* s) throw();
  1157. static void toLowerCase (juce_wchar* s) throw();
  1158. static bool isLowerCase (const char character) throw();
  1159. static bool isLowerCase (const juce_wchar character) throw();
  1160. static bool isWhitespace (const char character) throw();
  1161. static bool isWhitespace (const juce_wchar character) throw();
  1162. static bool isDigit (const char character) throw();
  1163. static bool isDigit (const juce_wchar character) throw();
  1164. static bool isLetter (const char character) throw();
  1165. static bool isLetter (const juce_wchar character) throw();
  1166. static bool isLetterOrDigit (const char character) throw();
  1167. static bool isLetterOrDigit (const juce_wchar character) throw();
  1168. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1169. hex digit.
  1170. */
  1171. static int getHexDigitValue (const tchar digit) throw();
  1172. static int printf (char* const dest, const int maxLength, const char* const format, ...) throw();
  1173. static int printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw();
  1174. static int vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw();
  1175. static int vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw();
  1176. };
  1177. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1178. /********* End of inlined file: juce_CharacterFunctions.h *********/
  1179. /**
  1180. The JUCE String class!
  1181. Using a reference-counted internal representation, these strings are fast
  1182. and efficient, and there are methods to do just about any operation you'll ever
  1183. dream of.
  1184. @see StringArray, StringPairArray
  1185. */
  1186. class JUCE_API String
  1187. {
  1188. public:
  1189. /** Creates an empty string.
  1190. @see empty
  1191. */
  1192. String() throw();
  1193. /** Creates a copy of another string. */
  1194. String (const String& other) throw();
  1195. /** Creates a string from a zero-terminated text string.
  1196. The string is assumed to be stored in the default system encoding.
  1197. */
  1198. String (const char* const text) throw();
  1199. /** Creates a string from an string of characters.
  1200. This will use up the the first maxChars characters of the string (or
  1201. less if the string is actually shorter)
  1202. */
  1203. String (const char* const text,
  1204. const int maxChars) throw();
  1205. /** Creates a string from a zero-terminated unicode text string. */
  1206. String (const juce_wchar* const unicodeText) throw();
  1207. /** Creates a string from a unicode text string.
  1208. This will use up the the first maxChars characters of the string (or
  1209. less if the string is actually shorter)
  1210. */
  1211. String (const juce_wchar* const unicodeText,
  1212. const int maxChars) throw();
  1213. /** Creates a string from a single character. */
  1214. static const String charToString (const tchar character) throw();
  1215. /** Destructor. */
  1216. ~String() throw();
  1217. /** This is an empty string that can be used whenever one is needed.
  1218. It's better to use this than String() because it explains what's going on
  1219. and is more efficient.
  1220. */
  1221. static const String empty;
  1222. /** Generates a probably-unique 32-bit hashcode from this string. */
  1223. int hashCode() const throw();
  1224. /** Generates a probably-unique 64-bit hashcode from this string. */
  1225. int64 hashCode64() const throw();
  1226. /** Returns the number of characters in the string. */
  1227. int length() const throw();
  1228. // Assignment and concatenation operators..
  1229. /** Replaces this string's contents with another string. */
  1230. const String& operator= (const tchar* const other) throw();
  1231. /** Replaces this string's contents with another string. */
  1232. const String& operator= (const String& other) throw();
  1233. /** Appends another string at the end of this one. */
  1234. const String& operator+= (const tchar* const textToAppend) throw();
  1235. /** Appends another string at the end of this one. */
  1236. const String& operator+= (const String& stringToAppend) throw();
  1237. /** Appends a character at the end of this string. */
  1238. const String& operator+= (const char characterToAppend) throw();
  1239. /** Appends a character at the end of this string. */
  1240. const String& operator+= (const juce_wchar characterToAppend) throw();
  1241. /** Appends a string at the end of this one.
  1242. @param textToAppend the string to add
  1243. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1244. */
  1245. void append (const tchar* const textToAppend,
  1246. const int maxCharsToTake) throw();
  1247. /** Appends a string at the end of this one.
  1248. @returns the concatenated string
  1249. */
  1250. const String operator+ (const String& stringToAppend) const throw();
  1251. /** Appends a string at the end of this one.
  1252. @returns the concatenated string
  1253. */
  1254. const String operator+ (const tchar* const textToAppend) const throw();
  1255. /** Appends a character at the end of this one.
  1256. @returns the concatenated string
  1257. */
  1258. const String operator+ (const tchar characterToAppend) const throw();
  1259. /** Appends a character at the end of this string. */
  1260. String& operator<< (const char n) throw();
  1261. /** Appends a character at the end of this string. */
  1262. String& operator<< (const juce_wchar n) throw();
  1263. /** Appends another string at the end of this one. */
  1264. String& operator<< (const char* const text) throw();
  1265. /** Appends another string at the end of this one. */
  1266. String& operator<< (const juce_wchar* const text) throw();
  1267. /** Appends another string at the end of this one. */
  1268. String& operator<< (const String& text) throw();
  1269. /** Appends a decimal number at the end of this string. */
  1270. String& operator<< (const short number) throw();
  1271. /** Appends a decimal number at the end of this string. */
  1272. String& operator<< (const int number) throw();
  1273. /** Appends a decimal number at the end of this string. */
  1274. String& operator<< (const unsigned int number) throw();
  1275. /** Appends a decimal number at the end of this string. */
  1276. String& operator<< (const long number) throw();
  1277. /** Appends a decimal number at the end of this string. */
  1278. String& operator<< (const unsigned long number) throw();
  1279. /** Appends a decimal number at the end of this string. */
  1280. String& operator<< (const float number) throw();
  1281. /** Appends a decimal number at the end of this string. */
  1282. String& operator<< (const double number) throw();
  1283. // Comparison methods..
  1284. /** Returns true if the string contains no characters.
  1285. Note that there's also an isNotEmpty() method to help write readable code.
  1286. @see containsNonWhitespaceChars()
  1287. */
  1288. inline bool isEmpty() const throw() { return text->text[0] == 0; }
  1289. /** Returns true if the string contains at least one character.
  1290. Note that there's also an isEmpty() method to help write readable code.
  1291. @see containsNonWhitespaceChars()
  1292. */
  1293. inline bool isNotEmpty() const throw() { return text->text[0] != 0; }
  1294. /** Case-sensitive comparison with another string. */
  1295. bool operator== (const String& other) const throw();
  1296. /** Case-sensitive comparison with another string. */
  1297. bool operator== (const tchar* const other) const throw();
  1298. /** Case-sensitive comparison with another string. */
  1299. bool operator!= (const String& other) const throw();
  1300. /** Case-sensitive comparison with another string. */
  1301. bool operator!= (const tchar* const other) const throw();
  1302. /** Case-insensitive comparison with another string. */
  1303. bool equalsIgnoreCase (const String& other) const throw();
  1304. /** Case-insensitive comparison with another string. */
  1305. bool equalsIgnoreCase (const tchar* const other) const throw();
  1306. /** Case-sensitive comparison with another string. */
  1307. bool operator> (const String& other) const throw();
  1308. /** Case-sensitive comparison with another string. */
  1309. bool operator< (const tchar* const other) const throw();
  1310. /** Case-sensitive comparison with another string. */
  1311. bool operator>= (const String& other) const throw();
  1312. /** Case-sensitive comparison with another string. */
  1313. bool operator<= (const tchar* const other) const throw();
  1314. /** Case-sensitive comparison with another string.
  1315. @returns 0 if the two strings are identical; negative if this string
  1316. comes before the other one alphabetically, or positive if it
  1317. comes after it.
  1318. */
  1319. int compare (const tchar* const other) const throw();
  1320. /** Case-insensitive comparison with another string.
  1321. @returns 0 if the two strings are identical; negative if this string
  1322. comes before the other one alphabetically, or positive if it
  1323. comes after it.
  1324. */
  1325. int compareIgnoreCase (const tchar* const other) const throw();
  1326. /** Lexicographic comparison with another string.
  1327. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1328. characters, making it good for sorting human-readable strings.
  1329. @returns 0 if the two strings are identical; negative if this string
  1330. comes before the other one alphabetically, or positive if it
  1331. comes after it.
  1332. */
  1333. int compareLexicographically (const tchar* const other) const throw();
  1334. /** Tests whether the string begins with another string.
  1335. Uses a case-sensitive comparison.
  1336. */
  1337. bool startsWith (const tchar* const text) const throw();
  1338. /** Tests whether the string begins with a particular character.
  1339. Uses a case-sensitive comparison.
  1340. */
  1341. bool startsWithChar (const tchar character) const throw();
  1342. /** Tests whether the string begins with another string.
  1343. Uses a case-insensitive comparison.
  1344. */
  1345. bool startsWithIgnoreCase (const tchar* const text) const throw();
  1346. /** Tests whether the string ends with another string.
  1347. Uses a case-sensitive comparison.
  1348. */
  1349. bool endsWith (const tchar* const text) const throw();
  1350. /** Tests whether the string ends with a particular character.
  1351. Uses a case-sensitive comparison.
  1352. */
  1353. bool endsWithChar (const tchar character) const throw();
  1354. /** Tests whether the string ends with another string.
  1355. Uses a case-insensitive comparison.
  1356. */
  1357. bool endsWithIgnoreCase (const tchar* const text) const throw();
  1358. /** Tests whether the string contains another substring.
  1359. Uses a case-sensitive comparison.
  1360. */
  1361. bool contains (const tchar* const text) const throw();
  1362. /** Tests whether the string contains a particular character.
  1363. Uses a case-sensitive comparison.
  1364. */
  1365. bool containsChar (const tchar character) const throw();
  1366. /** Tests whether the string contains another substring.
  1367. Uses a case-insensitive comparison.
  1368. */
  1369. bool containsIgnoreCase (const tchar* const text) const throw();
  1370. /** Tests whether the string contains another substring as a distict word.
  1371. @returns true if the string contains this word, surrounded by
  1372. non-alphanumeric characters
  1373. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1374. */
  1375. bool containsWholeWord (const tchar* const wordToLookFor) const throw();
  1376. /** Tests whether the string contains another substring as a distict word.
  1377. @returns true if the string contains this word, surrounded by
  1378. non-alphanumeric characters
  1379. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1380. */
  1381. bool containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1382. /** Finds an instance of another substring if it exists as a distict word.
  1383. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1384. then this will return the index of the start of the substring. If it isn't
  1385. found, then it will return -1
  1386. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1387. */
  1388. int indexOfWholeWord (const tchar* const wordToLookFor) const throw();
  1389. /** Finds an instance of another substring if it exists as a distict word.
  1390. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1391. then this will return the index of the start of the substring. If it isn't
  1392. found, then it will return -1
  1393. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1394. */
  1395. int indexOfWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw();
  1396. /** Looks for any of a set of characters in the string.
  1397. Uses a case-sensitive comparison.
  1398. @returns true if the string contains any of the characters from
  1399. the string that is passed in.
  1400. */
  1401. bool containsAnyOf (const tchar* const charactersItMightContain) const throw();
  1402. /** Looks for a set of characters in the string.
  1403. Uses a case-sensitive comparison.
  1404. @returns true if the all the characters in the string are also found in the
  1405. string that is passed in.
  1406. */
  1407. bool containsOnly (const tchar* const charactersItMightContain) const throw();
  1408. /** Returns true if this string contains any non-whitespace characters.
  1409. This will return false if the string contains only whitespace characters, or
  1410. if it's empty.
  1411. It is equivalent to calling "myString.trim().isNotEmpty()".
  1412. */
  1413. bool containsNonWhitespaceChars() const throw();
  1414. /** Returns true if the string matches this simple wildcard expression.
  1415. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1416. This isn't a full-blown regex though! The only wildcard characters supported
  1417. are "*" and "?". It's mainly intended for filename pattern matching.
  1418. */
  1419. bool matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw();
  1420. // Substring location methods..
  1421. /** Searches for a character inside this string.
  1422. Uses a case-sensitive comparison.
  1423. @returns the index of the first occurrence of the character in this
  1424. string, or -1 if it's not found.
  1425. */
  1426. int indexOfChar (const tchar characterToLookFor) const throw();
  1427. /** Searches for a character inside this string.
  1428. Uses a case-sensitive comparison.
  1429. @param startIndex the index from which the search should proceed
  1430. @param characterToLookFor the character to look for
  1431. @returns the index of the first occurrence of the character in this
  1432. string, or -1 if it's not found.
  1433. */
  1434. int indexOfChar (const int startIndex, const tchar characterToLookFor) const throw();
  1435. /** Returns the index of the first character that matches one of the characters
  1436. passed-in to this method.
  1437. This scans the string, beginning from the startIndex supplied, and if it finds
  1438. a character that appears in the string charactersToLookFor, it returns its index.
  1439. If none of these characters are found, it returns -1.
  1440. If ignoreCase is true, the comparison will be case-insensitive.
  1441. @see indexOfChar, lastIndexOfAnyOf
  1442. */
  1443. int indexOfAnyOf (const tchar* const charactersToLookFor,
  1444. const int startIndex = 0,
  1445. const bool ignoreCase = false) const throw();
  1446. /** Searches for a substring within this string.
  1447. Uses a case-sensitive comparison.
  1448. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1449. */
  1450. int indexOf (const tchar* const text) const throw();
  1451. /** Searches for a substring within this string.
  1452. Uses a case-sensitive comparison.
  1453. @param startIndex the index from which the search should proceed
  1454. @param textToLookFor the string to search for
  1455. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1456. */
  1457. int indexOf (const int startIndex,
  1458. const tchar* const textToLookFor) const throw();
  1459. /** Searches for a substring within this string.
  1460. Uses a case-insensitive comparison.
  1461. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1462. */
  1463. int indexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1464. /** Searches for a substring within this string.
  1465. Uses a case-insensitive comparison.
  1466. @param startIndex the index from which the search should proceed
  1467. @param textToLookFor the string to search for
  1468. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1469. */
  1470. int indexOfIgnoreCase (const int startIndex,
  1471. const tchar* const textToLookFor) const throw();
  1472. /** Searches for a character inside this string (working backwards from the end of the string).
  1473. Uses a case-sensitive comparison.
  1474. @returns the index of the last occurrence of the character in this
  1475. string, or -1 if it's not found.
  1476. */
  1477. int lastIndexOfChar (const tchar character) const throw();
  1478. /** Searches for a substring inside this string (working backwards from the end of the string).
  1479. Uses a case-sensitive comparison.
  1480. @returns the index of the start of the last occurrence of the
  1481. substring within this string, or -1 if it's not found.
  1482. */
  1483. int lastIndexOf (const tchar* const textToLookFor) const throw();
  1484. /** Searches for a substring inside this string (working backwards from the end of the string).
  1485. Uses a case-insensitive comparison.
  1486. @returns the index of the start of the last occurrence of the
  1487. substring within this string, or -1 if it's not found.
  1488. */
  1489. int lastIndexOfIgnoreCase (const tchar* const textToLookFor) const throw();
  1490. /** Returns the index of the last character in this string that matches one of the
  1491. characters passed-in to this method.
  1492. This scans the string backwards, starting from its end, and if it finds
  1493. a character that appears in the string charactersToLookFor, it returns its index.
  1494. If none of these characters are found, it returns -1.
  1495. If ignoreCase is true, the comparison will be case-insensitive.
  1496. @see lastIndexOf, indexOfAnyOf
  1497. */
  1498. int lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  1499. const bool ignoreCase = false) const throw();
  1500. // Substring extraction and manipulation methods..
  1501. /** Returns the character at this index in the string.
  1502. No checks are made to see if the index is within a valid range, so be careful!
  1503. */
  1504. inline const tchar& operator[] (const int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text->text [index]; }
  1505. /** Returns a character from the string such that it can also be altered.
  1506. This can be used as a way of easily changing characters in the string.
  1507. Note that the index passed-in is not checked to see whether it's in-range, so
  1508. be careful when using this.
  1509. */
  1510. tchar& operator[] (const int index) throw();
  1511. /** Returns the final character of the string.
  1512. If the string is empty this will return 0.
  1513. */
  1514. tchar getLastCharacter() const throw();
  1515. /** Returns a subsection of the string.
  1516. If the range specified is beyond the limits of the string, as much as
  1517. possible is returned.
  1518. @param startIndex the index of the start of the substring needed
  1519. @param endIndex all characters from startIndex up to (but not including)
  1520. this index are returned
  1521. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1522. */
  1523. const String substring (int startIndex,
  1524. int endIndex) const throw();
  1525. /** Returns a section of the string, starting from a given position.
  1526. @param startIndex the first character to include. If this is beyond the end
  1527. of the string, an empty string is returned. If it is zero or
  1528. less, the whole string is returned.
  1529. @returns the substring from startIndex up to the end of the string
  1530. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1531. */
  1532. const String substring (const int startIndex) const throw();
  1533. /** Returns a version of this string with a number of characters removed
  1534. from the end.
  1535. @param numberToDrop the number of characters to drop from the end of the
  1536. string. If this is greater than the length of the string,
  1537. an empty string will be returned. If zero or less, the
  1538. original string will be returned.
  1539. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1540. */
  1541. const String dropLastCharacters (const int numberToDrop) const throw();
  1542. /** Returns a number of characters from the end of the string.
  1543. This returns the last numCharacters characters from the end of the string. If the
  1544. string is shorter than numCharacters, the whole string is returned.
  1545. @see substring, dropLastCharacters, getLastCharacter
  1546. */
  1547. const String getLastCharacters (const int numCharacters) const throw();
  1548. /** Returns a section of the string starting from a given substring.
  1549. This will search for the first occurrence of the given substring, and
  1550. return the section of the string starting from the point where this is
  1551. found (optionally not including the substring itself).
  1552. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1553. fromFirstOccurrenceOf ("34", false) would return "56".
  1554. If the substring isn't found, the method will return an empty string.
  1555. If ignoreCase is true, the comparison will be case-insensitive.
  1556. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1557. */
  1558. const String fromFirstOccurrenceOf (const tchar* const substringToStartFrom,
  1559. const bool includeSubStringInResult,
  1560. const bool ignoreCase) const throw();
  1561. /** Returns a section of the string starting from the last occurrence of a given substring.
  1562. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1563. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1564. return the whole of the original string.
  1565. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1566. */
  1567. const String fromLastOccurrenceOf (const tchar* const substringToFind,
  1568. const bool includeSubStringInResult,
  1569. const bool ignoreCase) const throw();
  1570. /** Returns the start of this string, up to the first occurrence of a substring.
  1571. This will search for the first occurrence of a given substring, and then
  1572. return a copy of the string, up to the position of this substring,
  1573. optionally including or excluding the substring itself in the result.
  1574. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1575. upTo ("34", true) would return "1234".
  1576. If the substring isn't found, this will return the whole of the original string.
  1577. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1578. */
  1579. const String upToFirstOccurrenceOf (const tchar* const substringToEndWith,
  1580. const bool includeSubStringInResult,
  1581. const bool ignoreCase) const throw();
  1582. /** Returns the start of this string, up to the last occurrence of a substring.
  1583. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1584. If the substring isn't found, this will return an empty string.
  1585. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1586. */
  1587. const String upToLastOccurrenceOf (const tchar* substringToFind,
  1588. const bool includeSubStringInResult,
  1589. const bool ignoreCase) const throw();
  1590. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1591. const String trim() const throw();
  1592. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1593. const String trimStart() const throw();
  1594. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1595. const String trimEnd() const throw();
  1596. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1597. Characters are removed from the start of the string until it finds one that is not in the
  1598. specified set, and then it stops.
  1599. @param charactersToTrim the set of characters to remove. This must not be null.
  1600. @see trim, trimStart, trimCharactersAtEnd
  1601. */
  1602. const String trimCharactersAtStart (const tchar* charactersToTrim) const throw();
  1603. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1604. Characters are removed from the end of the string until it finds one that is not in the
  1605. specified set, and then it stops.
  1606. @param charactersToTrim the set of characters to remove. This must not be null.
  1607. @see trim, trimEnd, trimCharactersAtStart
  1608. */
  1609. const String trimCharactersAtEnd (const tchar* charactersToTrim) const throw();
  1610. /** Returns an upper-case version of this string. */
  1611. const String toUpperCase() const throw();
  1612. /** Returns an lower-case version of this string. */
  1613. const String toLowerCase() const throw();
  1614. /** Replaces a sub-section of the string with another string.
  1615. This will return a copy of this string, with a set of characters
  1616. from startIndex to startIndex + numCharsToReplace removed, and with
  1617. a new string inserted in their place.
  1618. Note that this is a const method, and won't alter the string itself.
  1619. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1620. it will be constrained to a valid range.
  1621. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1622. characters will be taken out.
  1623. @param stringToInsert the new string to insert at startIndex after the characters have been
  1624. removed.
  1625. */
  1626. const String replaceSection (int startIndex,
  1627. int numCharactersToReplace,
  1628. const tchar* const stringToInsert) const throw();
  1629. /** Replaces all occurrences of a substring with another string.
  1630. Returns a copy of this string, with any occurrences of stringToReplace
  1631. swapped for stringToInsertInstead.
  1632. Note that this is a const method, and won't alter the string itself.
  1633. */
  1634. const String replace (const tchar* const stringToReplace,
  1635. const tchar* const stringToInsertInstead,
  1636. const bool ignoreCase = false) const throw();
  1637. /** Returns a string with all occurrences of a character replaced with a different one. */
  1638. const String replaceCharacter (const tchar characterToReplace,
  1639. const tchar characterToInsertInstead) const throw();
  1640. /** Replaces a set of characters with another set.
  1641. Returns a string in which each character from charactersToReplace has been replaced
  1642. by the character at the equivalent position in newCharacters (so the two strings
  1643. passed in must be the same length).
  1644. e.g. translate ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1645. Note that this is a const method, and won't affect the string itself.
  1646. */
  1647. const String replaceCharacters (const String& charactersToReplace,
  1648. const tchar* const charactersToInsertInstead) const throw();
  1649. /** Returns a version of this string that only retains a fixed set of characters.
  1650. This will return a copy of this string, omitting any characters which are not
  1651. found in the string passed-in.
  1652. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1653. Note that this is a const method, and won't alter the string itself.
  1654. */
  1655. const String retainCharacters (const tchar* const charactersToRetain) const throw();
  1656. /** Returns a version of this string with a set of characters removed.
  1657. This will return a copy of this string, omitting any characters which are
  1658. found in the string passed-in.
  1659. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1660. Note that this is a const method, and won't alter the string itself.
  1661. */
  1662. const String removeCharacters (const tchar* const charactersToRemove) const throw();
  1663. /** Returns a section from the start of the string that only contains a certain set of characters.
  1664. This returns the leftmost section of the string, up to (and not including) the
  1665. first character that doesn't appear in the string passed in.
  1666. */
  1667. const String initialSectionContainingOnly (const tchar* const permittedCharacters) const throw();
  1668. /** Returns a section from the start of the string that only contains a certain set of characters.
  1669. This returns the leftmost section of the string, up to (and not including) the
  1670. first character that occurs in the string passed in.
  1671. */
  1672. const String initialSectionNotContaining (const tchar* const charactersToStopAt) const throw();
  1673. /** Checks whether the string might be in quotation marks.
  1674. @returns true if the string begins with a quote character (either a double or single quote).
  1675. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1676. @see unquoted, quoted
  1677. */
  1678. bool isQuotedString() const throw();
  1679. /** Removes quotation marks from around the string, (if there are any).
  1680. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1681. at the ends of the string are not affected. If there aren't any quotes, the original string
  1682. is returned.
  1683. Note that this is a const method, and won't alter the string itself.
  1684. @see isQuotedString, quoted
  1685. */
  1686. const String unquoted() const throw();
  1687. /** Adds quotation marks around a string.
  1688. This will return a copy of the string with a quote at the start and end, (but won't
  1689. add the quote if there's already one there, so it's safe to call this on strings that
  1690. may already have quotes around them).
  1691. Note that this is a const method, and won't alter the string itself.
  1692. @param quoteCharacter the character to add at the start and end
  1693. @see isQuotedString, unquoted
  1694. */
  1695. const String quoted (const tchar quoteCharacter = JUCE_T('"')) const throw();
  1696. /** Writes text into this string, using printf style-arguments.
  1697. This will replace the contents of the string with the output of this
  1698. formatted printf.
  1699. Note that using the %s token with a juce string is probably a bad idea, as
  1700. this may expect differect encodings on different platforms.
  1701. @see formatted
  1702. */
  1703. void printf (const tchar* const format, ...) throw();
  1704. /** Returns a string, created using arguments in the style of printf.
  1705. This will return a string which is the result of a sprintf using the
  1706. arguments passed-in.
  1707. Note that using the %s token with a juce string is probably a bad idea, as
  1708. this may expect differect encodings on different platforms.
  1709. @see printf, vprintf
  1710. */
  1711. static const String formatted (const tchar* const format, ...) throw();
  1712. /** Writes text into this string, using a printf style, but taking a va_list argument.
  1713. This will replace the contents of the string with the output of this
  1714. formatted printf. Used by other methods, this is public in case it's
  1715. useful for other purposes where you want to pass a va_list through directly.
  1716. Note that using the %s token with a juce string is probably a bad idea, as
  1717. this may expect differect encodings on different platforms.
  1718. @see printf, formatted
  1719. */
  1720. void vprintf (const tchar* const format, va_list& args) throw();
  1721. /** Creates a string which is a version of a string repeated and joined together.
  1722. @param stringToRepeat the string to repeat
  1723. @param numberOfTimesToRepeat how many times to repeat it
  1724. */
  1725. static const String repeatedString (const tchar* const stringToRepeat,
  1726. int numberOfTimesToRepeat) throw();
  1727. /** Creates a string from data in an unknown format.
  1728. This looks at some binary data and tries to guess whether it's Unicode
  1729. or 8-bit characters, then returns a string that represents it correctly.
  1730. Should be able to handle Unicode endianness correctly, by looking at
  1731. the first two bytes.
  1732. */
  1733. static const String createStringFromData (const void* const data,
  1734. const int size) throw();
  1735. // Numeric conversions..
  1736. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1737. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1738. */
  1739. explicit String (const int decimalInteger) throw();
  1740. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1741. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1742. */
  1743. explicit String (const unsigned int decimalInteger) throw();
  1744. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1745. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1746. */
  1747. explicit String (const short decimalInteger) throw();
  1748. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1749. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1750. */
  1751. explicit String (const unsigned short decimalInteger) throw();
  1752. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1753. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1754. */
  1755. explicit String (const int64 largeIntegerValue) throw();
  1756. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1757. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1758. */
  1759. explicit String (const uint64 largeIntegerValue) throw();
  1760. /** Creates a string representing this floating-point number.
  1761. @param floatValue the value to convert to a string
  1762. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1763. decimal places, and will not use exponent notation. If 0 or
  1764. less, it will use exponent notation if necessary.
  1765. @see getDoubleValue, getIntValue
  1766. */
  1767. explicit String (const float floatValue,
  1768. const int numberOfDecimalPlaces = 0) throw();
  1769. /** Creates a string representing this floating-point number.
  1770. @param doubleValue the value to convert to a string
  1771. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1772. decimal places, and will not use exponent notation. If 0 or
  1773. less, it will use exponent notation if necessary.
  1774. @see getFloatValue, getIntValue
  1775. */
  1776. explicit String (const double doubleValue,
  1777. const int numberOfDecimalPlaces = 0) throw();
  1778. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1779. @returns the value of the string as a 32 bit signed base-10 integer.
  1780. @see getTrailingIntValue, getHexValue32, getHexValue64
  1781. */
  1782. int getIntValue() const throw();
  1783. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1784. @returns the value of the string as a 64 bit signed base-10 integer.
  1785. */
  1786. int64 getLargeIntValue() const throw();
  1787. /** Parses a decimal number from the end of the string.
  1788. This will look for a value at the end of the string.
  1789. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1790. Negative numbers are not handled, so "xyz-5" returns 5.
  1791. @see getIntValue
  1792. */
  1793. int getTrailingIntValue() const throw();
  1794. /** Parses this string as a floating point number.
  1795. @returns the value of the string as a 32-bit floating point value.
  1796. @see getDoubleValue
  1797. */
  1798. float getFloatValue() const throw();
  1799. /** Parses this string as a floating point number.
  1800. @returns the value of the string as a 64-bit floating point value.
  1801. @see getFloatValue
  1802. */
  1803. double getDoubleValue() const throw();
  1804. /** Parses the string as a hexadecimal number.
  1805. Non-hexadecimal characters in the string are ignored.
  1806. If the string contains too many characters, then the lowest significant
  1807. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1808. @returns a 32-bit number which is the value of the string in hex.
  1809. */
  1810. int getHexValue32() const throw();
  1811. /** Parses the string as a hexadecimal number.
  1812. Non-hexadecimal characters in the string are ignored.
  1813. If the string contains too many characters, then the lowest significant
  1814. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1815. @returns a 64-bit number which is the value of the string in hex.
  1816. */
  1817. int64 getHexValue64() const throw();
  1818. /** Creates a string representing this 32-bit value in hexadecimal. */
  1819. static const String toHexString (const int number) throw();
  1820. /** Creates a string representing this 64-bit value in hexadecimal. */
  1821. static const String toHexString (const int64 number) throw();
  1822. /** Creates a string representing this 16-bit value in hexadecimal. */
  1823. static const String toHexString (const short number) throw();
  1824. /** Creates a string containing a hex dump of a block of binary data.
  1825. @param data the binary data to use as input
  1826. @param size how many bytes of data to use
  1827. @param groupSize how many bytes are grouped together before inserting a
  1828. space into the output. e.g. group size 0 has no spaces,
  1829. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1830. like "bea1 c2ff".
  1831. */
  1832. static const String toHexString (const unsigned char* data,
  1833. const int size,
  1834. const int groupSize = 1) throw();
  1835. // Casting to character arrays..
  1836. #if JUCE_STRINGS_ARE_UNICODE
  1837. /** Returns a version of this string using the default 8-bit system encoding.
  1838. Because it returns a reference to the string's internal data, the pointer
  1839. that is returned must not be stored anywhere, as it can be deleted whenever the
  1840. string changes.
  1841. */
  1842. operator const char*() const throw();
  1843. /** Returns a unicode version of this string.
  1844. Because it returns a reference to the string's internal data, the pointer
  1845. that is returned must not be stored anywhere, as it can be deleted whenever the
  1846. string changes.
  1847. */
  1848. inline operator const juce_wchar*() const throw() { return text->text; }
  1849. #else
  1850. /** Returns a version of this string using the default 8-bit system encoding.
  1851. Because it returns a reference to the string's internal data, the pointer
  1852. that is returned must not be stored anywhere, as it can be deleted whenever the
  1853. string changes.
  1854. */
  1855. inline operator const char*() const throw() { return text->text; }
  1856. /** Returns a unicode version of this string.
  1857. Because it returns a reference to the string's internal data, the pointer
  1858. that is returned must not be stored anywhere, as it can be deleted whenever the
  1859. string changes.
  1860. */
  1861. operator const juce_wchar*() const throw();
  1862. #endif
  1863. /** Copies the string to a buffer.
  1864. @param destBuffer the place to copy it to
  1865. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1866. not including the tailing zero, so this shouldn't be
  1867. larger than the size of your destination buffer - 1
  1868. */
  1869. void copyToBuffer (char* const destBuffer,
  1870. const int maxCharsToCopy) const throw();
  1871. /** Copies the string to a unicode buffer.
  1872. @param destBuffer the place to copy it to
  1873. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1874. not including the tailing zero, so this shouldn't be
  1875. larger than the size of your destination buffer - 1
  1876. */
  1877. void copyToBuffer (juce_wchar* const destBuffer,
  1878. const int maxCharsToCopy) const throw();
  1879. /** Copies the string to a buffer as UTF-8 characters.
  1880. Returns the number of bytes copied to the buffer, including the terminating null
  1881. character.
  1882. @param destBuffer the place to copy it to; if this is a null pointer,
  1883. the method just returns the number of bytes required
  1884. (including the terminating null character).
  1885. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1886. string won't fit, it'll put in as many as it can while
  1887. still allowing for a terminating null char at the end,
  1888. and will return the number of bytes that were actually
  1889. used. If this value is < 0, no limit is used.
  1890. */
  1891. int copyToUTF8 (uint8* const destBuffer, const int maxBufferSizeBytes = 0x7fffffff) const throw();
  1892. /** Returns a pointer to a UTF-8 version of this string.
  1893. Because it returns a reference to the string's internal data, the pointer
  1894. that is returned must not be stored anywhere, as it can be deleted whenever the
  1895. string changes.
  1896. */
  1897. const char* toUTF8() const throw();
  1898. /** Creates a String from a UTF-8 encoded buffer.
  1899. If the size is < 0, it'll keep reading until it hits a zero.
  1900. */
  1901. static const String fromUTF8 (const uint8* const utf8buffer,
  1902. int bufferSizeBytes = -1) throw();
  1903. /** Increases the string's internally allocated storage.
  1904. Although the string's contents won't be affected by this call, it will
  1905. increase the amount of memory allocated internally for the string to grow into.
  1906. If you're about to make a large number of calls to methods such
  1907. as += or <<, it's more efficient to preallocate enough extra space
  1908. beforehand, so that these methods won't have to keep resizing the string
  1909. to append the extra characters.
  1910. @param numCharsNeeded the number of characters to allocate storage for. If this
  1911. value is less than the currently allocated size, it will
  1912. have no effect.
  1913. */
  1914. void preallocateStorage (const int numCharsNeeded) throw();
  1915. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1916. private:
  1917. struct InternalRefCountedStringHolder
  1918. {
  1919. int refCount;
  1920. int allocatedNumChars;
  1921. #if JUCE_STRINGS_ARE_UNICODE
  1922. wchar_t text[1];
  1923. #else
  1924. char text[1];
  1925. #endif
  1926. };
  1927. InternalRefCountedStringHolder* text;
  1928. static InternalRefCountedStringHolder emptyString;
  1929. // internal constructor that preallocates a certain amount of memory
  1930. String (const int numChars, const int dummyVariable) throw();
  1931. void deleteInternal() throw();
  1932. void createInternal (const int numChars) throw();
  1933. void createInternal (const tchar* const text, const tchar* const textEnd) throw();
  1934. void appendInternal (const tchar* const text, const int numExtraChars) throw();
  1935. void doubleToStringWithDecPlaces (double n, int numDecPlaces) throw();
  1936. void dupeInternalIfMultiplyReferenced() throw();
  1937. };
  1938. /** Global operator to allow a String to be appended to a string literal.
  1939. This allows the use of expressions such as "abc" + String (x)
  1940. @see String
  1941. */
  1942. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  1943. const String& string2) throw();
  1944. /** Global operator to allow a String to be appended to a string literal.
  1945. This allows the use of expressions such as "abc" + String (x)
  1946. @see String
  1947. */
  1948. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  1949. const String& string2) throw();
  1950. #endif // __JUCE_STRING_JUCEHEADER__
  1951. /********* End of inlined file: juce_String.h *********/
  1952. /**
  1953. Acts as an application-wide logging class.
  1954. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  1955. method and this will then be used by all calls to writeToLog.
  1956. The logger class also contains methods for writing messages to the debugger's
  1957. output stream.
  1958. @see FileLogger
  1959. */
  1960. class JUCE_API Logger
  1961. {
  1962. public:
  1963. /** Destructor. */
  1964. virtual ~Logger();
  1965. /** Sets the current logging class to use.
  1966. Note that the object passed in won't be deleted when no longer needed.
  1967. A null pointer can be passed-in to disable any logging.
  1968. If deleteOldLogger is set to true, the existing logger will be
  1969. deleted (if there is one).
  1970. */
  1971. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  1972. const bool deleteOldLogger = false);
  1973. /** Writes a string to the current logger.
  1974. This will pass the string to the logger's logMessage() method if a logger
  1975. has been set.
  1976. @see logMessage
  1977. */
  1978. static void JUCE_CALLTYPE writeToLog (const String& message);
  1979. /** Writes a message to the standard error stream.
  1980. This can be called directly, or by using the DBG() macro in
  1981. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1982. */
  1983. static void JUCE_CALLTYPE outputDebugString (const String& text) throw();
  1984. /** Writes a message to the standard error stream.
  1985. This can be called directly, or by using the DBG_PRINTF() macro in
  1986. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  1987. */
  1988. static void JUCE_CALLTYPE outputDebugPrintf (const tchar* format, ...) throw();
  1989. protected:
  1990. Logger();
  1991. /** This is overloaded by subclasses to implement custom logging behaviour.
  1992. @see setCurrentLogger
  1993. */
  1994. virtual void logMessage (const String& message) = 0;
  1995. };
  1996. #endif // __JUCE_LOGGER_JUCEHEADER__
  1997. /********* End of inlined file: juce_Logger.h *********/
  1998. END_JUCE_NAMESPACE
  1999. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2000. /********* End of inlined file: juce_StandardHeader.h *********/
  2001. BEGIN_JUCE_NAMESPACE
  2002. #if JUCE_MSVC
  2003. // this is set explicitly in case the app is using a different packing size.
  2004. #pragma pack (push, 8)
  2005. #pragma warning (push)
  2006. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2007. #endif
  2008. #if JUCE_MAC || JUCE_IPHONE
  2009. #pragma align=natural
  2010. #endif
  2011. #define JUCE_PUBLIC_INCLUDES
  2012. // this is where all the class header files get brought in..
  2013. /********* Start of inlined file: juce_core_includes.h *********/
  2014. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2015. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2016. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2017. /********* Start of inlined file: juce_Array.h *********/
  2018. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2019. #define __JUCE_ARRAY_JUCEHEADER__
  2020. /********* Start of inlined file: juce_ArrayAllocationBase.h *********/
  2021. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2022. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2023. /** The default size of chunk in which arrays increase their storage.
  2024. Used by ArrayAllocationBase and its subclasses.
  2025. */
  2026. const int juceDefaultArrayGranularity = 8;
  2027. /**
  2028. Implements some basic array storage allocation functions.
  2029. This class isn't really for public use - it's used by the other
  2030. array classes, but might come in handy for some purposes.
  2031. @see Array, OwnedArray, ReferenceCountedArray
  2032. */
  2033. template <class ElementType>
  2034. class ArrayAllocationBase
  2035. {
  2036. public:
  2037. /** Creates an empty array.
  2038. @param granularity_ this is the size of increment by which the internal storage
  2039. will be increased.
  2040. */
  2041. ArrayAllocationBase (const int granularity_) throw()
  2042. : elements (0),
  2043. numAllocated (0),
  2044. granularity (granularity_)
  2045. {
  2046. jassert (granularity > 0);
  2047. }
  2048. /** Destructor. */
  2049. ~ArrayAllocationBase()
  2050. {
  2051. delete[] elements;
  2052. }
  2053. /** Changes the amount of storage allocated.
  2054. This will retain any data currently held in the array, and either add or
  2055. remove extra space at the end.
  2056. @param numElements the number of elements that are needed
  2057. */
  2058. void setAllocatedSize (const int numElements) throw()
  2059. {
  2060. if (numAllocated != numElements)
  2061. {
  2062. if (numElements > 0)
  2063. {
  2064. ElementType* const newElements = new ElementType [numElements];
  2065. const int itemsToRetain = jmin (numElements, numAllocated);
  2066. for (int i = 0; i < itemsToRetain; ++i)
  2067. newElements[i] = elements[i];
  2068. delete[] elements;
  2069. elements = newElements;
  2070. }
  2071. else if (elements != 0)
  2072. {
  2073. delete[] elements;
  2074. elements = 0;
  2075. }
  2076. numAllocated = numElements;
  2077. }
  2078. }
  2079. /** Increases the amount of storage allocated if it is less than a given amount.
  2080. This will retain any data currently held in the array, but will add
  2081. extra space at the end to make sure there it's at least as big as the size
  2082. passed in. If it's already bigger, no action is taken.
  2083. @param minNumElements the minimum number of elements that are needed
  2084. */
  2085. void ensureAllocatedSize (int minNumElements) throw()
  2086. {
  2087. if (minNumElements > numAllocated)
  2088. {
  2089. // for arrays with small granularity that get big, start
  2090. // increasing the size in bigger jumps
  2091. if (minNumElements > (granularity << 6))
  2092. {
  2093. minNumElements += (minNumElements / granularity);
  2094. if (minNumElements > (granularity << 8))
  2095. minNumElements += granularity << 6;
  2096. else
  2097. minNumElements += granularity << 5;
  2098. }
  2099. setAllocatedSize (granularity * (minNumElements / granularity + 1));
  2100. }
  2101. }
  2102. ElementType* elements;
  2103. int numAllocated, granularity;
  2104. private:
  2105. ArrayAllocationBase (const ArrayAllocationBase&);
  2106. const ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2107. };
  2108. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2109. /********* End of inlined file: juce_ArrayAllocationBase.h *********/
  2110. /********* Start of inlined file: juce_ElementComparator.h *********/
  2111. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2112. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2113. /**
  2114. Sorts a range of elements in an array.
  2115. The comparator object that is passed-in must define a public method with the following
  2116. signature:
  2117. @code
  2118. int compareElements (ElementType first, ElementType second);
  2119. @endcode
  2120. ..and this method must return:
  2121. - a value of < 0 if the first comes before the second
  2122. - a value of 0 if the two objects are equivalent
  2123. - a value of > 0 if the second comes before the first
  2124. To improve performance, the compareElements() method can be declared as static or const.
  2125. @param comparator an object which defines a compareElements() method
  2126. @param array the array to sort
  2127. @param firstElement the index of the first element of the range to be sorted
  2128. @param lastElement the index of the last element in the range that needs
  2129. sorting (this is inclusive)
  2130. @param retainOrderOfEquivalentItems if true, the order of items that the
  2131. comparator deems the same will be maintained - this will be
  2132. a slower algorithm than if they are allowed to be moved around.
  2133. @see sortArrayRetainingOrder
  2134. */
  2135. template <class ElementType, class ElementComparator>
  2136. static void sortArray (ElementComparator& comparator,
  2137. ElementType* const array,
  2138. int firstElement,
  2139. int lastElement,
  2140. const bool retainOrderOfEquivalentItems)
  2141. {
  2142. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2143. // avoids getting warning messages about the parameter being unused
  2144. if (lastElement > firstElement)
  2145. {
  2146. if (retainOrderOfEquivalentItems)
  2147. {
  2148. for (int i = firstElement; i < lastElement; ++i)
  2149. {
  2150. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2151. {
  2152. const ElementType temp = array [i];
  2153. array [i] = array[i + 1];
  2154. array [i + 1] = temp;
  2155. if (i > firstElement)
  2156. i -= 2;
  2157. }
  2158. }
  2159. }
  2160. else
  2161. {
  2162. int fromStack[30], toStack[30];
  2163. int stackIndex = 0;
  2164. for (;;)
  2165. {
  2166. const int size = (lastElement - firstElement) + 1;
  2167. if (size <= 8)
  2168. {
  2169. int j = lastElement;
  2170. int maxIndex;
  2171. while (j > firstElement)
  2172. {
  2173. maxIndex = firstElement;
  2174. for (int k = firstElement + 1; k <= j; ++k)
  2175. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2176. maxIndex = k;
  2177. const ElementType temp = array [maxIndex];
  2178. array [maxIndex] = array[j];
  2179. array [j] = temp;
  2180. --j;
  2181. }
  2182. }
  2183. else
  2184. {
  2185. const int mid = firstElement + (size >> 1);
  2186. ElementType temp = array [mid];
  2187. array [mid] = array [firstElement];
  2188. array [firstElement] = temp;
  2189. int i = firstElement;
  2190. int j = lastElement + 1;
  2191. for (;;)
  2192. {
  2193. while (++i <= lastElement
  2194. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2195. {}
  2196. while (--j > firstElement
  2197. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2198. {}
  2199. if (j < i)
  2200. break;
  2201. temp = array[i];
  2202. array[i] = array[j];
  2203. array[j] = temp;
  2204. }
  2205. temp = array [firstElement];
  2206. array [firstElement] = array[j];
  2207. array [j] = temp;
  2208. if (j - 1 - firstElement >= lastElement - i)
  2209. {
  2210. if (firstElement + 1 < j)
  2211. {
  2212. fromStack [stackIndex] = firstElement;
  2213. toStack [stackIndex] = j - 1;
  2214. ++stackIndex;
  2215. }
  2216. if (i < lastElement)
  2217. {
  2218. firstElement = i;
  2219. continue;
  2220. }
  2221. }
  2222. else
  2223. {
  2224. if (i < lastElement)
  2225. {
  2226. fromStack [stackIndex] = i;
  2227. toStack [stackIndex] = lastElement;
  2228. ++stackIndex;
  2229. }
  2230. if (firstElement + 1 < j)
  2231. {
  2232. lastElement = j - 1;
  2233. continue;
  2234. }
  2235. }
  2236. }
  2237. if (--stackIndex < 0)
  2238. break;
  2239. jassert (stackIndex < numElementsInArray (fromStack));
  2240. firstElement = fromStack [stackIndex];
  2241. lastElement = toStack [stackIndex];
  2242. }
  2243. }
  2244. }
  2245. }
  2246. /**
  2247. Searches a sorted array of elements, looking for the index at which a specified value
  2248. should be inserted for it to be in the correct order.
  2249. The comparator object that is passed-in must define a public method with the following
  2250. signature:
  2251. @code
  2252. int compareElements (ElementType first, ElementType second);
  2253. @endcode
  2254. ..and this method must return:
  2255. - a value of < 0 if the first comes before the second
  2256. - a value of 0 if the two objects are equivalent
  2257. - a value of > 0 if the second comes before the first
  2258. To improve performance, the compareElements() method can be declared as static or const.
  2259. @param comparator an object which defines a compareElements() method
  2260. @param array the array to search
  2261. @param newElement the value that is going to be inserted
  2262. @param firstElement the index of the first element to search
  2263. @param lastElement the index of the last element in the range (this is non-inclusive)
  2264. */
  2265. template <class ElementType, class ElementComparator>
  2266. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2267. ElementType* const array,
  2268. const ElementType newElement,
  2269. int firstElement,
  2270. int lastElement)
  2271. {
  2272. jassert (firstElement <= lastElement);
  2273. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2274. // avoids getting warning messages about the parameter being unused
  2275. while (firstElement < lastElement)
  2276. {
  2277. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2278. {
  2279. ++firstElement;
  2280. break;
  2281. }
  2282. else
  2283. {
  2284. const int halfway = (firstElement + lastElement) >> 1;
  2285. if (halfway == firstElement)
  2286. {
  2287. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2288. ++firstElement;
  2289. break;
  2290. }
  2291. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2292. {
  2293. firstElement = halfway;
  2294. }
  2295. else
  2296. {
  2297. lastElement = halfway;
  2298. }
  2299. }
  2300. }
  2301. return firstElement;
  2302. }
  2303. /**
  2304. A simple ElementComparator class that can be used to sort an array of
  2305. integer primitive objects.
  2306. Example: @code
  2307. Array <int> myArray;
  2308. IntegerElementComparator<int> sorter;
  2309. myArray.sort (sorter);
  2310. @endcode
  2311. For floating point values, see the FloatElementComparator class instead.
  2312. @see FloatElementComparator, ElementComparator
  2313. */
  2314. template <class ElementType>
  2315. class IntegerElementComparator
  2316. {
  2317. public:
  2318. static int compareElements (const ElementType first,
  2319. const ElementType second) throw()
  2320. {
  2321. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2322. }
  2323. };
  2324. /**
  2325. A simple ElementComparator class that can be used to sort an array of numeric
  2326. double or floating point primitive objects.
  2327. Example: @code
  2328. Array <double> myArray;
  2329. FloatElementComparator<double> sorter;
  2330. myArray.sort (sorter);
  2331. @endcode
  2332. For integer values, see the IntegerElementComparator class instead.
  2333. @see IntegerElementComparator, ElementComparator
  2334. */
  2335. template <class ElementType>
  2336. class FloatElementComparator
  2337. {
  2338. public:
  2339. static int compareElements (const ElementType first,
  2340. const ElementType second) throw()
  2341. {
  2342. return (first < second) ? -1 : ((first == second) ? 0 : 1);
  2343. }
  2344. };
  2345. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2346. /********* End of inlined file: juce_ElementComparator.h *********/
  2347. /********* Start of inlined file: juce_CriticalSection.h *********/
  2348. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2349. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2350. /**
  2351. Prevents multiple threads from accessing shared objects at the same time.
  2352. @see ScopedLock, Thread, InterProcessLock
  2353. */
  2354. class JUCE_API CriticalSection
  2355. {
  2356. public:
  2357. /**
  2358. Creates a CriticalSection object
  2359. */
  2360. CriticalSection() throw();
  2361. /** Destroys a CriticalSection object.
  2362. If the critical section is deleted whilst locked, its subsequent behaviour
  2363. is unpredictable.
  2364. */
  2365. ~CriticalSection() throw();
  2366. /** Locks this critical section.
  2367. If the lock is currently held by another thread, this will wait until it
  2368. becomes free.
  2369. If the lock is already held by the caller thread, the method returns immediately.
  2370. @see exit, ScopedLock
  2371. */
  2372. void enter() const throw();
  2373. /** Attempts to lock this critical section without blocking.
  2374. This method behaves identically to CriticalSection::enter, except that the caller thread
  2375. does not wait if the lock is currently held by another thread but returns false immediately.
  2376. @returns false if the lock is currently held by another thread, true otherwise.
  2377. @see enter
  2378. */
  2379. bool tryEnter() const throw();
  2380. /** Releases the lock.
  2381. If the caller thread hasn't got the lock, this can have unpredictable results.
  2382. If the enter() method has been called multiple times by the thread, each
  2383. call must be matched by a call to exit() before other threads will be allowed
  2384. to take over the lock.
  2385. @see enter, ScopedLock
  2386. */
  2387. void exit() const throw();
  2388. juce_UseDebuggingNewOperator
  2389. private:
  2390. #if JUCE_WIN32
  2391. #if JUCE_64BIT
  2392. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2393. // block of memory here that's big enough to be used internally as a windows critical
  2394. // section object.
  2395. uint8 internal [44];
  2396. #else
  2397. uint8 internal [24];
  2398. #endif
  2399. #else
  2400. mutable pthread_mutex_t internal;
  2401. #endif
  2402. CriticalSection (const CriticalSection&);
  2403. const CriticalSection& operator= (const CriticalSection&);
  2404. };
  2405. /**
  2406. A class that can be used in place of a real CriticalSection object.
  2407. This is currently used by some templated array classes, and should get
  2408. optimised out by the compiler.
  2409. @see Array, OwnedArray, ReferenceCountedArray
  2410. */
  2411. class JUCE_API DummyCriticalSection
  2412. {
  2413. public:
  2414. forcedinline DummyCriticalSection() throw() {}
  2415. forcedinline ~DummyCriticalSection() throw() {}
  2416. forcedinline void enter() const throw() {}
  2417. forcedinline void exit() const throw() {}
  2418. };
  2419. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2420. /********* End of inlined file: juce_CriticalSection.h *********/
  2421. /**
  2422. Holds a list of primitive objects, such as ints, doubles, or pointers.
  2423. Examples of arrays are: Array<int> or Array<MyClass*>
  2424. Note that when holding pointers to objects, the array doesn't take any ownership
  2425. of the objects - for doing this, see the OwnedArray class or the ReferenceCountedArray class.
  2426. If you're using a class or struct as the element type, it must be
  2427. capable of being copied or moved with a straightforward memcpy, rather than
  2428. needing construction and destruction code.
  2429. For holding lists of strings, use the specialised class StringArray.
  2430. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2431. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2432. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2433. */
  2434. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  2435. class Array
  2436. {
  2437. public:
  2438. /** Creates an empty array.
  2439. @param granularity this is the size of increment by which the internal storage
  2440. used by the array will grow. Only change it from the default if you know the
  2441. array is going to be very big and needs to be able to grow efficiently.
  2442. */
  2443. Array (const int granularity = juceDefaultArrayGranularity) throw()
  2444. : data (granularity),
  2445. numUsed (0)
  2446. {
  2447. }
  2448. /** Creates a copy of another array.
  2449. @param other the array to copy
  2450. */
  2451. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2452. : data (other.data.granularity)
  2453. {
  2454. other.lockArray();
  2455. numUsed = other.numUsed;
  2456. data.setAllocatedSize (other.numUsed);
  2457. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  2458. other.unlockArray();
  2459. }
  2460. /** Initalises from a null-terminated C array of values.
  2461. @param values the array to copy from
  2462. */
  2463. Array (const ElementType* values) throw()
  2464. : data (juceDefaultArrayGranularity),
  2465. numUsed (0)
  2466. {
  2467. while (*values != 0)
  2468. add (*values++);
  2469. }
  2470. /** Initalises from a C array of values.
  2471. @param values the array to copy from
  2472. @param numValues the number of values in the array
  2473. */
  2474. Array (const ElementType* values, int numValues) throw()
  2475. : data (juceDefaultArrayGranularity),
  2476. numUsed (numValues)
  2477. {
  2478. data.setAllocatedSize (numValues);
  2479. memcpy (data.elements, values, numValues * sizeof (ElementType));
  2480. }
  2481. /** Destructor. */
  2482. ~Array() throw()
  2483. {
  2484. }
  2485. /** Copies another array.
  2486. @param other the array to copy
  2487. */
  2488. const Array <ElementType, TypeOfCriticalSectionToUse>& operator= (const Array <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2489. {
  2490. if (this != &other)
  2491. {
  2492. other.lockArray();
  2493. lock.enter();
  2494. data.granularity = other.data.granularity;
  2495. data.ensureAllocatedSize (other.size());
  2496. numUsed = other.numUsed;
  2497. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  2498. minimiseStorageOverheads();
  2499. lock.exit();
  2500. other.unlockArray();
  2501. }
  2502. return *this;
  2503. }
  2504. /** Compares this array to another one.
  2505. Two arrays are considered equal if they both contain the same set of
  2506. elements, in the same order.
  2507. @param other the other array to compare with
  2508. */
  2509. template <class OtherArrayType>
  2510. bool operator== (const OtherArrayType& other) const throw()
  2511. {
  2512. lock.enter();
  2513. if (numUsed != other.numUsed)
  2514. {
  2515. lock.exit();
  2516. return false;
  2517. }
  2518. for (int i = numUsed; --i >= 0;)
  2519. {
  2520. if (data.elements [i] != other.data.elements [i])
  2521. {
  2522. lock.exit();
  2523. return false;
  2524. }
  2525. }
  2526. lock.exit();
  2527. return true;
  2528. }
  2529. /** Compares this array to another one.
  2530. Two arrays are considered equal if they both contain the same set of
  2531. elements, in the same order.
  2532. @param other the other array to compare with
  2533. */
  2534. template <class OtherArrayType>
  2535. bool operator!= (const OtherArrayType& other) const throw()
  2536. {
  2537. return ! operator== (other);
  2538. }
  2539. /** Removes all elements from the array.
  2540. This will remove all the elements, and free any storage that the array is
  2541. using. To clear the array without freeing the storage, use the clearQuick()
  2542. method instead.
  2543. @see clearQuick
  2544. */
  2545. void clear() throw()
  2546. {
  2547. lock.enter();
  2548. data.setAllocatedSize (0);
  2549. numUsed = 0;
  2550. lock.exit();
  2551. }
  2552. /** Removes all elements from the array without freeing the array's allocated storage.
  2553. @see clear
  2554. */
  2555. void clearQuick() throw()
  2556. {
  2557. lock.enter();
  2558. numUsed = 0;
  2559. lock.exit();
  2560. }
  2561. /** Returns the current number of elements in the array.
  2562. */
  2563. inline int size() const throw()
  2564. {
  2565. return numUsed;
  2566. }
  2567. /** Returns one of the elements in the array.
  2568. If the index passed in is beyond the range of valid elements, this
  2569. will return zero.
  2570. If you're certain that the index will always be a valid element, you
  2571. can call getUnchecked() instead, which is faster.
  2572. @param index the index of the element being requested (0 is the first element in the array)
  2573. @see getUnchecked, getFirst, getLast
  2574. */
  2575. inline ElementType operator[] (const int index) const throw()
  2576. {
  2577. lock.enter();
  2578. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  2579. ? data.elements [index]
  2580. : ElementType();
  2581. lock.exit();
  2582. return result;
  2583. }
  2584. /** Returns one of the elements in the array, without checking the index passed in.
  2585. Unlike the operator[] method, this will try to return an element without
  2586. checking that the index is within the bounds of the array, so should only
  2587. be used when you're confident that it will always be a valid index.
  2588. @param index the index of the element being requested (0 is the first element in the array)
  2589. @see operator[], getFirst, getLast
  2590. */
  2591. inline ElementType getUnchecked (const int index) const throw()
  2592. {
  2593. lock.enter();
  2594. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2595. const ElementType result = data.elements [index];
  2596. lock.exit();
  2597. return result;
  2598. }
  2599. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2600. This is like getUnchecked, but returns a direct reference to the element, so that
  2601. you can alter it directly. Obviously this can be dangerous, so only use it when
  2602. absolutely necessary.
  2603. @param index the index of the element being requested (0 is the first element in the array)
  2604. @see operator[], getFirst, getLast
  2605. */
  2606. inline ElementType& getReference (const int index) const throw()
  2607. {
  2608. lock.enter();
  2609. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2610. ElementType& result = data.elements [index];
  2611. lock.exit();
  2612. return result;
  2613. }
  2614. /** Returns the first element in the array, or 0 if the array is empty.
  2615. @see operator[], getUnchecked, getLast
  2616. */
  2617. inline ElementType getFirst() const throw()
  2618. {
  2619. lock.enter();
  2620. const ElementType result = (numUsed > 0) ? data.elements [0]
  2621. : ElementType();
  2622. lock.exit();
  2623. return result;
  2624. }
  2625. /** Returns the last element in the array, or 0 if the array is empty.
  2626. @see operator[], getUnchecked, getFirst
  2627. */
  2628. inline ElementType getLast() const throw()
  2629. {
  2630. lock.enter();
  2631. const ElementType result = (numUsed > 0) ? data.elements [numUsed - 1]
  2632. : ElementType();
  2633. lock.exit();
  2634. return result;
  2635. }
  2636. /** Finds the index of the first element which matches the value passed in.
  2637. This will search the array for the given object, and return the index
  2638. of its first occurrence. If the object isn't found, the method will return -1.
  2639. @param elementToLookFor the value or object to look for
  2640. @returns the index of the object, or -1 if it's not found
  2641. */
  2642. int indexOf (const ElementType elementToLookFor) const throw()
  2643. {
  2644. int result = -1;
  2645. lock.enter();
  2646. const ElementType* e = data.elements;
  2647. for (int i = numUsed; --i >= 0;)
  2648. {
  2649. if (elementToLookFor == *e)
  2650. {
  2651. result = (int) (e - data.elements);
  2652. break;
  2653. }
  2654. ++e;
  2655. }
  2656. lock.exit();
  2657. return result;
  2658. }
  2659. /** Returns true if the array contains at least one occurrence of an object.
  2660. @param elementToLookFor the value or object to look for
  2661. @returns true if the item is found
  2662. */
  2663. bool contains (const ElementType elementToLookFor) const throw()
  2664. {
  2665. lock.enter();
  2666. const ElementType* e = data.elements;
  2667. int num = numUsed;
  2668. while (num >= 4)
  2669. {
  2670. if (*e == elementToLookFor
  2671. || *++e == elementToLookFor
  2672. || *++e == elementToLookFor
  2673. || *++e == elementToLookFor)
  2674. {
  2675. lock.exit();
  2676. return true;
  2677. }
  2678. num -= 4;
  2679. ++e;
  2680. }
  2681. while (num > 0)
  2682. {
  2683. if (elementToLookFor == *e)
  2684. {
  2685. lock.exit();
  2686. return true;
  2687. }
  2688. --num;
  2689. ++e;
  2690. }
  2691. lock.exit();
  2692. return false;
  2693. }
  2694. /** Appends a new element at the end of the array.
  2695. @param newElement the new object to add to the array
  2696. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  2697. */
  2698. void add (const ElementType newElement) throw()
  2699. {
  2700. lock.enter();
  2701. data.ensureAllocatedSize (numUsed + 1);
  2702. data.elements [numUsed++] = newElement;
  2703. lock.exit();
  2704. }
  2705. /** Inserts a new element into the array at a given position.
  2706. If the index is less than 0 or greater than the size of the array, the
  2707. element will be added to the end of the array.
  2708. Otherwise, it will be inserted into the array, moving all the later elements
  2709. along to make room.
  2710. @param indexToInsertAt the index at which the new element should be
  2711. inserted (pass in -1 to add it to the end)
  2712. @param newElement the new object to add to the array
  2713. @see add, addSorted, set
  2714. */
  2715. void insert (int indexToInsertAt, const ElementType newElement) throw()
  2716. {
  2717. lock.enter();
  2718. data.ensureAllocatedSize (numUsed + 1);
  2719. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2720. {
  2721. ElementType* const insertPos = data.elements + indexToInsertAt;
  2722. const int numberToMove = numUsed - indexToInsertAt;
  2723. if (numberToMove > 0)
  2724. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2725. *insertPos = newElement;
  2726. ++numUsed;
  2727. }
  2728. else
  2729. {
  2730. data.elements [numUsed++] = newElement;
  2731. }
  2732. lock.exit();
  2733. }
  2734. /** Inserts multiple copies of an element into the array at a given position.
  2735. If the index is less than 0 or greater than the size of the array, the
  2736. element will be added to the end of the array.
  2737. Otherwise, it will be inserted into the array, moving all the later elements
  2738. along to make room.
  2739. @param indexToInsertAt the index at which the new element should be inserted
  2740. @param newElement the new object to add to the array
  2741. @param numberOfTimesToInsertIt how many copies of the value to insert
  2742. @see insert, add, addSorted, set
  2743. */
  2744. void insertMultiple (int indexToInsertAt, const ElementType newElement,
  2745. int numberOfTimesToInsertIt) throw()
  2746. {
  2747. if (numberOfTimesToInsertIt > 0)
  2748. {
  2749. lock.enter();
  2750. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2751. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2752. {
  2753. ElementType* insertPos = data.elements + indexToInsertAt;
  2754. const int numberToMove = numUsed - indexToInsertAt;
  2755. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2756. numUsed += numberOfTimesToInsertIt;
  2757. while (--numberOfTimesToInsertIt >= 0)
  2758. *insertPos++ = newElement;
  2759. }
  2760. else
  2761. {
  2762. while (--numberOfTimesToInsertIt >= 0)
  2763. data.elements [numUsed++] = newElement;
  2764. }
  2765. lock.exit();
  2766. }
  2767. }
  2768. /** Inserts an array of values into this array at a given position.
  2769. If the index is less than 0 or greater than the size of the array, the
  2770. new elements will be added to the end of the array.
  2771. Otherwise, they will be inserted into the array, moving all the later elements
  2772. along to make room.
  2773. @param indexToInsertAt the index at which the first new element should be inserted
  2774. @param newElements the new values to add to the array
  2775. @param numberOfElements how many items are in the array
  2776. @see insert, add, addSorted, set
  2777. */
  2778. void insertArray (int indexToInsertAt,
  2779. const ElementType* newElements,
  2780. int numberOfElements) throw()
  2781. {
  2782. if (numberOfElements > 0)
  2783. {
  2784. lock.enter();
  2785. data.ensureAllocatedSize (numUsed + numberOfElements);
  2786. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2787. {
  2788. ElementType* insertPos = data.elements + indexToInsertAt;
  2789. const int numberToMove = numUsed - indexToInsertAt;
  2790. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  2791. numUsed += numberOfElements;
  2792. while (--numberOfElements >= 0)
  2793. *insertPos++ = *newElements++;
  2794. }
  2795. else
  2796. {
  2797. while (--numberOfElements >= 0)
  2798. data.elements [numUsed++] = *newElements++;
  2799. }
  2800. lock.exit();
  2801. }
  2802. }
  2803. /** Appends a new element at the end of the array as long as the array doesn't
  2804. already contain it.
  2805. If the array already contains an element that matches the one passed in, nothing
  2806. will be done.
  2807. @param newElement the new object to add to the array
  2808. */
  2809. void addIfNotAlreadyThere (const ElementType newElement) throw()
  2810. {
  2811. lock.enter();
  2812. if (! contains (newElement))
  2813. add (newElement);
  2814. lock.exit();
  2815. }
  2816. /** Replaces an element with a new value.
  2817. If the index is less than zero, this method does nothing.
  2818. If the index is beyond the end of the array, the item is added to the end of the array.
  2819. @param indexToChange the index whose value you want to change
  2820. @param newValue the new value to set for this index.
  2821. @see add, insert
  2822. */
  2823. void set (const int indexToChange,
  2824. const ElementType newValue) throw()
  2825. {
  2826. jassert (indexToChange >= 0);
  2827. if (indexToChange >= 0)
  2828. {
  2829. lock.enter();
  2830. if (indexToChange < numUsed)
  2831. {
  2832. data.elements [indexToChange] = newValue;
  2833. }
  2834. else
  2835. {
  2836. data.ensureAllocatedSize (numUsed + 1);
  2837. data.elements [numUsed++] = newValue;
  2838. }
  2839. lock.exit();
  2840. }
  2841. }
  2842. /** Replaces an element with a new value without doing any bounds-checking.
  2843. This just sets a value directly in the array's internal storage, so you'd
  2844. better make sure it's in range!
  2845. @param indexToChange the index whose value you want to change
  2846. @param newValue the new value to set for this index.
  2847. @see set, getUnchecked
  2848. */
  2849. void setUnchecked (const int indexToChange,
  2850. const ElementType newValue) throw()
  2851. {
  2852. lock.enter();
  2853. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  2854. data.elements [indexToChange] = newValue;
  2855. lock.exit();
  2856. }
  2857. /** Adds elements from an array to the end of this array.
  2858. @param elementsToAdd the array of elements to add
  2859. @param numElementsToAdd how many elements are in this other array
  2860. @see add
  2861. */
  2862. void addArray (const ElementType* elementsToAdd,
  2863. int numElementsToAdd) throw()
  2864. {
  2865. lock.enter();
  2866. if (numElementsToAdd > 0)
  2867. {
  2868. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  2869. while (--numElementsToAdd >= 0)
  2870. data.elements [numUsed++] = *elementsToAdd++;
  2871. }
  2872. lock.exit();
  2873. }
  2874. /** This swaps the contents of this array with those of another array.
  2875. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  2876. because it just swaps their internal pointers.
  2877. */
  2878. template <class OtherArrayType>
  2879. void swapWithArray (OtherArrayType& otherArray) throw()
  2880. {
  2881. lock.enter();
  2882. otherArray.lock.enter();
  2883. swapVariables <int> (numUsed, otherArray.numUsed);
  2884. swapVariables <ElementType*> (data.elements, otherArray.data.elements);
  2885. swapVariables <int> (data.numAllocated, otherArray.data.numAllocated);
  2886. otherArray.lock.exit();
  2887. lock.exit();
  2888. }
  2889. /** Adds elements from another array to the end of this array.
  2890. @param arrayToAddFrom the array from which to copy the elements
  2891. @param startIndex the first element of the other array to start copying from
  2892. @param numElementsToAdd how many elements to add from the other array. If this
  2893. value is negative or greater than the number of available elements,
  2894. all available elements will be copied.
  2895. @see add
  2896. */
  2897. template <class OtherArrayType>
  2898. void addArray (const OtherArrayType& arrayToAddFrom,
  2899. int startIndex = 0,
  2900. int numElementsToAdd = -1) throw()
  2901. {
  2902. arrayToAddFrom.lockArray();
  2903. lock.enter();
  2904. if (startIndex < 0)
  2905. {
  2906. jassertfalse
  2907. startIndex = 0;
  2908. }
  2909. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  2910. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  2911. while (--numElementsToAdd >= 0)
  2912. add (arrayToAddFrom.getUnchecked (startIndex++));
  2913. lock.exit();
  2914. arrayToAddFrom.unlockArray();
  2915. }
  2916. /** Inserts a new element into the array, assuming that the array is sorted.
  2917. This will use a comparator to find the position at which the new element
  2918. should go. If the array isn't sorted, the behaviour of this
  2919. method will be unpredictable.
  2920. @param comparator the comparator to use to compare the elements - see the sort()
  2921. method for details about the form this object should take
  2922. @param newElement the new element to insert to the array
  2923. @see add, sort
  2924. */
  2925. template <class ElementComparator>
  2926. void addSorted (ElementComparator& comparator,
  2927. const ElementType newElement) throw()
  2928. {
  2929. lock.enter();
  2930. insert (findInsertIndexInSortedArray (comparator, data.elements, newElement, 0, numUsed), newElement);
  2931. lock.exit();
  2932. }
  2933. /** Finds the index of an element in the array, assuming that the array is sorted.
  2934. This will use a comparator to do a binary-chop to find the index of the given
  2935. element, if it exists. If the array isn't sorted, the behaviour of this
  2936. method will be unpredictable.
  2937. @param comparator the comparator to use to compare the elements - see the sort()
  2938. method for details about the form this object should take
  2939. @param elementToLookFor the element to search for
  2940. @returns the index of the element, or -1 if it's not found
  2941. @see addSorted, sort
  2942. */
  2943. template <class ElementComparator>
  2944. int indexOfSorted (ElementComparator& comparator,
  2945. const ElementType elementToLookFor) const throw()
  2946. {
  2947. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2948. // avoids getting warning messages about the parameter being unused
  2949. lock.enter();
  2950. int start = 0;
  2951. int end = numUsed;
  2952. for (;;)
  2953. {
  2954. if (start >= end)
  2955. {
  2956. lock.exit();
  2957. return -1;
  2958. }
  2959. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  2960. {
  2961. lock.exit();
  2962. return start;
  2963. }
  2964. else
  2965. {
  2966. const int halfway = (start + end) >> 1;
  2967. if (halfway == start)
  2968. {
  2969. lock.exit();
  2970. return -1;
  2971. }
  2972. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  2973. start = halfway;
  2974. else
  2975. end = halfway;
  2976. }
  2977. }
  2978. }
  2979. /** Removes an element from the array.
  2980. This will remove the element at a given index, and move back
  2981. all the subsequent elements to close the gap.
  2982. If the index passed in is out-of-range, nothing will happen.
  2983. @param indexToRemove the index of the element to remove
  2984. @returns the element that has been removed
  2985. @see removeValue, removeRange
  2986. */
  2987. ElementType remove (const int indexToRemove) throw()
  2988. {
  2989. lock.enter();
  2990. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  2991. {
  2992. --numUsed;
  2993. ElementType* const e = data.elements + indexToRemove;
  2994. ElementType const removed = *e;
  2995. const int numberToShift = numUsed - indexToRemove;
  2996. if (numberToShift > 0)
  2997. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  2998. if ((numUsed << 1) < data.numAllocated)
  2999. minimiseStorageOverheads();
  3000. lock.exit();
  3001. return removed;
  3002. }
  3003. else
  3004. {
  3005. lock.exit();
  3006. return ElementType();
  3007. }
  3008. }
  3009. /** Removes an item from the array.
  3010. This will remove the first occurrence of the given element from the array.
  3011. If the item isn't found, no action is taken.
  3012. @param valueToRemove the object to try to remove
  3013. @see remove, removeRange
  3014. */
  3015. void removeValue (const ElementType valueToRemove) throw()
  3016. {
  3017. lock.enter();
  3018. ElementType* e = data.elements;
  3019. for (int i = numUsed; --i >= 0;)
  3020. {
  3021. if (valueToRemove == *e)
  3022. {
  3023. remove ((int) (e - data.elements));
  3024. break;
  3025. }
  3026. ++e;
  3027. }
  3028. lock.exit();
  3029. }
  3030. /** Removes a range of elements from the array.
  3031. This will remove a set of elements, starting from the given index,
  3032. and move subsequent elements down to close the gap.
  3033. If the range extends beyond the bounds of the array, it will
  3034. be safely clipped to the size of the array.
  3035. @param startIndex the index of the first element to remove
  3036. @param numberToRemove how many elements should be removed
  3037. @see remove, removeValue
  3038. */
  3039. void removeRange (int startIndex,
  3040. const int numberToRemove) throw()
  3041. {
  3042. lock.enter();
  3043. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3044. startIndex = jlimit (0, numUsed, startIndex);
  3045. if (endIndex > startIndex)
  3046. {
  3047. const int rangeSize = endIndex - startIndex;
  3048. ElementType* e = data.elements + startIndex;
  3049. int numToShift = numUsed - endIndex;
  3050. numUsed -= rangeSize;
  3051. while (--numToShift >= 0)
  3052. {
  3053. *e = e [rangeSize];
  3054. ++e;
  3055. }
  3056. if ((numUsed << 1) < data.numAllocated)
  3057. minimiseStorageOverheads();
  3058. }
  3059. lock.exit();
  3060. }
  3061. /** Removes the last n elements from the array.
  3062. @param howManyToRemove how many elements to remove from the end of the array
  3063. @see remove, removeValue, removeRange
  3064. */
  3065. void removeLast (const int howManyToRemove = 1) throw()
  3066. {
  3067. lock.enter();
  3068. numUsed = jmax (0, numUsed - howManyToRemove);
  3069. if ((numUsed << 1) < data.numAllocated)
  3070. minimiseStorageOverheads();
  3071. lock.exit();
  3072. }
  3073. /** Removes any elements which are also in another array.
  3074. @param otherArray the other array in which to look for elements to remove
  3075. @see removeValuesNotIn, remove, removeValue, removeRange
  3076. */
  3077. template <class OtherArrayType>
  3078. void removeValuesIn (const OtherArrayType& otherArray) throw()
  3079. {
  3080. otherArray.lockArray();
  3081. lock.enter();
  3082. if (this == &otherArray)
  3083. {
  3084. clear();
  3085. }
  3086. else
  3087. {
  3088. if (otherArray.size() > 0)
  3089. {
  3090. for (int i = numUsed; --i >= 0;)
  3091. if (otherArray.contains (data.elements [i]))
  3092. remove (i);
  3093. }
  3094. }
  3095. lock.exit();
  3096. otherArray.unlockArray();
  3097. }
  3098. /** Removes any elements which are not found in another array.
  3099. Only elements which occur in this other array will be retained.
  3100. @param otherArray the array in which to look for elements NOT to remove
  3101. @see removeValuesIn, remove, removeValue, removeRange
  3102. */
  3103. template <class OtherArrayType>
  3104. void removeValuesNotIn (const OtherArrayType& otherArray) throw()
  3105. {
  3106. otherArray.lockArray();
  3107. lock.enter();
  3108. if (this != &otherArray)
  3109. {
  3110. if (otherArray.size() <= 0)
  3111. {
  3112. clear();
  3113. }
  3114. else
  3115. {
  3116. for (int i = numUsed; --i >= 0;)
  3117. if (! otherArray.contains (data.elements [i]))
  3118. remove (i);
  3119. }
  3120. }
  3121. lock.exit();
  3122. otherArray.unlockArray();
  3123. }
  3124. /** Swaps over two elements in the array.
  3125. This swaps over the elements found at the two indexes passed in.
  3126. If either index is out-of-range, this method will do nothing.
  3127. @param index1 index of one of the elements to swap
  3128. @param index2 index of the other element to swap
  3129. */
  3130. void swap (const int index1,
  3131. const int index2) throw()
  3132. {
  3133. lock.enter();
  3134. if (((unsigned int) index1) < (unsigned int) numUsed
  3135. && ((unsigned int) index2) < (unsigned int) numUsed)
  3136. {
  3137. swapVariables (data.elements [index1],
  3138. data.elements [index2]);
  3139. }
  3140. lock.exit();
  3141. }
  3142. /** Moves one of the values to a different position.
  3143. This will move the value to a specified index, shuffling along
  3144. any intervening elements as required.
  3145. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3146. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3147. @param currentIndex the index of the value to be moved. If this isn't a
  3148. valid index, then nothing will be done
  3149. @param newIndex the index at which you'd like this value to end up. If this
  3150. is less than zero, the value will be moved to the end
  3151. of the array
  3152. */
  3153. void move (const int currentIndex,
  3154. int newIndex) throw()
  3155. {
  3156. if (currentIndex != newIndex)
  3157. {
  3158. lock.enter();
  3159. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3160. {
  3161. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3162. newIndex = numUsed - 1;
  3163. const ElementType value = data.elements [currentIndex];
  3164. if (newIndex > currentIndex)
  3165. {
  3166. memmove (data.elements + currentIndex,
  3167. data.elements + currentIndex + 1,
  3168. (newIndex - currentIndex) * sizeof (ElementType));
  3169. }
  3170. else
  3171. {
  3172. memmove (data.elements + newIndex + 1,
  3173. data.elements + newIndex,
  3174. (currentIndex - newIndex) * sizeof (ElementType));
  3175. }
  3176. data.elements [newIndex] = value;
  3177. }
  3178. lock.exit();
  3179. }
  3180. }
  3181. /** Reduces the amount of storage being used by the array.
  3182. Arrays typically allocate slightly more storage than they need, and after
  3183. removing elements, they may have quite a lot of unused space allocated.
  3184. This method will reduce the amount of allocated storage to a minimum.
  3185. */
  3186. void minimiseStorageOverheads() throw()
  3187. {
  3188. lock.enter();
  3189. if (numUsed == 0)
  3190. {
  3191. data.setAllocatedSize (0);
  3192. }
  3193. else
  3194. {
  3195. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  3196. if (newAllocation < data.numAllocated)
  3197. data.setAllocatedSize (newAllocation);
  3198. }
  3199. lock.exit();
  3200. }
  3201. /** Increases the array's internal storage to hold a minimum number of elements.
  3202. Calling this before adding a large known number of elements means that
  3203. the array won't have to keep dynamically resizing itself as the elements
  3204. are added, and it'll therefore be more efficient.
  3205. */
  3206. void ensureStorageAllocated (const int minNumElements) throw()
  3207. {
  3208. data.ensureAllocatedSize (minNumElements);
  3209. }
  3210. /** Sorts the elements in the array.
  3211. This will use a comparator object to sort the elements into order. The object
  3212. passed must have a method of the form:
  3213. @code
  3214. int compareElements (ElementType first, ElementType second);
  3215. @endcode
  3216. ..and this method must return:
  3217. - a value of < 0 if the first comes before the second
  3218. - a value of 0 if the two objects are equivalent
  3219. - a value of > 0 if the second comes before the first
  3220. To improve performance, the compareElements() method can be declared as static or const.
  3221. @param comparator the comparator to use for comparing elements.
  3222. @param retainOrderOfEquivalentItems if this is true, then items
  3223. which the comparator says are equivalent will be
  3224. kept in the order in which they currently appear
  3225. in the array. This is slower to perform, but may
  3226. be important in some cases. If it's false, a faster
  3227. algorithm is used, but equivalent elements may be
  3228. rearranged.
  3229. @see addSorted, indexOfSorted, sortArray
  3230. */
  3231. template <class ElementComparator>
  3232. void sort (ElementComparator& comparator,
  3233. const bool retainOrderOfEquivalentItems = false) const throw()
  3234. {
  3235. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3236. // avoids getting warning messages about the parameter being unused
  3237. lock.enter();
  3238. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  3239. lock.exit();
  3240. }
  3241. /** Locks the array's CriticalSection.
  3242. Of course if the type of section used is a DummyCriticalSection, this won't
  3243. have any effect.
  3244. @see unlockArray
  3245. */
  3246. void lockArray() const throw()
  3247. {
  3248. lock.enter();
  3249. }
  3250. /** Unlocks the array's CriticalSection.
  3251. Of course if the type of section used is a DummyCriticalSection, this won't
  3252. have any effect.
  3253. @see lockArray
  3254. */
  3255. void unlockArray() const throw()
  3256. {
  3257. lock.exit();
  3258. }
  3259. juce_UseDebuggingNewOperator
  3260. private:
  3261. ArrayAllocationBase <ElementType> data;
  3262. int numUsed;
  3263. TypeOfCriticalSectionToUse lock;
  3264. };
  3265. #endif // __JUCE_ARRAY_JUCEHEADER__
  3266. /********* End of inlined file: juce_Array.h *********/
  3267. #endif
  3268. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3269. #endif
  3270. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  3271. /********* Start of inlined file: juce_BitArray.h *********/
  3272. #ifndef __JUCE_BITARRAY_JUCEHEADER__
  3273. #define __JUCE_BITARRAY_JUCEHEADER__
  3274. /********* Start of inlined file: juce_HeapBlock.h *********/
  3275. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  3276. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  3277. /**
  3278. Very simple container class to hold a pointer to some data on the heap.
  3279. When you need to allocate some heap storage for something, always try to use
  3280. this class instead of allocating the memory directly using malloc/free.
  3281. A HeapBlock<char> object can be treated in pretty much exactly the same way
  3282. as an char*, but as long as you allocate it on the stack or as a class member,
  3283. it's almost impossible for it to leak memory.
  3284. It also makes your code much more concise and readable than doing the same thing
  3285. using direct allocations,
  3286. E.g. instead of this:
  3287. @code
  3288. int* temp = (int*) juce_malloc (1024 * sizeof (int));
  3289. memcpy (temp, xyz, 1024 * sizeof (int));
  3290. juce_free (temp);
  3291. temp = (int*) juce_calloc (2048 * sizeof (int));
  3292. temp[0] = 1234;
  3293. memcpy (foobar, temp, 2048 * sizeof (int));
  3294. juce_free (temp);
  3295. @endcode
  3296. ..you could just write this:
  3297. @code
  3298. HeapBlock <int> temp (1024);
  3299. memcpy (temp, xyz, 1024 * sizeof (int));
  3300. temp.calloc (2048);
  3301. temp[0] = 1234;
  3302. memcpy (foobar, temp, 2048 * sizeof (int));
  3303. @endcode
  3304. The class is extremely lightweight, containing only a pointer to the
  3305. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  3306. as their less object-oriented counterparts. Despite adding safety, you probably
  3307. won't sacrifice any performance by using this in place of normal pointers.
  3308. @see Array, OwnedArray, MemoryBlock
  3309. */
  3310. template <class ElementType>
  3311. class HeapBlock
  3312. {
  3313. public:
  3314. /** Creates a HeapBlock which is initially just a null pointer.
  3315. After creation, you can resize the array using the malloc(), calloc(),
  3316. or realloc() methods.
  3317. */
  3318. HeapBlock() : data (0)
  3319. {
  3320. }
  3321. /** Creates a HeapBlock containing a number of elements.
  3322. The contents of the block are undefined, as it will have been created by a
  3323. malloc call.
  3324. If you want an array of zero values, you can use the calloc() method instead.
  3325. */
  3326. HeapBlock (const int numElements)
  3327. : data ((ElementType*) ::juce_malloc (numElements * sizeof (ElementType)))
  3328. {
  3329. }
  3330. /** Destructor.
  3331. This will free the data, if any has been allocated.
  3332. */
  3333. ~HeapBlock()
  3334. {
  3335. ::juce_free (data);
  3336. }
  3337. /** Returns a raw pointer to the allocated data.
  3338. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  3339. freed by calling the free() method.
  3340. */
  3341. inline operator ElementType*() const { return data; }
  3342. /** Returns a void pointer to the allocated data.
  3343. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  3344. freed by calling the free() method.
  3345. */
  3346. inline operator void*() const { return (void*) data; }
  3347. /** Lets you use indirect calls to the first element in the array.
  3348. Obviously this will cause problems if the array hasn't been initialised, because it'll
  3349. be referencing a null pointer.
  3350. */
  3351. inline ElementType* operator->() const { return data; }
  3352. /** Returns a pointer to the data by casting it to any type you need.
  3353. */
  3354. template <class CastType>
  3355. inline operator CastType*() const { return (CastType*) data; }
  3356. /** Returns a reference to one of the data elements.
  3357. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  3358. has no idea of the size it currently has allocated.
  3359. */
  3360. inline ElementType& operator[] (const pointer_sized_int index) const { return data [index]; }
  3361. /** Returns a pointer to a data element at an offset from the start of the array.
  3362. This is the same as doing pointer arithmetic on the raw pointer itself.
  3363. */
  3364. inline ElementType* operator+ (const pointer_sized_int index) const { return data + index; }
  3365. /** Returns a reference to the raw data pointer.
  3366. Beware that the pointer returned here will become invalid as soon as you call
  3367. any of the allocator methods on this object!
  3368. */
  3369. inline ElementType** operator&() const { return (ElementType**) &data; }
  3370. /** Compares the pointer with another pointer.
  3371. This can be handy for checking whether this is a null pointer.
  3372. */
  3373. inline bool operator== (const ElementType* const otherPointer) const { return otherPointer == data; }
  3374. /** Compares the pointer with another pointer.
  3375. This can be handy for checking whether this is a null pointer.
  3376. */
  3377. inline bool operator!= (const ElementType* const otherPointer) const { return otherPointer != data; }
  3378. /** Allocates a specified amount of memory.
  3379. This uses the normal malloc to allocate an amount of memory for this object.
  3380. Any previously allocated memory will be freed by this method.
  3381. The number of bytes allocated will be (newNumElements * elementSize). Normally
  3382. you wouldn't need to specify the second parameter, but it can be handy if you need
  3383. to allocate a size in bytes rather than in terms of the number of elements.
  3384. The data that is allocated will be freed when this object is deleted, or when you
  3385. call free() or any of the allocation methods.
  3386. */
  3387. void malloc (const int newNumElements, const unsigned int elementSize = sizeof (ElementType))
  3388. {
  3389. ::juce_free (data);
  3390. data = (ElementType*) ::juce_malloc (newNumElements * elementSize);
  3391. }
  3392. /** Allocates a specified amount of memory and clears it.
  3393. This does the same job as the malloc() method, but clears the memory that it allocates.
  3394. */
  3395. void calloc (const int newNumElements, const unsigned int elementSize = sizeof (ElementType))
  3396. {
  3397. ::juce_free (data);
  3398. data = (ElementType*) ::juce_calloc (newNumElements * elementSize);
  3399. }
  3400. /** Allocates a specified amount of memory and optionally clears it.
  3401. This does the same job as either malloc() or calloc(), depending on the
  3402. initialiseToZero parameter.
  3403. */
  3404. void allocate (const int newNumElements, const bool initialiseToZero)
  3405. {
  3406. ::juce_free (data);
  3407. if (initialiseToZero)
  3408. data = (ElementType*) ::juce_calloc (newNumElements * sizeof (ElementType));
  3409. else
  3410. data = (ElementType*) ::juce_malloc (newNumElements * sizeof (ElementType));
  3411. }
  3412. /** Re-allocates a specified amount of memory.
  3413. The semantics of this method are the same as malloc() and calloc(), but it
  3414. uses realloc() to keep as much of the existing data as possible.
  3415. */
  3416. void realloc (const int newNumElements, const unsigned int elementSize = sizeof (ElementType))
  3417. {
  3418. if (data == 0)
  3419. data = (ElementType*) ::juce_malloc (newNumElements * elementSize);
  3420. else
  3421. data = (ElementType*) ::juce_realloc (data, newNumElements * elementSize);
  3422. }
  3423. /** Frees any currently-allocated data.
  3424. This will free the data and reset this object to be a null pointer.
  3425. */
  3426. void free()
  3427. {
  3428. ::juce_free (data);
  3429. data = 0;
  3430. }
  3431. /** Swaps this object's data with the data of another HeapBlock.
  3432. The two objects simply exchange their data pointers.
  3433. */
  3434. void swapWith (HeapBlock <ElementType>& other)
  3435. {
  3436. swapVariables (data, other.data);
  3437. }
  3438. private:
  3439. ElementType* data;
  3440. HeapBlock (const HeapBlock&);
  3441. const HeapBlock& operator= (const HeapBlock&);
  3442. };
  3443. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  3444. /********* End of inlined file: juce_HeapBlock.h *********/
  3445. class MemoryBlock;
  3446. /**
  3447. An array of on/off bits, also usable to store large binary integers.
  3448. A BitArray acts like an arbitrarily large integer whose bits can be set or
  3449. cleared, and some basic mathematical operations can be done on the number as
  3450. a whole.
  3451. */
  3452. class JUCE_API BitArray
  3453. {
  3454. public:
  3455. /** Creates an empty BitArray */
  3456. BitArray() throw();
  3457. /** Creates a BitArray containing an integer value in its low bits.
  3458. The low 32 bits of the array are initialised with this value.
  3459. */
  3460. BitArray (const unsigned int value) throw();
  3461. /** Creates a BitArray containing an integer value in its low bits.
  3462. The low 32 bits of the array are initialised with the absolute value
  3463. passed in, and its sign is set to reflect the sign of the number.
  3464. */
  3465. BitArray (const int value) throw();
  3466. /** Creates a BitArray containing an integer value in its low bits.
  3467. The low 64 bits of the array are initialised with the absolute value
  3468. passed in, and its sign is set to reflect the sign of the number.
  3469. */
  3470. BitArray (int64 value) throw();
  3471. /** Creates a copy of another BitArray. */
  3472. BitArray (const BitArray& other) throw();
  3473. /** Destructor. */
  3474. ~BitArray() throw();
  3475. /** Copies another BitArray onto this one. */
  3476. const BitArray& operator= (const BitArray& other) throw();
  3477. /** Two arrays are the same if the same bits are set. */
  3478. bool operator== (const BitArray& other) const throw();
  3479. /** Two arrays are the same if the same bits are set. */
  3480. bool operator!= (const BitArray& other) const throw();
  3481. /** Clears all bits in the BitArray to 0. */
  3482. void clear() throw();
  3483. /** Clears a particular bit in the array. */
  3484. void clearBit (const int bitNumber) throw();
  3485. /** Sets a specified bit to 1.
  3486. If the bit number is high, this will grow the array to accomodate it.
  3487. */
  3488. void setBit (const int bitNumber) throw();
  3489. /** Sets or clears a specified bit. */
  3490. void setBit (const int bitNumber,
  3491. const bool shouldBeSet) throw();
  3492. /** Sets a range of bits to be either on or off.
  3493. @param startBit the first bit to change
  3494. @param numBits the number of bits to change
  3495. @param shouldBeSet whether to turn these bits on or off
  3496. */
  3497. void setRange (int startBit,
  3498. int numBits,
  3499. const bool shouldBeSet) throw();
  3500. /** Inserts a bit an a given position, shifting up any bits above it. */
  3501. void insertBit (const int bitNumber,
  3502. const bool shouldBeSet) throw();
  3503. /** Returns the value of a specified bit in the array.
  3504. If the index is out-of-range, the result will be false.
  3505. */
  3506. bool operator[] (const int bit) const throw();
  3507. /** Returns true if no bits are set. */
  3508. bool isEmpty() const throw();
  3509. /** Returns a range of bits in the array as a new BitArray.
  3510. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3511. @see getBitRangeAsInt
  3512. */
  3513. const BitArray getBitRange (int startBit, int numBits) const throw();
  3514. /** Returns a range of bits in the array as an integer value.
  3515. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3516. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3517. getBitRange().
  3518. */
  3519. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3520. /** Sets a range of bits in the array based on an integer value.
  3521. Copies the given integer into the array, starting at startBit,
  3522. and only using up to numBits of the available bits.
  3523. */
  3524. void setBitRangeAsInt (int startBit, int numBits,
  3525. unsigned int valueToSet) throw();
  3526. /** Performs a bitwise OR with another BitArray.
  3527. The result ends up in this array.
  3528. */
  3529. void orWith (const BitArray& other) throw();
  3530. /** Performs a bitwise AND with another BitArray.
  3531. The result ends up in this array.
  3532. */
  3533. void andWith (const BitArray& other) throw();
  3534. /** Performs a bitwise XOR with another BitArray.
  3535. The result ends up in this array.
  3536. */
  3537. void xorWith (const BitArray& other) throw();
  3538. /** Adds another BitArray's value to this one.
  3539. Treating the two arrays as large positive integers, this
  3540. adds them up and puts the result in this array.
  3541. */
  3542. void add (const BitArray& other) throw();
  3543. /** Subtracts another BitArray's value from this one.
  3544. Treating the two arrays as large positive integers, this
  3545. subtracts them and puts the result in this array.
  3546. Note that if the result should be negative, this won't be
  3547. handled correctly.
  3548. */
  3549. void subtract (const BitArray& other) throw();
  3550. /** Multiplies another BitArray's value with this one.
  3551. Treating the two arrays as large positive integers, this
  3552. multiplies them and puts the result in this array.
  3553. */
  3554. void multiplyBy (const BitArray& other) throw();
  3555. /** Divides another BitArray's value into this one and also produces a remainder.
  3556. Treating the two arrays as large positive integers, this
  3557. divides this value by the other, leaving the quotient in this
  3558. array, and the remainder is copied into the other BitArray passed in.
  3559. */
  3560. void divideBy (const BitArray& divisor, BitArray& remainder) throw();
  3561. /** Returns the largest value that will divide both this value and the one
  3562. passed-in.
  3563. */
  3564. const BitArray findGreatestCommonDivisor (BitArray other) const throw();
  3565. /** Performs a modulo operation on this value.
  3566. The result is stored in this value.
  3567. */
  3568. void modulo (const BitArray& divisor) throw();
  3569. /** Performs a combined exponent and modulo operation.
  3570. This BitArray's value becomes (this ^ exponent) % modulus.
  3571. */
  3572. void exponentModulo (const BitArray& exponent, const BitArray& modulus) throw();
  3573. /** Performs an inverse modulo on the value.
  3574. i.e. the result is (this ^ -1) mod (modulus).
  3575. */
  3576. void inverseModulo (const BitArray& modulus) throw();
  3577. /** Shifts a section of bits left or right.
  3578. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3579. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3580. */
  3581. void shiftBits (int howManyBitsLeft,
  3582. int startBit = 0) throw();
  3583. /** Does a signed comparison of two BitArrays.
  3584. Return values are:
  3585. - 0 if the numbers are the same
  3586. - < 0 if this number is smaller than the other
  3587. - > 0 if this number is bigger than the other
  3588. */
  3589. int compare (const BitArray& other) const throw();
  3590. /** Compares the magnitudes of two BitArrays, ignoring their signs.
  3591. Return values are:
  3592. - 0 if the numbers are the same
  3593. - < 0 if this number is smaller than the other
  3594. - > 0 if this number is bigger than the other
  3595. */
  3596. int compareAbsolute (const BitArray& other) const throw();
  3597. /** Returns true if the value is less than zero.
  3598. @see setNegative, negate
  3599. */
  3600. bool isNegative() const throw();
  3601. /** Changes the sign of the number to be positive or negative.
  3602. @see isNegative, negate
  3603. */
  3604. void setNegative (const bool shouldBeNegative) throw();
  3605. /** Inverts the sign of the number.
  3606. @see isNegative, setNegative
  3607. */
  3608. void negate() throw();
  3609. /** Counts the total number of set bits in the array. */
  3610. int countNumberOfSetBits() const throw();
  3611. /** Looks for the index of the next set bit after a given starting point.
  3612. searches from startIndex (inclusive) upwards for the first set bit,
  3613. and returns its index.
  3614. If no set bits are found, it returns -1.
  3615. */
  3616. int findNextSetBit (int startIndex = 0) const throw();
  3617. /** Looks for the index of the next clear bit after a given starting point.
  3618. searches from startIndex (inclusive) upwards for the first clear bit,
  3619. and returns its index.
  3620. */
  3621. int findNextClearBit (int startIndex = 0) const throw();
  3622. /** Returns the index of the highest set bit in the array.
  3623. If the array is empty, this will return -1.
  3624. */
  3625. int getHighestBit() const throw();
  3626. /** Converts the array to a number string.
  3627. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3628. If minuimumNumCharacters is greater than 0, the returned string will be
  3629. padded with leading zeros to reach at least that length.
  3630. */
  3631. const String toString (const int base, const int minimumNumCharacters = 1) const throw();
  3632. /** Converts a number string to an array.
  3633. Any non-valid characters will be ignored.
  3634. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3635. */
  3636. void parseString (const String& text,
  3637. const int base) throw();
  3638. /** Turns the array into a block of binary data.
  3639. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3640. of the array, and so on.
  3641. @see loadFromMemoryBlock
  3642. */
  3643. const MemoryBlock toMemoryBlock() const throw();
  3644. /** Copies a block of raw data onto this array.
  3645. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3646. of the array, and so on.
  3647. @see toMemoryBlock
  3648. */
  3649. void loadFromMemoryBlock (const MemoryBlock& data) throw();
  3650. juce_UseDebuggingNewOperator
  3651. private:
  3652. void ensureSize (const int numVals) throw();
  3653. HeapBlock <unsigned int> values;
  3654. int numValues, highestBit;
  3655. bool negative;
  3656. };
  3657. #endif // __JUCE_BITARRAY_JUCEHEADER__
  3658. /********* End of inlined file: juce_BitArray.h *********/
  3659. #endif
  3660. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  3661. #endif
  3662. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  3663. #endif
  3664. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3665. /********* Start of inlined file: juce_MemoryBlock.h *********/
  3666. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3667. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  3668. /**
  3669. A class to hold a resizable block of raw data.
  3670. */
  3671. class JUCE_API MemoryBlock
  3672. {
  3673. public:
  3674. /** Create an uninitialised block with 0 size. */
  3675. MemoryBlock() throw();
  3676. /** Creates a memory block with a given initial size.
  3677. @param initialSize the size of block to create
  3678. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  3679. */
  3680. MemoryBlock (const int initialSize,
  3681. const bool initialiseToZero = false) throw();
  3682. /** Creates a copy of another memory block. */
  3683. MemoryBlock (const MemoryBlock& other) throw();
  3684. /** Creates a memory block using a copy of a block of data.
  3685. @param dataToInitialiseFrom some data to copy into this block
  3686. @param sizeInBytes how much space to use
  3687. */
  3688. MemoryBlock (const void* const dataToInitialiseFrom,
  3689. const int sizeInBytes) throw();
  3690. /** Destructor. */
  3691. ~MemoryBlock() throw();
  3692. /** Copies another memory block onto this one.
  3693. This block will be resized and copied to exactly match the other one.
  3694. */
  3695. const MemoryBlock& operator= (const MemoryBlock& other) throw();
  3696. /** Compares two memory blocks.
  3697. @returns true only if the two blocks are the same size and have identical contents.
  3698. */
  3699. bool operator== (const MemoryBlock& other) const throw();
  3700. /** Compares two memory blocks.
  3701. @returns true if the two blocks are different sizes or have different contents.
  3702. */
  3703. bool operator!= (const MemoryBlock& other) const throw();
  3704. /** Returns a pointer to the data, casting it to any type of primitive data required.
  3705. Note that the pointer returned will probably become invalid when the
  3706. block is resized.
  3707. */
  3708. template <class DataType>
  3709. operator DataType*() const throw() { return (DataType*) data; }
  3710. /** Returns a void pointer to the data.
  3711. Note that the pointer returned will probably become invalid when the
  3712. block is resized.
  3713. */
  3714. void* getData() const throw() { return data; }
  3715. /** Returns a byte from the memory block.
  3716. This returns a reference, so you can also use it to set a byte.
  3717. */
  3718. char& operator[] (const int offset) const throw() { return data [offset]; }
  3719. /** Returns the block's current allocated size, in bytes. */
  3720. int getSize() const throw() { return size; }
  3721. /** Resizes the memory block.
  3722. This will try to keep as much of the block's current content as it can,
  3723. and can optionally be made to clear any new space that gets allocated at
  3724. the end of the block.
  3725. @param newSize the new desired size for the block
  3726. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3727. whether to clear the new section or just leave it
  3728. uninitialised
  3729. @see ensureSize
  3730. */
  3731. void setSize (const int newSize,
  3732. const bool initialiseNewSpaceToZero = false) throw();
  3733. /** Increases the block's size only if it's smaller than a given size.
  3734. @param minimumSize if the block is already bigger than this size, no action
  3735. will be taken; otherwise it will be increased to this size
  3736. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3737. whether to clear the new section or just leave it
  3738. uninitialised
  3739. @see setSize
  3740. */
  3741. void ensureSize (const int minimumSize,
  3742. const bool initialiseNewSpaceToZero = false) throw();
  3743. /** Fills the entire memory block with a repeated byte value.
  3744. This is handy for clearing a block of memory to zero.
  3745. */
  3746. void fillWith (const uint8 valueToUse) throw();
  3747. /** Adds another block of data to the end of this one.
  3748. This block's size will be increased accordingly.
  3749. */
  3750. void append (const void* const data,
  3751. const int numBytes) throw();
  3752. /** Copies data into this MemoryBlock from a memory address.
  3753. @param srcData the memory location of the data to copy into this block
  3754. @param destinationOffset the offset in this block at which the data being copied should begin
  3755. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  3756. it will be clipped so not to do anything nasty)
  3757. */
  3758. void copyFrom (const void* srcData,
  3759. int destinationOffset,
  3760. int numBytes) throw();
  3761. /** Copies data from this MemoryBlock to a memory address.
  3762. @param destData the memory location to write to
  3763. @param sourceOffset the offset within this block from which the copied data will be read
  3764. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  3765. zeros will be used for that portion of the data)
  3766. */
  3767. void copyTo (void* destData,
  3768. int sourceOffset,
  3769. int numBytes) const throw();
  3770. /** Chops out a section of the block.
  3771. This will remove a section of the memory block and close the gap around it,
  3772. shifting any subsequent data downwards and reducing the size of the block.
  3773. If the range specified goes beyond the size of the block, it will be clipped.
  3774. */
  3775. void removeSection (int startByte, int numBytesToRemove) throw();
  3776. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  3777. characters in the system's default encoding. */
  3778. const String toString() const throw();
  3779. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  3780. The block will be resized to the number of valid bytes read from the string.
  3781. Non-hex characters in the string will be ignored.
  3782. @see String::toHexString()
  3783. */
  3784. void loadFromHexString (const String& sourceHexString) throw();
  3785. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  3786. void setBitRange (int bitRangeStart,
  3787. int numBits,
  3788. int binaryNumberToApply) throw();
  3789. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  3790. int getBitRange (int bitRangeStart,
  3791. int numBitsToRead) const throw();
  3792. /** Returns a string of characters that represent the binary contents of this block.
  3793. Uses a 64-bit encoding system to allow binary data to be turned into a string
  3794. of simple non-extended characters, e.g. for storage in XML.
  3795. @see fromBase64Encoding
  3796. */
  3797. const String toBase64Encoding() const throw();
  3798. /** Takes a string of encoded characters and turns it into binary data.
  3799. The string passed in must have been created by to64BitEncoding(), and this
  3800. block will be resized to recreate the original data block.
  3801. @see toBase64Encoding
  3802. */
  3803. bool fromBase64Encoding (const String& encodedString) throw();
  3804. juce_UseDebuggingNewOperator
  3805. private:
  3806. HeapBlock <char> data;
  3807. int size;
  3808. };
  3809. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  3810. /********* End of inlined file: juce_MemoryBlock.h *********/
  3811. #endif
  3812. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  3813. /********* Start of inlined file: juce_OwnedArray.h *********/
  3814. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  3815. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  3816. /********* Start of inlined file: juce_ScopedPointer.h *********/
  3817. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  3818. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  3819. /**
  3820. This class holds a pointer which is automatically deleted when this object goes
  3821. out of scope.
  3822. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  3823. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  3824. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  3825. created objects.
  3826. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  3827. to an object. If you use the assignment operator to assign a different object to a
  3828. ScopedPointer, the old one will be automatically deleted.
  3829. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  3830. can use the release() method.
  3831. */
  3832. template <class ObjectType>
  3833. class ScopedPointer
  3834. {
  3835. public:
  3836. /** Creates a ScopedPointer containing a null pointer. */
  3837. inline ScopedPointer() : object (0)
  3838. {
  3839. }
  3840. /** Creates a ScopedPointer that owns the specified object. */
  3841. inline ScopedPointer (ObjectType* const objectToTakePossessionOf)
  3842. : object (objectToTakePossessionOf)
  3843. {
  3844. }
  3845. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  3846. Because a pointer can only belong to one ScopedPointer, this transfers
  3847. the pointer from the other object to this one, and the other object is reset to
  3848. be a null pointer.
  3849. */
  3850. ScopedPointer (ScopedPointer& objectToTransferFrom)
  3851. : object (objectToTransferFrom.object)
  3852. {
  3853. objectToTransferFrom.object = 0;
  3854. }
  3855. /** Destructor.
  3856. This will delete the object that this ScopedPointer currently refers to.
  3857. */
  3858. inline ~ScopedPointer() { delete object; }
  3859. /** Changes this ScopedPointer to point to a new object.
  3860. Because a pointer can only belong to one ScopedPointer, this transfers
  3861. the pointer from the other object to this one, and the other object is reset to
  3862. be a null pointer.
  3863. If this ScopedPointer already points to an object, that object
  3864. will first be deleted.
  3865. */
  3866. const ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  3867. {
  3868. if (this != &objectToTransferFrom)
  3869. {
  3870. // Two ScopedPointers should never be able to refer to the same object - if
  3871. // this happens, you must have done something dodgy!
  3872. jassert (object != objectToTransferFrom.object);
  3873. ObjectType* const oldObject = object;
  3874. object = objectToTransferFrom.object;
  3875. objectToTransferFrom.object = 0;
  3876. delete oldObject;
  3877. }
  3878. return *this;
  3879. }
  3880. /** Changes this ScopedPointer to point to a new object.
  3881. If this ScopedPointer already points to an object, that object
  3882. will first be deleted.
  3883. The pointer that you pass is may be null.
  3884. */
  3885. const ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  3886. {
  3887. if (object != newObjectToTakePossessionOf)
  3888. {
  3889. ObjectType* const oldObject = object;
  3890. object = newObjectToTakePossessionOf;
  3891. delete oldObject;
  3892. }
  3893. return *this;
  3894. }
  3895. /** Returns the object that this ScopedPointer refers to.
  3896. */
  3897. inline operator ObjectType*() const { return object; }
  3898. /** Returns the object that this ScopedPointer refers to.
  3899. */
  3900. inline ObjectType& operator*() const { return *object; }
  3901. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  3902. inline ObjectType* operator->() const { return object; }
  3903. /** Returns a pointer to the object by casting it to whatever type you need. */
  3904. template <class CastType>
  3905. inline operator CastType*() const { return static_cast <CastType*> (object); }
  3906. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  3907. inline ObjectType** operator&() const { return (ObjectType**) &object; }
  3908. /** Removes the current object from this ScopedPointer without deleting it.
  3909. This will return the current object, and set the ScopedPointer to a null pointer.
  3910. */
  3911. ObjectType* release() { ObjectType* const o = object; object = 0; return o; }
  3912. /** Compares the pointer with another pointer.
  3913. This can be handy for checking whether this is a null pointer.
  3914. */
  3915. inline bool operator== (const ObjectType* const otherPointer) const { return otherPointer == object; }
  3916. /** Compares the pointer with another pointer.
  3917. This can be handy for checking whether this is a null pointer.
  3918. */
  3919. inline bool operator!= (const ObjectType* const otherPointer) const { return otherPointer != object; }
  3920. /** Swaps this object with that of another ScopedPointer.
  3921. The two objects simply exchange their pointers.
  3922. */
  3923. void swapWith (ScopedPointer <ObjectType>& other)
  3924. {
  3925. // Two ScopedPointers should never be able to refer to the same object - if
  3926. // this happens, you must have done something dodgy!
  3927. jassert (object != other.object);
  3928. swapVariables (object, other.object);
  3929. }
  3930. private:
  3931. ObjectType* object;
  3932. };
  3933. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  3934. /********* End of inlined file: juce_ScopedPointer.h *********/
  3935. /** An array designed for holding objects.
  3936. This holds a list of pointers to objects, and will automatically
  3937. delete the objects when they are removed from the array, or when the
  3938. array is itself deleted.
  3939. Declare it in the form: OwnedArray<MyObjectClass>
  3940. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  3941. After adding objects, they are 'owned' by the array and will be deleted when
  3942. removed or replaced.
  3943. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  3944. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  3945. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  3946. */
  3947. template <class ObjectClass,
  3948. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  3949. class OwnedArray
  3950. {
  3951. public:
  3952. /** Creates an empty array.
  3953. @param granularity this is the size of increment by which the internal storage
  3954. used by the array will grow. Only change it from the default if you know the
  3955. array is going to be very big and needs to be able to grow efficiently.
  3956. */
  3957. OwnedArray (const int granularity = juceDefaultArrayGranularity) throw()
  3958. : data (granularity),
  3959. numUsed (0)
  3960. {
  3961. }
  3962. /** Deletes the array and also deletes any objects inside it.
  3963. To get rid of the array without deleting its objects, use its
  3964. clear (false) method before deleting it.
  3965. */
  3966. ~OwnedArray()
  3967. {
  3968. clear (true);
  3969. }
  3970. /** Clears the array, optionally deleting the objects inside it first. */
  3971. void clear (const bool deleteObjects = true)
  3972. {
  3973. lock.enter();
  3974. if (deleteObjects)
  3975. {
  3976. while (numUsed > 0)
  3977. delete data.elements [--numUsed];
  3978. }
  3979. data.setAllocatedSize (0);
  3980. numUsed = 0;
  3981. lock.exit();
  3982. }
  3983. /** Returns the number of items currently in the array.
  3984. @see operator[]
  3985. */
  3986. inline int size() const throw()
  3987. {
  3988. return numUsed;
  3989. }
  3990. /** Returns a pointer to the object at this index in the array.
  3991. If the index is out-of-range, this will return a null pointer, (and
  3992. it could be null anyway, because it's ok for the array to hold null
  3993. pointers as well as objects).
  3994. @see getUnchecked
  3995. */
  3996. inline ObjectClass* operator[] (const int index) const throw()
  3997. {
  3998. lock.enter();
  3999. ObjectClass* const result = (((unsigned int) index) < (unsigned int) numUsed)
  4000. ? data.elements [index]
  4001. : (ObjectClass*) 0;
  4002. lock.exit();
  4003. return result;
  4004. }
  4005. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  4006. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  4007. it can be used when you're sure the index if always going to be legal.
  4008. */
  4009. inline ObjectClass* getUnchecked (const int index) const throw()
  4010. {
  4011. lock.enter();
  4012. jassert (((unsigned int) index) < (unsigned int) numUsed);
  4013. ObjectClass* const result = data.elements [index];
  4014. lock.exit();
  4015. return result;
  4016. }
  4017. /** Returns a pointer to the first object in the array.
  4018. This will return a null pointer if the array's empty.
  4019. @see getLast
  4020. */
  4021. inline ObjectClass* getFirst() const throw()
  4022. {
  4023. lock.enter();
  4024. ObjectClass* const result = (numUsed > 0) ? data.elements [0]
  4025. : (ObjectClass*) 0;
  4026. lock.exit();
  4027. return result;
  4028. }
  4029. /** Returns a pointer to the last object in the array.
  4030. This will return a null pointer if the array's empty.
  4031. @see getFirst
  4032. */
  4033. inline ObjectClass* getLast() const throw()
  4034. {
  4035. lock.enter();
  4036. ObjectClass* const result = (numUsed > 0) ? data.elements [numUsed - 1]
  4037. : (ObjectClass*) 0;
  4038. lock.exit();
  4039. return result;
  4040. }
  4041. /** Finds the index of an object which might be in the array.
  4042. @param objectToLookFor the object to look for
  4043. @returns the index at which the object was found, or -1 if it's not found
  4044. */
  4045. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  4046. {
  4047. int result = -1;
  4048. lock.enter();
  4049. ObjectClass* const* e = data.elements;
  4050. for (int i = numUsed; --i >= 0;)
  4051. {
  4052. if (objectToLookFor == *e)
  4053. {
  4054. result = (int) (e - data.elements);
  4055. break;
  4056. }
  4057. ++e;
  4058. }
  4059. lock.exit();
  4060. return result;
  4061. }
  4062. /** Returns true if the array contains a specified object.
  4063. @param objectToLookFor the object to look for
  4064. @returns true if the object is in the array
  4065. */
  4066. bool contains (const ObjectClass* const objectToLookFor) const throw()
  4067. {
  4068. lock.enter();
  4069. ObjectClass* const* e = data.elements;
  4070. int i = numUsed;
  4071. while (i >= 4)
  4072. {
  4073. if (objectToLookFor == *e
  4074. || objectToLookFor == *++e
  4075. || objectToLookFor == *++e
  4076. || objectToLookFor == *++e)
  4077. {
  4078. lock.exit();
  4079. return true;
  4080. }
  4081. i -= 4;
  4082. ++e;
  4083. }
  4084. while (i > 0)
  4085. {
  4086. if (objectToLookFor == *e)
  4087. {
  4088. lock.exit();
  4089. return true;
  4090. }
  4091. --i;
  4092. ++e;
  4093. }
  4094. lock.exit();
  4095. return false;
  4096. }
  4097. /** Appends a new object to the end of the array.
  4098. Note that the this object will be deleted by the OwnedArray when it
  4099. is removed, so be careful not to delete it somewhere else.
  4100. Also be careful not to add the same object to the array more than once,
  4101. as this will obviously cause deletion of dangling pointers.
  4102. @param newObject the new object to add to the array
  4103. @see set, insert, addIfNotAlreadyThere, addSorted
  4104. */
  4105. void add (const ObjectClass* const newObject) throw()
  4106. {
  4107. lock.enter();
  4108. data.ensureAllocatedSize (numUsed + 1);
  4109. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  4110. lock.exit();
  4111. }
  4112. /** Inserts a new object into the array at the given index.
  4113. Note that the this object will be deleted by the OwnedArray when it
  4114. is removed, so be careful not to delete it somewhere else.
  4115. If the index is less than 0 or greater than the size of the array, the
  4116. element will be added to the end of the array.
  4117. Otherwise, it will be inserted into the array, moving all the later elements
  4118. along to make room.
  4119. Be careful not to add the same object to the array more than once,
  4120. as this will obviously cause deletion of dangling pointers.
  4121. @param indexToInsertAt the index at which the new element should be inserted
  4122. @param newObject the new object to add to the array
  4123. @see add, addSorted, addIfNotAlreadyThere, set
  4124. */
  4125. void insert (int indexToInsertAt,
  4126. const ObjectClass* const newObject) throw()
  4127. {
  4128. if (indexToInsertAt >= 0)
  4129. {
  4130. lock.enter();
  4131. if (indexToInsertAt > numUsed)
  4132. indexToInsertAt = numUsed;
  4133. data.ensureAllocatedSize (numUsed + 1);
  4134. ObjectClass** const e = data.elements + indexToInsertAt;
  4135. const int numToMove = numUsed - indexToInsertAt;
  4136. if (numToMove > 0)
  4137. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  4138. *e = const_cast <ObjectClass*> (newObject);
  4139. ++numUsed;
  4140. lock.exit();
  4141. }
  4142. else
  4143. {
  4144. add (newObject);
  4145. }
  4146. }
  4147. /** Appends a new object at the end of the array as long as the array doesn't
  4148. already contain it.
  4149. If the array already contains a matching object, nothing will be done.
  4150. @param newObject the new object to add to the array
  4151. */
  4152. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  4153. {
  4154. lock.enter();
  4155. if (! contains (newObject))
  4156. add (newObject);
  4157. lock.exit();
  4158. }
  4159. /** Replaces an object in the array with a different one.
  4160. If the index is less than zero, this method does nothing.
  4161. If the index is beyond the end of the array, the new object is added to the end of the array.
  4162. Be careful not to add the same object to the array more than once,
  4163. as this will obviously cause deletion of dangling pointers.
  4164. @param indexToChange the index whose value you want to change
  4165. @param newObject the new value to set for this index.
  4166. @param deleteOldElement whether to delete the object that's being replaced with the new one
  4167. @see add, insert, remove
  4168. */
  4169. void set (const int indexToChange,
  4170. const ObjectClass* const newObject,
  4171. const bool deleteOldElement = true)
  4172. {
  4173. if (indexToChange >= 0)
  4174. {
  4175. ScopedPointer <ObjectClass> toDelete;
  4176. lock.enter();
  4177. if (indexToChange < numUsed)
  4178. {
  4179. if (deleteOldElement)
  4180. {
  4181. toDelete = data.elements [indexToChange];
  4182. if (toDelete == newObject)
  4183. toDelete = 0;
  4184. }
  4185. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  4186. }
  4187. else
  4188. {
  4189. data.ensureAllocatedSize (numUsed + 1);
  4190. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  4191. }
  4192. lock.exit();
  4193. }
  4194. }
  4195. /** Inserts a new object into the array assuming that the array is sorted.
  4196. This will use a comparator to find the position at which the new object
  4197. should go. If the array isn't sorted, the behaviour of this
  4198. method will be unpredictable.
  4199. @param comparator the comparator to use to compare the elements - see the sort method
  4200. for details about this object's structure
  4201. @param newObject the new object to insert to the array
  4202. @see add, sort, indexOfSorted
  4203. */
  4204. template <class ElementComparator>
  4205. void addSorted (ElementComparator& comparator,
  4206. ObjectClass* const newObject) throw()
  4207. {
  4208. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4209. // avoids getting warning messages about the parameter being unused
  4210. lock.enter();
  4211. insert (findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed), newObject);
  4212. lock.exit();
  4213. }
  4214. /** Finds the index of an object in the array, assuming that the array is sorted.
  4215. This will use a comparator to do a binary-chop to find the index of the given
  4216. element, if it exists. If the array isn't sorted, the behaviour of this
  4217. method will be unpredictable.
  4218. @param comparator the comparator to use to compare the elements - see the sort()
  4219. method for details about the form this object should take
  4220. @param objectToLookFor the object to search for
  4221. @returns the index of the element, or -1 if it's not found
  4222. @see addSorted, sort
  4223. */
  4224. template <class ElementComparator>
  4225. int indexOfSorted (ElementComparator& comparator,
  4226. const ObjectClass* const objectToLookFor) const throw()
  4227. {
  4228. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4229. // avoids getting warning messages about the parameter being unused
  4230. lock.enter();
  4231. int start = 0;
  4232. int end = numUsed;
  4233. for (;;)
  4234. {
  4235. if (start >= end)
  4236. {
  4237. lock.exit();
  4238. return -1;
  4239. }
  4240. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  4241. {
  4242. lock.exit();
  4243. return start;
  4244. }
  4245. else
  4246. {
  4247. const int halfway = (start + end) >> 1;
  4248. if (halfway == start)
  4249. {
  4250. lock.exit();
  4251. return -1;
  4252. }
  4253. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  4254. start = halfway;
  4255. else
  4256. end = halfway;
  4257. }
  4258. }
  4259. }
  4260. /** Removes an object from the array.
  4261. This will remove the object at a given index (optionally also
  4262. deleting it) and move back all the subsequent objects to close the gap.
  4263. If the index passed in is out-of-range, nothing will happen.
  4264. @param indexToRemove the index of the element to remove
  4265. @param deleteObject whether to delete the object that is removed
  4266. @see removeObject, removeRange
  4267. */
  4268. void remove (const int indexToRemove,
  4269. const bool deleteObject = true)
  4270. {
  4271. ScopedPointer <ObjectClass> toDelete;
  4272. lock.enter();
  4273. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  4274. {
  4275. ObjectClass** const e = data.elements + indexToRemove;
  4276. if (deleteObject)
  4277. toDelete = *e;
  4278. --numUsed;
  4279. const int numToShift = numUsed - indexToRemove;
  4280. if (numToShift > 0)
  4281. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  4282. if ((numUsed << 1) < data.numAllocated)
  4283. minimiseStorageOverheads();
  4284. }
  4285. lock.exit();
  4286. }
  4287. /** Removes a specified object from the array.
  4288. If the item isn't found, no action is taken.
  4289. @param objectToRemove the object to try to remove
  4290. @param deleteObject whether to delete the object (if it's found)
  4291. @see remove, removeRange
  4292. */
  4293. void removeObject (const ObjectClass* const objectToRemove,
  4294. const bool deleteObject = true)
  4295. {
  4296. lock.enter();
  4297. ObjectClass** e = data.elements;
  4298. for (int i = numUsed; --i >= 0;)
  4299. {
  4300. if (objectToRemove == *e)
  4301. {
  4302. remove ((int) (e - data.elements), deleteObject);
  4303. break;
  4304. }
  4305. ++e;
  4306. }
  4307. lock.exit();
  4308. }
  4309. /** Removes a range of objects from the array.
  4310. This will remove a set of objects, starting from the given index,
  4311. and move any subsequent elements down to close the gap.
  4312. If the range extends beyond the bounds of the array, it will
  4313. be safely clipped to the size of the array.
  4314. @param startIndex the index of the first object to remove
  4315. @param numberToRemove how many objects should be removed
  4316. @param deleteObjects whether to delete the objects that get removed
  4317. @see remove, removeObject
  4318. */
  4319. void removeRange (int startIndex,
  4320. const int numberToRemove,
  4321. const bool deleteObjects = true)
  4322. {
  4323. lock.enter();
  4324. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  4325. startIndex = jlimit (0, numUsed, startIndex);
  4326. if (endIndex > startIndex)
  4327. {
  4328. if (deleteObjects)
  4329. {
  4330. for (int i = startIndex; i < endIndex; ++i)
  4331. {
  4332. delete data.elements [i];
  4333. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  4334. }
  4335. }
  4336. const int rangeSize = endIndex - startIndex;
  4337. ObjectClass** e = data.elements + startIndex;
  4338. int numToShift = numUsed - endIndex;
  4339. numUsed -= rangeSize;
  4340. while (--numToShift >= 0)
  4341. {
  4342. *e = e [rangeSize];
  4343. ++e;
  4344. }
  4345. if ((numUsed << 1) < data.numAllocated)
  4346. minimiseStorageOverheads();
  4347. }
  4348. lock.exit();
  4349. }
  4350. /** Removes the last n objects from the array.
  4351. @param howManyToRemove how many objects to remove from the end of the array
  4352. @param deleteObjects whether to also delete the objects that are removed
  4353. @see remove, removeObject, removeRange
  4354. */
  4355. void removeLast (int howManyToRemove = 1,
  4356. const bool deleteObjects = true)
  4357. {
  4358. lock.enter();
  4359. if (howManyToRemove >= numUsed)
  4360. {
  4361. clear (deleteObjects);
  4362. }
  4363. else
  4364. {
  4365. while (--howManyToRemove >= 0)
  4366. remove (numUsed - 1, deleteObjects);
  4367. }
  4368. lock.exit();
  4369. }
  4370. /** Swaps a pair of objects in the array.
  4371. If either of the indexes passed in is out-of-range, nothing will happen,
  4372. otherwise the two objects at these positions will be exchanged.
  4373. */
  4374. void swap (const int index1,
  4375. const int index2) throw()
  4376. {
  4377. lock.enter();
  4378. if (((unsigned int) index1) < (unsigned int) numUsed
  4379. && ((unsigned int) index2) < (unsigned int) numUsed)
  4380. {
  4381. swapVariables (data.elements [index1],
  4382. data.elements [index2]);
  4383. }
  4384. lock.exit();
  4385. }
  4386. /** Moves one of the objects to a different position.
  4387. This will move the object to a specified index, shuffling along
  4388. any intervening elements as required.
  4389. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4390. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4391. @param currentIndex the index of the object to be moved. If this isn't a
  4392. valid index, then nothing will be done
  4393. @param newIndex the index at which you'd like this object to end up. If this
  4394. is less than zero, it will be moved to the end of the array
  4395. */
  4396. void move (const int currentIndex,
  4397. int newIndex) throw()
  4398. {
  4399. if (currentIndex != newIndex)
  4400. {
  4401. lock.enter();
  4402. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  4403. {
  4404. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  4405. newIndex = numUsed - 1;
  4406. ObjectClass* const value = data.elements [currentIndex];
  4407. if (newIndex > currentIndex)
  4408. {
  4409. memmove (data.elements + currentIndex,
  4410. data.elements + currentIndex + 1,
  4411. (newIndex - currentIndex) * sizeof (ObjectClass*));
  4412. }
  4413. else
  4414. {
  4415. memmove (data.elements + newIndex + 1,
  4416. data.elements + newIndex,
  4417. (currentIndex - newIndex) * sizeof (ObjectClass*));
  4418. }
  4419. data.elements [newIndex] = value;
  4420. }
  4421. lock.exit();
  4422. }
  4423. }
  4424. /** This swaps the contents of this array with those of another array.
  4425. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  4426. because it just swaps their internal pointers.
  4427. */
  4428. template <class OtherArrayType>
  4429. void swapWithArray (OtherArrayType& otherArray) throw()
  4430. {
  4431. lock.enter();
  4432. otherArray.lock.enter();
  4433. swapVariables <int> (numUsed, otherArray.numUsed);
  4434. swapVariables <ObjectClass**> (data.elements, otherArray.data.elements);
  4435. swapVariables <int> (data.numAllocated, otherArray.data.numAllocated);
  4436. otherArray.lock.exit();
  4437. lock.exit();
  4438. }
  4439. /** Reduces the amount of storage being used by the array.
  4440. Arrays typically allocate slightly more storage than they need, and after
  4441. removing elements, they may have quite a lot of unused space allocated.
  4442. This method will reduce the amount of allocated storage to a minimum.
  4443. */
  4444. void minimiseStorageOverheads() throw()
  4445. {
  4446. lock.enter();
  4447. if (numUsed == 0)
  4448. {
  4449. data.setAllocatedSize (0);
  4450. }
  4451. else
  4452. {
  4453. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  4454. if (newAllocation < data.numAllocated)
  4455. data.setAllocatedSize (newAllocation);
  4456. }
  4457. lock.exit();
  4458. }
  4459. /** Increases the array's internal storage to hold a minimum number of elements.
  4460. Calling this before adding a large known number of elements means that
  4461. the array won't have to keep dynamically resizing itself as the elements
  4462. are added, and it'll therefore be more efficient.
  4463. */
  4464. void ensureStorageAllocated (const int minNumElements) throw()
  4465. {
  4466. data.ensureAllocatedSize (minNumElements);
  4467. }
  4468. /** Sorts the elements in the array.
  4469. This will use a comparator object to sort the elements into order. The object
  4470. passed must have a method of the form:
  4471. @code
  4472. int compareElements (ElementType first, ElementType second);
  4473. @endcode
  4474. ..and this method must return:
  4475. - a value of < 0 if the first comes before the second
  4476. - a value of 0 if the two objects are equivalent
  4477. - a value of > 0 if the second comes before the first
  4478. To improve performance, the compareElements() method can be declared as static or const.
  4479. @param comparator the comparator to use for comparing elements.
  4480. @param retainOrderOfEquivalentItems if this is true, then items
  4481. which the comparator says are equivalent will be
  4482. kept in the order in which they currently appear
  4483. in the array. This is slower to perform, but may
  4484. be important in some cases. If it's false, a faster
  4485. algorithm is used, but equivalent elements may be
  4486. rearranged.
  4487. @see sortArray, indexOfSorted
  4488. */
  4489. template <class ElementComparator>
  4490. void sort (ElementComparator& comparator,
  4491. const bool retainOrderOfEquivalentItems = false) const throw()
  4492. {
  4493. (void) comparator; // if you pass in an object with a static compareElements() method, this
  4494. // avoids getting warning messages about the parameter being unused
  4495. lock.enter();
  4496. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  4497. lock.exit();
  4498. }
  4499. /** Locks the array's CriticalSection.
  4500. Of course if the type of section used is a DummyCriticalSection, this won't
  4501. have any effect.
  4502. @see unlockArray
  4503. */
  4504. void lockArray() const throw()
  4505. {
  4506. lock.enter();
  4507. }
  4508. /** Unlocks the array's CriticalSection.
  4509. Of course if the type of section used is a DummyCriticalSection, this won't
  4510. have any effect.
  4511. @see lockArray
  4512. */
  4513. void unlockArray() const throw()
  4514. {
  4515. lock.exit();
  4516. }
  4517. juce_UseDebuggingNewOperator
  4518. private:
  4519. ArrayAllocationBase <ObjectClass*> data;
  4520. int numUsed;
  4521. TypeOfCriticalSectionToUse lock;
  4522. // disallow copy constructor and assignment
  4523. OwnedArray (const OwnedArray&);
  4524. const OwnedArray& operator= (const OwnedArray&);
  4525. };
  4526. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  4527. /********* End of inlined file: juce_OwnedArray.h *********/
  4528. #endif
  4529. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  4530. /********* Start of inlined file: juce_PropertySet.h *********/
  4531. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  4532. #define __JUCE_PROPERTYSET_JUCEHEADER__
  4533. /********* Start of inlined file: juce_StringPairArray.h *********/
  4534. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  4535. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  4536. /********* Start of inlined file: juce_StringArray.h *********/
  4537. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  4538. #define __JUCE_STRINGARRAY_JUCEHEADER__
  4539. #ifndef DOXYGEN
  4540. // (used in StringArray::appendNumbersToDuplicates)
  4541. static const tchar* const defaultPreNumberString = JUCE_T(" (");
  4542. static const tchar* const defaultPostNumberString = JUCE_T(")");
  4543. #endif
  4544. /**
  4545. A special array for holding a list of strings.
  4546. @see String, StringPairArray
  4547. */
  4548. class JUCE_API StringArray
  4549. {
  4550. public:
  4551. /** Creates an empty string array */
  4552. StringArray() throw();
  4553. /** Creates a copy of another string array */
  4554. StringArray (const StringArray& other) throw();
  4555. /** Creates a copy of an array of string literals.
  4556. @param strings an array of strings to add. Null pointers in the array will be
  4557. treated as empty strings
  4558. @param numberOfStrings how many items there are in the array
  4559. */
  4560. StringArray (const juce_wchar** const strings,
  4561. const int numberOfStrings) throw();
  4562. /** Creates a copy of an array of string literals.
  4563. @param strings an array of strings to add. Null pointers in the array will be
  4564. treated as empty strings
  4565. @param numberOfStrings how many items there are in the array
  4566. */
  4567. StringArray (const char** const strings,
  4568. const int numberOfStrings) throw();
  4569. /** Creates a copy of a null-terminated array of string literals.
  4570. Each item from the array passed-in is added, until it encounters a null pointer,
  4571. at which point it stops.
  4572. */
  4573. StringArray (const juce_wchar** const strings) throw();
  4574. /** Creates a copy of a null-terminated array of string literals.
  4575. Each item from the array passed-in is added, until it encounters a null pointer,
  4576. at which point it stops.
  4577. */
  4578. StringArray (const char** const strings) throw();
  4579. /** Destructor. */
  4580. virtual ~StringArray() throw();
  4581. /** Copies the contents of another string array into this one */
  4582. const StringArray& operator= (const StringArray& other) throw();
  4583. /** Compares two arrays.
  4584. Comparisons are case-sensitive.
  4585. @returns true only if the other array contains exactly the same strings in the same order
  4586. */
  4587. bool operator== (const StringArray& other) const throw();
  4588. /** Compares two arrays.
  4589. Comparisons are case-sensitive.
  4590. @returns false if the other array contains exactly the same strings in the same order
  4591. */
  4592. bool operator!= (const StringArray& other) const throw();
  4593. /** Returns the number of strings in the array */
  4594. inline int size() const throw() { return strings.size(); };
  4595. /** Returns one of the strings from the array.
  4596. If the index is out-of-range, an empty string is returned.
  4597. Obviously the reference returned shouldn't be stored for later use, as the
  4598. string it refers to may disappear when the array changes.
  4599. */
  4600. const String& operator[] (const int index) const throw();
  4601. /** Searches for a string in the array.
  4602. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4603. @returns true if the string is found inside the array
  4604. */
  4605. bool contains (const String& stringToLookFor,
  4606. const bool ignoreCase = false) const throw();
  4607. /** Searches for a string in the array.
  4608. The comparison will be case-insensitive if the ignoreCase parameter is true.
  4609. @param stringToLookFor the string to try to find
  4610. @param ignoreCase whether the comparison should be case-insensitive
  4611. @param startIndex the first index to start searching from
  4612. @returns the index of the first occurrence of the string in this array,
  4613. or -1 if it isn't found.
  4614. */
  4615. int indexOf (const String& stringToLookFor,
  4616. const bool ignoreCase = false,
  4617. int startIndex = 0) const throw();
  4618. /** Appends a string at the end of the array. */
  4619. void add (const String& stringToAdd) throw();
  4620. /** Inserts a string into the array.
  4621. This will insert a string into the array at the given index, moving
  4622. up the other elements to make room for it.
  4623. If the index is less than zero or greater than the size of the array,
  4624. the new string will be added to the end of the array.
  4625. */
  4626. void insert (const int index,
  4627. const String& stringToAdd) throw();
  4628. /** Adds a string to the array as long as it's not already in there.
  4629. The search can optionally be case-insensitive.
  4630. */
  4631. void addIfNotAlreadyThere (const String& stringToAdd,
  4632. const bool ignoreCase = false) throw();
  4633. /** Replaces one of the strings in the array with another one.
  4634. If the index is higher than the array's size, the new string will be
  4635. added to the end of the array; if it's less than zero nothing happens.
  4636. */
  4637. void set (const int index,
  4638. const String& newString) throw();
  4639. /** Appends some strings from another array to the end of this one.
  4640. @param other the array to add
  4641. @param startIndex the first element of the other array to add
  4642. @param numElementsToAdd the maximum number of elements to add (if this is
  4643. less than zero, they are all added)
  4644. */
  4645. void addArray (const StringArray& other,
  4646. int startIndex = 0,
  4647. int numElementsToAdd = -1) throw();
  4648. /** Breaks up a string into tokens and adds them to this array.
  4649. This will tokenise the given string using whitespace characters as the
  4650. token delimiters, and will add these tokens to the end of the array.
  4651. @returns the number of tokens added
  4652. */
  4653. int addTokens (const tchar* const stringToTokenise,
  4654. const bool preserveQuotedStrings) throw();
  4655. /** Breaks up a string into tokens and adds them to this array.
  4656. This will tokenise the given string (using the string passed in to define the
  4657. token delimiters), and will add these tokens to the end of the array.
  4658. @param stringToTokenise the string to tokenise
  4659. @param breakCharacters a string of characters, any of which will be considered
  4660. to be a token delimiter.
  4661. @param quoteCharacters if this string isn't empty, it defines a set of characters
  4662. which are treated as quotes. Any text occurring
  4663. between quotes is not broken up into tokens.
  4664. @returns the number of tokens added
  4665. */
  4666. int addTokens (const tchar* const stringToTokenise,
  4667. const tchar* breakCharacters,
  4668. const tchar* quoteCharacters) throw();
  4669. /** Breaks up a string into lines and adds them to this array.
  4670. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  4671. to the array. Line-break characters are omitted from the strings that are added to
  4672. the array.
  4673. */
  4674. int addLines (const tchar* stringToBreakUp) throw();
  4675. /** Removes all elements from the array. */
  4676. void clear() throw();
  4677. /** Removes a string from the array.
  4678. If the index is out-of-range, no action will be taken.
  4679. */
  4680. void remove (const int index) throw();
  4681. /** Finds a string in the array and removes it.
  4682. This will remove the first occurrence of the given string from the array. The
  4683. comparison may be case-insensitive depending on the ignoreCase parameter.
  4684. */
  4685. void removeString (const String& stringToRemove,
  4686. const bool ignoreCase = false) throw();
  4687. /** Removes any duplicated elements from the array.
  4688. If any string appears in the array more than once, only the first occurrence of
  4689. it will be retained.
  4690. @param ignoreCase whether to use a case-insensitive comparison
  4691. */
  4692. void removeDuplicates (const bool ignoreCase) throw();
  4693. /** Removes empty strings from the array.
  4694. @param removeWhitespaceStrings if true, strings that only contain whitespace
  4695. characters will also be removed
  4696. */
  4697. void removeEmptyStrings (const bool removeWhitespaceStrings = true) throw();
  4698. /** Moves one of the strings to a different position.
  4699. This will move the string to a specified index, shuffling along
  4700. any intervening elements as required.
  4701. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  4702. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  4703. @param currentIndex the index of the value to be moved. If this isn't a
  4704. valid index, then nothing will be done
  4705. @param newIndex the index at which you'd like this value to end up. If this
  4706. is less than zero, the value will be moved to the end
  4707. of the array
  4708. */
  4709. void move (const int currentIndex, int newIndex) throw();
  4710. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  4711. void trim() throw();
  4712. /** Adds numbers to the strings in the array, to make each string unique.
  4713. This will add numbers to the ends of groups of similar strings.
  4714. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  4715. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  4716. @param appendNumberToFirstInstance whether the first of a group of similar strings
  4717. also has a number appended to it.
  4718. @param preNumberString when adding a number, this string is added before the number
  4719. @param postNumberString this string is appended after any numbers that are added
  4720. */
  4721. void appendNumbersToDuplicates (const bool ignoreCaseWhenComparing,
  4722. const bool appendNumberToFirstInstance,
  4723. const tchar* const preNumberString = defaultPreNumberString,
  4724. const tchar* const postNumberString = defaultPostNumberString) throw();
  4725. /** Joins the strings in the array together into one string.
  4726. This will join a range of elements from the array into a string, separating
  4727. them with a given string.
  4728. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  4729. @param separatorString the string to insert between all the strings
  4730. @param startIndex the first element to join
  4731. @param numberOfElements how many elements to join together. If this is less
  4732. than zero, all available elements will be used.
  4733. */
  4734. const String joinIntoString (const String& separatorString,
  4735. int startIndex = 0,
  4736. int numberOfElements = -1) const throw();
  4737. /** Sorts the array into alphabetical order.
  4738. @param ignoreCase if true, the comparisons used will be case-sensitive.
  4739. */
  4740. void sort (const bool ignoreCase) throw();
  4741. /** Reduces the amount of storage being used by the array.
  4742. Arrays typically allocate slightly more storage than they need, and after
  4743. removing elements, they may have quite a lot of unused space allocated.
  4744. This method will reduce the amount of allocated storage to a minimum.
  4745. */
  4746. void minimiseStorageOverheads() throw();
  4747. juce_UseDebuggingNewOperator
  4748. private:
  4749. OwnedArray <String> strings;
  4750. };
  4751. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  4752. /********* End of inlined file: juce_StringArray.h *********/
  4753. /**
  4754. A container for holding a set of strings which are keyed by another string.
  4755. @see StringArray
  4756. */
  4757. class JUCE_API StringPairArray
  4758. {
  4759. public:
  4760. /** Creates an empty array */
  4761. StringPairArray (const bool ignoreCaseWhenComparingKeys = true) throw();
  4762. /** Creates a copy of another array */
  4763. StringPairArray (const StringPairArray& other) throw();
  4764. /** Destructor. */
  4765. ~StringPairArray() throw();
  4766. /** Copies the contents of another string array into this one */
  4767. const StringPairArray& operator= (const StringPairArray& other) throw();
  4768. /** Compares two arrays.
  4769. Comparisons are case-sensitive.
  4770. @returns true only if the other array contains exactly the same strings with the same keys
  4771. */
  4772. bool operator== (const StringPairArray& other) const throw();
  4773. /** Compares two arrays.
  4774. Comparisons are case-sensitive.
  4775. @returns false if the other array contains exactly the same strings with the same keys
  4776. */
  4777. bool operator!= (const StringPairArray& other) const throw();
  4778. /** Finds the value corresponding to a key string.
  4779. If no such key is found, this will just return an empty string. To check whether
  4780. a given key actually exists (because it might actually be paired with an empty string), use
  4781. the getAllKeys() method to obtain a list.
  4782. Obviously the reference returned shouldn't be stored for later use, as the
  4783. string it refers to may disappear when the array changes.
  4784. @see getValue
  4785. */
  4786. const String& operator[] (const String& key) const throw();
  4787. /** Finds the value corresponding to a key string.
  4788. If no such key is found, this will just return the value provided as a default.
  4789. @see operator[]
  4790. */
  4791. const String getValue (const String& key, const String& defaultReturnValue) const;
  4792. /** Returns a list of all keys in the array. */
  4793. const StringArray& getAllKeys() const throw() { return keys; }
  4794. /** Returns a list of all values in the array. */
  4795. const StringArray& getAllValues() const throw() { return values; }
  4796. /** Returns the number of strings in the array */
  4797. inline int size() const throw() { return keys.size(); };
  4798. /** Adds or amends a key/value pair.
  4799. If a value already exists with this key, its value will be overwritten,
  4800. otherwise the key/value pair will be added to the array.
  4801. */
  4802. void set (const String& key,
  4803. const String& value) throw();
  4804. /** Adds the items from another array to this one.
  4805. This is equivalent to using set() to add each of the pairs from the other array.
  4806. */
  4807. void addArray (const StringPairArray& other);
  4808. /** Removes all elements from the array. */
  4809. void clear() throw();
  4810. /** Removes a string from the array based on its key.
  4811. If the key isn't found, nothing will happen.
  4812. */
  4813. void remove (const String& key) throw();
  4814. /** Removes a string from the array based on its index.
  4815. If the index is out-of-range, no action will be taken.
  4816. */
  4817. void remove (const int index) throw();
  4818. /** Indicates whether to use a case-insensitive search when looking up a key string.
  4819. */
  4820. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  4821. /** Returns a descriptive string containing the items.
  4822. This is handy for dumping the contents of an array.
  4823. */
  4824. const String getDescription() const;
  4825. /** Reduces the amount of storage being used by the array.
  4826. Arrays typically allocate slightly more storage than they need, and after
  4827. removing elements, they may have quite a lot of unused space allocated.
  4828. This method will reduce the amount of allocated storage to a minimum.
  4829. */
  4830. void minimiseStorageOverheads() throw();
  4831. juce_UseDebuggingNewOperator
  4832. private:
  4833. StringArray keys, values;
  4834. bool ignoreCase;
  4835. };
  4836. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  4837. /********* End of inlined file: juce_StringPairArray.h *********/
  4838. /********* Start of inlined file: juce_XmlElement.h *********/
  4839. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  4840. #define __JUCE_XMLELEMENT_JUCEHEADER__
  4841. /********* Start of inlined file: juce_OutputStream.h *********/
  4842. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4843. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4844. /********* Start of inlined file: juce_InputStream.h *********/
  4845. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  4846. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  4847. /** The base class for streams that read data.
  4848. Input and output streams are used throughout the library - subclasses can override
  4849. some or all of the virtual functions to implement their behaviour.
  4850. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  4851. */
  4852. class JUCE_API InputStream
  4853. {
  4854. public:
  4855. /** Destructor. */
  4856. virtual ~InputStream() {}
  4857. /** Returns the total number of bytes available for reading in this stream.
  4858. Note that this is the number of bytes available from the start of the
  4859. stream, not from the current position.
  4860. If the size of the stream isn't actually known, this may return -1.
  4861. */
  4862. virtual int64 getTotalLength() = 0;
  4863. /** Returns true if the stream has no more data to read. */
  4864. virtual bool isExhausted() = 0;
  4865. /** Reads a set of bytes from the stream into a memory buffer.
  4866. This is the only read method that subclasses actually need to implement, as the
  4867. InputStream base class implements the other read methods in terms of this one (although
  4868. it's often more efficient for subclasses to implement them directly).
  4869. @param destBuffer the destination buffer for the data
  4870. @param maxBytesToRead the maximum number of bytes to read - make sure the
  4871. memory block passed in is big enough to contain this
  4872. many bytes.
  4873. @returns the actual number of bytes that were read, which may be less than
  4874. maxBytesToRead if the stream is exhausted before it gets that far
  4875. */
  4876. virtual int read (void* destBuffer,
  4877. int maxBytesToRead) = 0;
  4878. /** Reads a byte from the stream.
  4879. If the stream is exhausted, this will return zero.
  4880. @see OutputStream::writeByte
  4881. */
  4882. virtual char readByte();
  4883. /** Reads a boolean from the stream.
  4884. The bool is encoded as a single byte - 1 for true, 0 for false.
  4885. If the stream is exhausted, this will return false.
  4886. @see OutputStream::writeBool
  4887. */
  4888. virtual bool readBool();
  4889. /** Reads two bytes from the stream as a little-endian 16-bit value.
  4890. If the next two bytes read are byte1 and byte2, this returns
  4891. (byte1 | (byte2 << 8)).
  4892. If the stream is exhausted partway through reading the bytes, this will return zero.
  4893. @see OutputStream::writeShort, readShortBigEndian
  4894. */
  4895. virtual short readShort();
  4896. /** Reads two bytes from the stream as a little-endian 16-bit value.
  4897. If the next two bytes read are byte1 and byte2, this returns
  4898. (byte2 | (byte1 << 8)).
  4899. If the stream is exhausted partway through reading the bytes, this will return zero.
  4900. @see OutputStream::writeShortBigEndian, readShort
  4901. */
  4902. virtual short readShortBigEndian();
  4903. /** Reads four bytes from the stream as a little-endian 32-bit value.
  4904. If the next four bytes are byte1 to byte4, this returns
  4905. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  4906. If the stream is exhausted partway through reading the bytes, this will return zero.
  4907. @see OutputStream::writeInt, readIntBigEndian
  4908. */
  4909. virtual int readInt();
  4910. /** Reads four bytes from the stream as a big-endian 32-bit value.
  4911. If the next four bytes are byte1 to byte4, this returns
  4912. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  4913. If the stream is exhausted partway through reading the bytes, this will return zero.
  4914. @see OutputStream::writeIntBigEndian, readInt
  4915. */
  4916. virtual int readIntBigEndian();
  4917. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  4918. If the next eight bytes are byte1 to byte8, this returns
  4919. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  4920. If the stream is exhausted partway through reading the bytes, this will return zero.
  4921. @see OutputStream::writeInt64, readInt64BigEndian
  4922. */
  4923. virtual int64 readInt64();
  4924. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  4925. If the next eight bytes are byte1 to byte8, this returns
  4926. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  4927. If the stream is exhausted partway through reading the bytes, this will return zero.
  4928. @see OutputStream::writeInt64BigEndian, readInt64
  4929. */
  4930. virtual int64 readInt64BigEndian();
  4931. /** Reads four bytes as a 32-bit floating point value.
  4932. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  4933. If the stream is exhausted partway through reading the bytes, this will return zero.
  4934. @see OutputStream::writeFloat, readDouble
  4935. */
  4936. virtual float readFloat();
  4937. /** Reads four bytes as a 32-bit floating point value.
  4938. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  4939. If the stream is exhausted partway through reading the bytes, this will return zero.
  4940. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  4941. */
  4942. virtual float readFloatBigEndian();
  4943. /** Reads eight bytes as a 64-bit floating point value.
  4944. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  4945. If the stream is exhausted partway through reading the bytes, this will return zero.
  4946. @see OutputStream::writeDouble, readFloat
  4947. */
  4948. virtual double readDouble();
  4949. /** Reads eight bytes as a 64-bit floating point value.
  4950. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  4951. If the stream is exhausted partway through reading the bytes, this will return zero.
  4952. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  4953. */
  4954. virtual double readDoubleBigEndian();
  4955. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  4956. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  4957. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4958. @see OutputStream::writeCompressedInt()
  4959. */
  4960. virtual int readCompressedInt();
  4961. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  4962. This will read up to the next "\n" or "\r\n" or end-of-stream.
  4963. After this call, the stream's position will be left pointing to the next character
  4964. following the line-feed, but the linefeeds aren't included in the string that
  4965. is returned.
  4966. */
  4967. virtual const String readNextLine();
  4968. /** Reads a zero-terminated UTF8 string from the stream.
  4969. This will read characters from the stream until it hits a zero character or
  4970. end-of-stream.
  4971. @see OutputStream::writeString, readEntireStreamAsString
  4972. */
  4973. virtual const String readString();
  4974. /** Tries to read the whole stream and turn it into a string.
  4975. This will read from the stream's current position until the end-of-stream, and
  4976. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  4977. */
  4978. virtual const String readEntireStreamAsString();
  4979. /** Reads from the stream and appends the data to a MemoryBlock.
  4980. @param destBlock the block to append the data onto
  4981. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  4982. of bytes that will be read - if it's negative, data
  4983. will be read until the stream is exhausted.
  4984. @returns the number of bytes that were added to the memory block
  4985. */
  4986. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  4987. int maxNumBytesToRead = -1);
  4988. /** Returns the offset of the next byte that will be read from the stream.
  4989. @see setPosition
  4990. */
  4991. virtual int64 getPosition() = 0;
  4992. /** Tries to move the current read position of the stream.
  4993. The position is an absolute number of bytes from the stream's start.
  4994. Some streams might not be able to do this, in which case they should do
  4995. nothing and return false. Others might be able to manage it by resetting
  4996. themselves and skipping to the correct position, although this is
  4997. obviously a bit slow.
  4998. @returns true if the stream manages to reposition itself correctly
  4999. @see getPosition
  5000. */
  5001. virtual bool setPosition (int64 newPosition) = 0;
  5002. /** Reads and discards a number of bytes from the stream.
  5003. Some input streams might implement this efficiently, but the base
  5004. class will just keep reading data until the requisite number of bytes
  5005. have been done.
  5006. */
  5007. virtual void skipNextBytes (int64 numBytesToSkip);
  5008. juce_UseDebuggingNewOperator
  5009. protected:
  5010. InputStream() throw() {}
  5011. };
  5012. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  5013. /********* End of inlined file: juce_InputStream.h *********/
  5014. /**
  5015. The base class for streams that write data to some kind of destination.
  5016. Input and output streams are used throughout the library - subclasses can override
  5017. some or all of the virtual functions to implement their behaviour.
  5018. @see InputStream, MemoryOutputStream, FileOutputStream
  5019. */
  5020. class JUCE_API OutputStream
  5021. {
  5022. public:
  5023. /** Destructor.
  5024. Some subclasses might want to do things like call flush() during their
  5025. destructors.
  5026. */
  5027. virtual ~OutputStream();
  5028. /** If the stream is using a buffer, this will ensure it gets written
  5029. out to the destination. */
  5030. virtual void flush() = 0;
  5031. /** Tries to move the stream's output position.
  5032. Not all streams will be able to seek to a new position - this will return
  5033. false if it fails to work.
  5034. @see getPosition
  5035. */
  5036. virtual bool setPosition (int64 newPosition) = 0;
  5037. /** Returns the stream's current position.
  5038. @see setPosition
  5039. */
  5040. virtual int64 getPosition() = 0;
  5041. /** Writes a block of data to the stream.
  5042. When creating a subclass of OutputStream, this is the only write method
  5043. that needs to be overloaded - the base class has methods for writing other
  5044. types of data which use this to do the work.
  5045. @returns false if the write operation fails for some reason
  5046. */
  5047. virtual bool write (const void* dataToWrite,
  5048. int howManyBytes) = 0;
  5049. /** Writes a single byte to the stream.
  5050. @see InputStream::readByte
  5051. */
  5052. virtual void writeByte (char byte);
  5053. /** Writes a boolean to the stream.
  5054. This is encoded as a byte - either 1 or 0.
  5055. @see InputStream::readBool
  5056. */
  5057. virtual void writeBool (bool boolValue);
  5058. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  5059. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  5060. @see InputStream::readShort
  5061. */
  5062. virtual void writeShort (short value);
  5063. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  5064. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  5065. @see InputStream::readShortBigEndian
  5066. */
  5067. virtual void writeShortBigEndian (short value);
  5068. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  5069. @see InputStream::readInt
  5070. */
  5071. virtual void writeInt (int value);
  5072. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  5073. @see InputStream::readIntBigEndian
  5074. */
  5075. virtual void writeIntBigEndian (int value);
  5076. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  5077. @see InputStream::readInt64
  5078. */
  5079. virtual void writeInt64 (int64 value);
  5080. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  5081. @see InputStream::readInt64BigEndian
  5082. */
  5083. virtual void writeInt64BigEndian (int64 value);
  5084. /** Writes a 32-bit floating point value to the stream.
  5085. The binary 32-bit encoding of the float is written as a little-endian int.
  5086. @see InputStream::readFloat
  5087. */
  5088. virtual void writeFloat (float value);
  5089. /** Writes a 32-bit floating point value to the stream.
  5090. The binary 32-bit encoding of the float is written as a big-endian int.
  5091. @see InputStream::readFloatBigEndian
  5092. */
  5093. virtual void writeFloatBigEndian (float value);
  5094. /** Writes a 64-bit floating point value to the stream.
  5095. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  5096. @see InputStream::readDouble
  5097. */
  5098. virtual void writeDouble (double value);
  5099. /** Writes a 64-bit floating point value to the stream.
  5100. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  5101. @see InputStream::readDoubleBigEndian
  5102. */
  5103. virtual void writeDoubleBigEndian (double value);
  5104. /** Writes a condensed encoding of a 32-bit integer.
  5105. If you're storing a lot of integers which are unlikely to have very large values,
  5106. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  5107. under 0xffff only 3 bytes, etc.
  5108. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  5109. @see InputStream::readCompressedInt
  5110. */
  5111. virtual void writeCompressedInt (int value);
  5112. /** Stores a string in the stream.
  5113. This isn't the method to use if you're trying to append text to the end of a
  5114. text-file! It's intended for storing a string for later retrieval
  5115. by InputStream::readString.
  5116. It writes the string to the stream as UTF8, with a null character terminating it.
  5117. For appending text to a file, instead use writeText, printf, or operator<<
  5118. @see InputStream::readString, writeText, printf, operator<<
  5119. */
  5120. virtual void writeString (const String& text);
  5121. /** Writes a string of text to the stream.
  5122. It can either write it as 8-bit system-encoded characters, or as unicode, and
  5123. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  5124. should only be done at the start of a file).
  5125. The method also replaces '\\n' characters in the text with '\\r\\n'.
  5126. */
  5127. virtual void writeText (const String& text,
  5128. const bool asUnicode,
  5129. const bool writeUnicodeHeaderBytes);
  5130. /** Writes a string of text to the stream.
  5131. @see writeText
  5132. */
  5133. virtual void printf (const char* format, ...);
  5134. /** Reads data from an input stream and writes it to this stream.
  5135. @param source the stream to read from
  5136. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  5137. less than zero, it will keep reading until the input
  5138. is exhausted)
  5139. */
  5140. virtual int writeFromInputStream (InputStream& source,
  5141. int maxNumBytesToWrite);
  5142. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  5143. virtual OutputStream& operator<< (const int number);
  5144. /** Writes a number to the stream as 8-bit characters in the default system encoding. */
  5145. virtual OutputStream& operator<< (const double number);
  5146. /** Writes a character to the stream. */
  5147. virtual OutputStream& operator<< (const char character);
  5148. /** Writes a null-terminated string to the stream. */
  5149. virtual OutputStream& operator<< (const char* const text);
  5150. /** Writes a null-terminated unicode text string to the stream, converting it
  5151. to 8-bit characters in the default system encoding. */
  5152. virtual OutputStream& operator<< (const juce_wchar* const text);
  5153. /** Writes a string to the stream as 8-bit characters in the default system encoding. */
  5154. virtual OutputStream& operator<< (const String& text);
  5155. juce_UseDebuggingNewOperator
  5156. protected:
  5157. OutputStream() throw();
  5158. };
  5159. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  5160. /********* End of inlined file: juce_OutputStream.h *********/
  5161. /********* Start of inlined file: juce_File.h *********/
  5162. #ifndef __JUCE_FILE_JUCEHEADER__
  5163. #define __JUCE_FILE_JUCEHEADER__
  5164. /********* Start of inlined file: juce_Time.h *********/
  5165. #ifndef __JUCE_TIME_JUCEHEADER__
  5166. #define __JUCE_TIME_JUCEHEADER__
  5167. /********* Start of inlined file: juce_RelativeTime.h *********/
  5168. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5169. #define __JUCE_RELATIVETIME_JUCEHEADER__
  5170. /** A relative measure of time.
  5171. The time is stored as a number of seconds, at double-precision floating
  5172. point accuracy, and may be positive or negative.
  5173. If you need an absolute time, (i.e. a date + time), see the Time class.
  5174. */
  5175. class JUCE_API RelativeTime
  5176. {
  5177. public:
  5178. /** Creates a RelativeTime.
  5179. @param seconds the number of seconds, which may be +ve or -ve.
  5180. @see milliseconds, minutes, hours, days, weeks
  5181. */
  5182. explicit RelativeTime (const double seconds = 0.0) throw();
  5183. /** Copies another relative time. */
  5184. RelativeTime (const RelativeTime& other) throw();
  5185. /** Copies another relative time. */
  5186. const RelativeTime& operator= (const RelativeTime& other) throw();
  5187. /** Destructor. */
  5188. ~RelativeTime() throw();
  5189. /** Creates a new RelativeTime object representing a number of milliseconds.
  5190. @see minutes, hours, days, weeks
  5191. */
  5192. static const RelativeTime milliseconds (const int milliseconds) throw();
  5193. /** Creates a new RelativeTime object representing a number of milliseconds.
  5194. @see minutes, hours, days, weeks
  5195. */
  5196. static const RelativeTime milliseconds (const int64 milliseconds) throw();
  5197. /** Creates a new RelativeTime object representing a number of minutes.
  5198. @see milliseconds, hours, days, weeks
  5199. */
  5200. static const RelativeTime minutes (const double numberOfMinutes) throw();
  5201. /** Creates a new RelativeTime object representing a number of hours.
  5202. @see milliseconds, minutes, days, weeks
  5203. */
  5204. static const RelativeTime hours (const double numberOfHours) throw();
  5205. /** Creates a new RelativeTime object representing a number of days.
  5206. @see milliseconds, minutes, hours, weeks
  5207. */
  5208. static const RelativeTime days (const double numberOfDays) throw();
  5209. /** Creates a new RelativeTime object representing a number of weeks.
  5210. @see milliseconds, minutes, hours, days
  5211. */
  5212. static const RelativeTime weeks (const double numberOfWeeks) throw();
  5213. /** Returns the number of milliseconds this time represents.
  5214. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  5215. */
  5216. int64 inMilliseconds() const throw();
  5217. /** Returns the number of seconds this time represents.
  5218. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  5219. */
  5220. double inSeconds() const throw() { return seconds; }
  5221. /** Returns the number of minutes this time represents.
  5222. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  5223. */
  5224. double inMinutes() const throw();
  5225. /** Returns the number of hours this time represents.
  5226. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  5227. */
  5228. double inHours() const throw();
  5229. /** Returns the number of days this time represents.
  5230. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  5231. */
  5232. double inDays() const throw();
  5233. /** Returns the number of weeks this time represents.
  5234. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  5235. */
  5236. double inWeeks() const throw();
  5237. /** Returns a readable textual description of the time.
  5238. The exact format of the string returned will depend on
  5239. the magnitude of the time - e.g.
  5240. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  5241. so that only the two most significant units are printed.
  5242. The returnValueForZeroTime value is the result that is returned if the
  5243. length is zero. Depending on your application you might want to use this
  5244. to return something more relevant like "empty" or "0 secs", etc.
  5245. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  5246. */
  5247. const String getDescription (const String& returnValueForZeroTime = JUCE_T("0")) const throw();
  5248. /** Compares two RelativeTimes. */
  5249. bool operator== (const RelativeTime& other) const throw();
  5250. /** Compares two RelativeTimes. */
  5251. bool operator!= (const RelativeTime& other) const throw();
  5252. /** Compares two RelativeTimes. */
  5253. bool operator> (const RelativeTime& other) const throw();
  5254. /** Compares two RelativeTimes. */
  5255. bool operator< (const RelativeTime& other) const throw();
  5256. /** Compares two RelativeTimes. */
  5257. bool operator>= (const RelativeTime& other) const throw();
  5258. /** Compares two RelativeTimes. */
  5259. bool operator<= (const RelativeTime& other) const throw();
  5260. /** Adds another RelativeTime to this one and returns the result. */
  5261. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  5262. /** Subtracts another RelativeTime from this one and returns the result. */
  5263. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  5264. /** Adds a number of seconds to this RelativeTime and returns the result. */
  5265. const RelativeTime operator+ (const double secondsToAdd) const throw();
  5266. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  5267. const RelativeTime operator- (const double secondsToSubtract) const throw();
  5268. /** Adds another RelativeTime to this one. */
  5269. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  5270. /** Subtracts another RelativeTime from this one. */
  5271. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  5272. /** Adds a number of seconds to this time. */
  5273. const RelativeTime& operator+= (const double secondsToAdd) throw();
  5274. /** Subtracts a number of seconds from this time. */
  5275. const RelativeTime& operator-= (const double secondsToSubtract) throw();
  5276. juce_UseDebuggingNewOperator
  5277. private:
  5278. double seconds;
  5279. };
  5280. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  5281. /********* End of inlined file: juce_RelativeTime.h *********/
  5282. /**
  5283. Holds an absolute date and time.
  5284. Internally, the time is stored at millisecond precision.
  5285. @see RelativeTime
  5286. */
  5287. class JUCE_API Time
  5288. {
  5289. public:
  5290. /** Creates a Time object.
  5291. This default constructor creates a time of 1st January 1970, (which is
  5292. represented internally as 0ms).
  5293. To create a time object representing the current time, use getCurrentTime().
  5294. @see getCurrentTime
  5295. */
  5296. Time() throw();
  5297. /** Creates a copy of another Time object. */
  5298. Time (const Time& other) throw();
  5299. /** Creates a time based on a number of milliseconds.
  5300. The internal millisecond count is set to 0 (1st January 1970). To create a
  5301. time object set to the current time, use getCurrentTime().
  5302. @param millisecondsSinceEpoch the number of milliseconds since the unix
  5303. 'epoch' (midnight Jan 1st 1970).
  5304. @see getCurrentTime, currentTimeMillis
  5305. */
  5306. Time (const int64 millisecondsSinceEpoch) throw();
  5307. /** Creates a time from a set of date components.
  5308. The timezone is assumed to be whatever the system is using as its locale.
  5309. @param year the year, in 4-digit format, e.g. 2004
  5310. @param month the month, in the range 0 to 11
  5311. @param day the day of the month, in the range 1 to 31
  5312. @param hours hours in 24-hour clock format, 0 to 23
  5313. @param minutes minutes 0 to 59
  5314. @param seconds seconds 0 to 59
  5315. @param milliseconds milliseconds 0 to 999
  5316. @param useLocalTime if true, encode using the current machine's local time; if
  5317. false, it will always work in GMT.
  5318. */
  5319. Time (const int year,
  5320. const int month,
  5321. const int day,
  5322. const int hours,
  5323. const int minutes,
  5324. const int seconds = 0,
  5325. const int milliseconds = 0,
  5326. const bool useLocalTime = true) throw();
  5327. /** Destructor. */
  5328. ~Time() throw();
  5329. /** Copies this time from another one. */
  5330. const Time& operator= (const Time& other) throw();
  5331. /** Returns a Time object that is set to the current system time.
  5332. @see currentTimeMillis
  5333. */
  5334. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  5335. /** Returns the time as a number of milliseconds.
  5336. @returns the number of milliseconds this Time object represents, since
  5337. midnight jan 1st 1970.
  5338. @see getMilliseconds
  5339. */
  5340. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  5341. /** Returns the year.
  5342. A 4-digit format is used, e.g. 2004.
  5343. */
  5344. int getYear() const throw();
  5345. /** Returns the number of the month.
  5346. The value returned is in the range 0 to 11.
  5347. @see getMonthName
  5348. */
  5349. int getMonth() const throw();
  5350. /** Returns the name of the month.
  5351. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  5352. it'll return the long form, e.g. "January"
  5353. @see getMonth
  5354. */
  5355. const String getMonthName (const bool threeLetterVersion) const throw();
  5356. /** Returns the day of the month.
  5357. The value returned is in the range 1 to 31.
  5358. */
  5359. int getDayOfMonth() const throw();
  5360. /** Returns the number of the day of the week.
  5361. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  5362. */
  5363. int getDayOfWeek() const throw();
  5364. /** Returns the name of the weekday.
  5365. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  5366. false, it'll return the full version, e.g. "Tuesday".
  5367. */
  5368. const String getWeekdayName (const bool threeLetterVersion) const throw();
  5369. /** Returns the number of hours since midnight.
  5370. This is in 24-hour clock format, in the range 0 to 23.
  5371. @see getHoursInAmPmFormat, isAfternoon
  5372. */
  5373. int getHours() const throw();
  5374. /** Returns true if the time is in the afternoon.
  5375. So it returns true for "PM", false for "AM".
  5376. @see getHoursInAmPmFormat, getHours
  5377. */
  5378. bool isAfternoon() const throw();
  5379. /** Returns the hours in 12-hour clock format.
  5380. This will return a value 1 to 12 - use isAfternoon() to find out
  5381. whether this is in the afternoon or morning.
  5382. @see getHours, isAfternoon
  5383. */
  5384. int getHoursInAmPmFormat() const throw();
  5385. /** Returns the number of minutes, 0 to 59. */
  5386. int getMinutes() const throw();
  5387. /** Returns the number of seconds, 0 to 59. */
  5388. int getSeconds() const throw();
  5389. /** Returns the number of milliseconds, 0 to 999.
  5390. Unlike toMilliseconds(), this just returns the position within the
  5391. current second rather than the total number since the epoch.
  5392. @see toMilliseconds
  5393. */
  5394. int getMilliseconds() const throw();
  5395. /** Returns true if the local timezone uses a daylight saving correction. */
  5396. bool isDaylightSavingTime() const throw();
  5397. /** Returns a 3-character string to indicate the local timezone. */
  5398. const String getTimeZone() const throw();
  5399. /** Quick way of getting a string version of a date and time.
  5400. For a more powerful way of formatting the date and time, see the formatted() method.
  5401. @param includeDate whether to include the date in the string
  5402. @param includeTime whether to include the time in the string
  5403. @param includeSeconds if the time is being included, this provides an option not to include
  5404. the seconds in it
  5405. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  5406. hour notation.
  5407. @see formatted
  5408. */
  5409. const String toString (const bool includeDate,
  5410. const bool includeTime,
  5411. const bool includeSeconds = true,
  5412. const bool use24HourClock = false) const throw();
  5413. /** Converts this date/time to a string with a user-defined format.
  5414. This uses the C strftime() function to format this time as a string. To save you
  5415. looking it up, these are the escape codes that strftime uses (other codes might
  5416. work on some platforms and not others, but these are the common ones):
  5417. %a is replaced by the locale's abbreviated weekday name.
  5418. %A is replaced by the locale's full weekday name.
  5419. %b is replaced by the locale's abbreviated month name.
  5420. %B is replaced by the locale's full month name.
  5421. %c is replaced by the locale's appropriate date and time representation.
  5422. %d is replaced by the day of the month as a decimal number [01,31].
  5423. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  5424. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  5425. %j is replaced by the day of the year as a decimal number [001,366].
  5426. %m is replaced by the month as a decimal number [01,12].
  5427. %M is replaced by the minute as a decimal number [00,59].
  5428. %p is replaced by the locale's equivalent of either a.m. or p.m.
  5429. %S is replaced by the second as a decimal number [00,61].
  5430. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  5431. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  5432. %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.
  5433. %x is replaced by the locale's appropriate date representation.
  5434. %X is replaced by the locale's appropriate time representation.
  5435. %y is replaced by the year without century as a decimal number [00,99].
  5436. %Y is replaced by the year with century as a decimal number.
  5437. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  5438. %% is replaced by %.
  5439. @see toString
  5440. */
  5441. const String formatted (const tchar* const format) const throw();
  5442. /** Adds a RelativeTime to this time and returns the result. */
  5443. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  5444. /** Subtracts a RelativeTime from this time and returns the result. */
  5445. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  5446. /** Returns the relative time difference between this time and another one. */
  5447. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  5448. /** Compares two Time objects. */
  5449. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  5450. /** Compares two Time objects. */
  5451. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  5452. /** Compares two Time objects. */
  5453. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  5454. /** Compares two Time objects. */
  5455. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  5456. /** Compares two Time objects. */
  5457. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  5458. /** Compares two Time objects. */
  5459. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  5460. /** Tries to set the computer's clock.
  5461. @returns true if this succeeds, although depending on the system, the
  5462. application might not have sufficient privileges to do this.
  5463. */
  5464. bool setSystemTimeToThisTime() const throw();
  5465. /** Returns the name of a day of the week.
  5466. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  5467. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  5468. false, it'll return the full version, e.g. "Tuesday".
  5469. */
  5470. static const String getWeekdayName (int dayNumber,
  5471. const bool threeLetterVersion) throw();
  5472. /** Returns the name of one of the months.
  5473. @param monthNumber the month, 0 to 11
  5474. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  5475. it'll return the long form, e.g. "January"
  5476. */
  5477. static const String getMonthName (int monthNumber,
  5478. const bool threeLetterVersion) throw();
  5479. // Static methods for getting system timers directly..
  5480. /** Returns the current system time.
  5481. Returns the number of milliseconds since midnight jan 1st 1970.
  5482. Should be accurate to within a few millisecs, depending on platform,
  5483. hardware, etc.
  5484. */
  5485. static int64 currentTimeMillis() throw();
  5486. /** Returns the number of millisecs since system startup.
  5487. Should be accurate to within a few millisecs, depending on platform,
  5488. hardware, etc.
  5489. @see getApproximateMillisecondCounter
  5490. */
  5491. static uint32 getMillisecondCounter() throw();
  5492. /** Returns the number of millisecs since system startup.
  5493. Same as getMillisecondCounter(), but returns a more accurate value, using
  5494. the high-res timer.
  5495. @see getMillisecondCounter
  5496. */
  5497. static double getMillisecondCounterHiRes() throw();
  5498. /** Waits until the getMillisecondCounter() reaches a given value.
  5499. This will make the thread sleep as efficiently as it can while it's waiting.
  5500. */
  5501. static void waitForMillisecondCounter (const uint32 targetTime) throw();
  5502. /** Less-accurate but faster version of getMillisecondCounter().
  5503. This will return the last value that getMillisecondCounter() returned, so doesn't
  5504. need to make a system call, but is less accurate - it shouldn't be more than
  5505. 100ms away from the correct time, though, so is still accurate enough for a
  5506. lot of purposes.
  5507. @see getMillisecondCounter
  5508. */
  5509. static uint32 getApproximateMillisecondCounter() throw();
  5510. // High-resolution timers..
  5511. /** Returns the current high-resolution counter's tick-count.
  5512. This is a similar idea to getMillisecondCounter(), but with a higher
  5513. resolution.
  5514. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  5515. secondsToHighResolutionTicks
  5516. */
  5517. static int64 getHighResolutionTicks() throw();
  5518. /** Returns the resolution of the high-resolution counter in ticks per second.
  5519. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  5520. secondsToHighResolutionTicks
  5521. */
  5522. static int64 getHighResolutionTicksPerSecond() throw();
  5523. /** Converts a number of high-resolution ticks into seconds.
  5524. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  5525. secondsToHighResolutionTicks
  5526. */
  5527. static double highResolutionTicksToSeconds (const int64 ticks) throw();
  5528. /** Converts a number seconds into high-resolution ticks.
  5529. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  5530. highResolutionTicksToSeconds
  5531. */
  5532. static int64 secondsToHighResolutionTicks (const double seconds) throw();
  5533. private:
  5534. int64 millisSinceEpoch;
  5535. };
  5536. #endif // __JUCE_TIME_JUCEHEADER__
  5537. /********* End of inlined file: juce_Time.h *********/
  5538. class FileInputStream;
  5539. class FileOutputStream;
  5540. /**
  5541. Represents a local file or directory.
  5542. This class encapsulates the absolute pathname of a file or directory, and
  5543. has methods for finding out about the file and changing its properties.
  5544. To read or write to the file, there are methods for returning an input or
  5545. output stream.
  5546. @see FileInputStream, FileOutputStream
  5547. */
  5548. class JUCE_API File
  5549. {
  5550. public:
  5551. /** Creates an (invalid) file object.
  5552. The file is initially set to an empty path, so getFullPath() will return
  5553. an empty string, and comparing the file to File::nonexistent will return
  5554. true.
  5555. You can use its operator= method to point it at a proper file.
  5556. */
  5557. File() throw() {}
  5558. /** Creates a file from an absolute path.
  5559. If the path supplied is a relative path, it is taken to be relative
  5560. to the current working directory (see File::getCurrentWorkingDirectory()),
  5561. but this isn't a recommended way of creating a file, because you
  5562. never know what the CWD is going to be.
  5563. On the Mac/Linux, the path can include "~" notation for referring to
  5564. user home directories.
  5565. */
  5566. File (const String& path) throw();
  5567. /** Creates a copy of another file object. */
  5568. File (const File& other) throw();
  5569. /** Destructor. */
  5570. ~File() throw() {}
  5571. /** Sets the file based on an absolute pathname.
  5572. If the path supplied is a relative path, it is taken to be relative
  5573. to the current working directory (see File::getCurrentWorkingDirectory()),
  5574. but this isn't a recommended way of creating a file, because you
  5575. never know what the CWD is going to be.
  5576. On the Mac/Linux, the path can include "~" notation for referring to
  5577. user home directories.
  5578. */
  5579. const File& operator= (const String& newFilePath) throw();
  5580. /** Copies from another file object. */
  5581. const File& operator= (const File& otherFile) throw();
  5582. /** This static constant is used for referring to an 'invalid' file. */
  5583. static const File nonexistent;
  5584. /** Checks whether the file actually exists.
  5585. @returns true if the file exists, either as a file or a directory.
  5586. @see existsAsFile, isDirectory
  5587. */
  5588. bool exists() const throw();
  5589. /** Checks whether the file exists and is a file rather than a directory.
  5590. @returns true only if this is a real file, false if it's a directory
  5591. or doesn't exist
  5592. @see exists, isDirectory
  5593. */
  5594. bool existsAsFile() const throw();
  5595. /** Checks whether the file is a directory that exists.
  5596. @returns true only if the file is a directory which actually exists, so
  5597. false if it's a file or doesn't exist at all
  5598. @see exists, existsAsFile
  5599. */
  5600. bool isDirectory() const throw();
  5601. /** Returns the size of the file in bytes.
  5602. @returns the number of bytes in the file, or 0 if it doesn't exist.
  5603. */
  5604. int64 getSize() const throw();
  5605. /** Utility function to convert a file size in bytes to a neat string description.
  5606. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  5607. 2000000 would produce "2 MB", etc.
  5608. */
  5609. static const String descriptionOfSizeInBytes (const int64 bytes);
  5610. /** Returns the complete, absolute path of this file.
  5611. This includes the filename and all its parent folders. On Windows it'll
  5612. also include the drive letter prefix; on Mac or Linux it'll be a complete
  5613. path starting from the root folder.
  5614. If you just want the file's name, you should use getFileName() or
  5615. getFileNameWithoutExtension().
  5616. @see getFileName, getRelativePathFrom
  5617. */
  5618. const String& getFullPathName() const throw() { return fullPath; }
  5619. /** Returns the last section of the pathname.
  5620. Returns just the final part of the path - e.g. if the whole path
  5621. is "/moose/fish/foo.txt" this will return "foo.txt".
  5622. For a directory, it returns the final part of the path - e.g. for the
  5623. directory "/moose/fish" it'll return "fish".
  5624. If the filename begins with a dot, it'll return the whole filename, e.g. for
  5625. "/moose/.fish", it'll return ".fish"
  5626. @see getFullPathName, getFileNameWithoutExtension
  5627. */
  5628. const String getFileName() const throw();
  5629. /** Creates a relative path that refers to a file relatively to a given directory.
  5630. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  5631. would return "../../foo.txt".
  5632. If it's not possible to navigate from one file to the other, an absolute
  5633. path is returned. If the paths are invalid, an empty string may also be
  5634. returned.
  5635. @param directoryToBeRelativeTo the directory which the resultant string will
  5636. be relative to. If this is actually a file rather than
  5637. a directory, its parent directory will be used instead.
  5638. If it doesn't exist, it's assumed to be a directory.
  5639. @see getChildFile, isAbsolutePath
  5640. */
  5641. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const throw();
  5642. /** Returns the file's extension.
  5643. Returns the file extension of this file, also including the dot.
  5644. e.g. "/moose/fish/foo.txt" would return ".txt"
  5645. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  5646. */
  5647. const String getFileExtension() const throw();
  5648. /** Checks whether the file has a given extension.
  5649. @param extensionToTest the extension to look for - it doesn't matter whether or
  5650. not this string has a dot at the start, so ".wav" and "wav"
  5651. will have the same effect. The comparison used is
  5652. case-insensitve. To compare with multiple extensions, this
  5653. parameter can contain multiple strings, separated by semi-colons -
  5654. so, for example: hasFileExtension (".jpeg;png;gif") would return
  5655. true if the file has any of those three extensions.
  5656. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  5657. */
  5658. bool hasFileExtension (const String& extensionToTest) const throw();
  5659. /** Returns a version of this file with a different file extension.
  5660. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  5661. @param newExtension the new extension, either with or without a dot at the start (this
  5662. doesn't make any difference). To get remove a file's extension altogether,
  5663. pass an empty string into this function.
  5664. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  5665. */
  5666. const File withFileExtension (const String& newExtension) const throw();
  5667. /** Returns the last part of the filename, without its file extension.
  5668. e.g. for "/moose/fish/foo.txt" this will return "foo".
  5669. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  5670. */
  5671. const String getFileNameWithoutExtension() const throw();
  5672. /** Returns a 32-bit hash-code that identifies this file.
  5673. This is based on the filename. Obviously it's possible, although unlikely, that
  5674. two files will have the same hash-code.
  5675. */
  5676. int hashCode() const throw();
  5677. /** Returns a 64-bit hash-code that identifies this file.
  5678. This is based on the filename. Obviously it's possible, although unlikely, that
  5679. two files will have the same hash-code.
  5680. */
  5681. int64 hashCode64() const throw();
  5682. /** Returns a file based on a relative path.
  5683. This will find a child file or directory of the current object.
  5684. e.g.
  5685. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  5686. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  5687. If the string is actually an absolute path, it will be treated as such, e.g.
  5688. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  5689. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  5690. */
  5691. const File getChildFile (String relativePath) const throw();
  5692. /** Returns a file which is in the same directory as this one.
  5693. This is equivalent to getParentDirectory().getChildFile (name).
  5694. @see getChildFile, getParentDirectory
  5695. */
  5696. const File getSiblingFile (const String& siblingFileName) const throw();
  5697. /** Returns the directory that contains this file or directory.
  5698. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  5699. */
  5700. const File getParentDirectory() const throw();
  5701. /** Checks whether a file is somewhere inside a directory.
  5702. Returns true if this file is somewhere inside a subdirectory of the directory
  5703. that is passed in. Neither file actually has to exist, because the function
  5704. just checks the paths for similarities.
  5705. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  5706. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  5707. */
  5708. bool isAChildOf (const File& potentialParentDirectory) const throw();
  5709. /** Chooses a filename relative to this one that doesn't already exist.
  5710. If this file is a directory, this will return a child file of this
  5711. directory that doesn't exist, by adding numbers to a prefix and suffix until
  5712. it finds one that isn't already there.
  5713. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  5714. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  5715. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  5716. @param prefix the string to use for the filename before the number
  5717. @param suffix the string to add to the filename after the number
  5718. @param putNumbersInBrackets if true, this will create filenames in the
  5719. format "prefix(number)suffix", if false, it will leave the
  5720. brackets out.
  5721. */
  5722. const File getNonexistentChildFile (const String& prefix,
  5723. const String& suffix,
  5724. bool putNumbersInBrackets = true) const throw();
  5725. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  5726. If this file doesn't exist, this will just return itself, otherwise it
  5727. will return an appropriate sibling that doesn't exist, e.g. if a file
  5728. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  5729. @param putNumbersInBrackets whether to add brackets around the numbers that
  5730. get appended to the new filename.
  5731. */
  5732. const File getNonexistentSibling (const bool putNumbersInBrackets = true) const throw();
  5733. /** Compares the pathnames for two files. */
  5734. bool operator== (const File& otherFile) const throw();
  5735. /** Compares the pathnames for two files. */
  5736. bool operator!= (const File& otherFile) const throw();
  5737. /** Checks whether a file can be created or written to.
  5738. @returns true if it's possible to create and write to this file. If the file
  5739. doesn't already exist, this will check its parent directory to
  5740. see if writing is allowed.
  5741. @see setReadOnly
  5742. */
  5743. bool hasWriteAccess() const throw();
  5744. /** Changes the write-permission of a file or directory.
  5745. @param shouldBeReadOnly whether to add or remove write-permission
  5746. @param applyRecursively if the file is a directory and this is true, it will
  5747. recurse through all the subfolders changing the permissions
  5748. of all files
  5749. @returns true if it manages to change the file's permissions.
  5750. @see hasWriteAccess
  5751. */
  5752. bool setReadOnly (const bool shouldBeReadOnly,
  5753. const bool applyRecursively = false) const throw();
  5754. /** Returns true if this file is a hidden or system file.
  5755. The criteria for deciding whether a file is hidden are platform-dependent.
  5756. */
  5757. bool isHidden() const throw();
  5758. /** If this file is a link, this returns the file that it points to.
  5759. If this file isn't actually link, it'll just return itself.
  5760. */
  5761. const File getLinkedTarget() const throw();
  5762. /** Returns the last modification time of this file.
  5763. @returns the time, or an invalid time if the file doesn't exist.
  5764. @see setLastModificationTime, getLastAccessTime, getCreationTime
  5765. */
  5766. const Time getLastModificationTime() const throw();
  5767. /** Returns the last time this file was accessed.
  5768. @returns the time, or an invalid time if the file doesn't exist.
  5769. @see setLastAccessTime, getLastModificationTime, getCreationTime
  5770. */
  5771. const Time getLastAccessTime() const throw();
  5772. /** Returns the time that this file was created.
  5773. @returns the time, or an invalid time if the file doesn't exist.
  5774. @see getLastModificationTime, getLastAccessTime
  5775. */
  5776. const Time getCreationTime() const throw();
  5777. /** Changes the modification time for this file.
  5778. @param newTime the time to apply to the file
  5779. @returns true if it manages to change the file's time.
  5780. @see getLastModificationTime, setLastAccessTime, setCreationTime
  5781. */
  5782. bool setLastModificationTime (const Time& newTime) const throw();
  5783. /** Changes the last-access time for this file.
  5784. @param newTime the time to apply to the file
  5785. @returns true if it manages to change the file's time.
  5786. @see getLastAccessTime, setLastModificationTime, setCreationTime
  5787. */
  5788. bool setLastAccessTime (const Time& newTime) const throw();
  5789. /** Changes the creation date for this file.
  5790. @param newTime the time to apply to the file
  5791. @returns true if it manages to change the file's time.
  5792. @see getCreationTime, setLastModificationTime, setLastAccessTime
  5793. */
  5794. bool setCreationTime (const Time& newTime) const throw();
  5795. /** If possible, this will try to create a version string for the given file.
  5796. The OS may be able to look at the file and give a version for it - e.g. with
  5797. executables, bundles, dlls, etc. If no version is available, this will
  5798. return an empty string.
  5799. */
  5800. const String getVersion() const throw();
  5801. /** Creates an empty file if it doesn't already exist.
  5802. If the file that this object refers to doesn't exist, this will create a file
  5803. of zero size.
  5804. If it already exists or is a directory, this method will do nothing.
  5805. @returns true if the file has been created (or if it already existed).
  5806. @see createDirectory
  5807. */
  5808. bool create() const throw();
  5809. /** Creates a new directory for this filename.
  5810. This will try to create the file as a directory, and fill also create
  5811. any parent directories it needs in order to complete the operation.
  5812. @returns true if the directory has been created successfully, (or if it
  5813. already existed beforehand).
  5814. @see create
  5815. */
  5816. bool createDirectory() const throw();
  5817. /** Deletes a file.
  5818. If this file is actually a directory, it may not be deleted correctly if it
  5819. contains files. See deleteRecursively() as a better way of deleting directories.
  5820. @returns true if the file has been successfully deleted (or if it didn't exist to
  5821. begin with).
  5822. @see deleteRecursively
  5823. */
  5824. bool deleteFile() const throw();
  5825. /** Deletes a file or directory and all its subdirectories.
  5826. If this file is a directory, this will try to delete it and all its subfolders. If
  5827. it's just a file, it will just try to delete the file.
  5828. @returns true if the file and all its subfolders have been successfully deleted
  5829. (or if it didn't exist to begin with).
  5830. @see deleteFile
  5831. */
  5832. bool deleteRecursively() const throw();
  5833. /** Moves this file or folder to the trash.
  5834. @returns true if the operation succeeded. It could fail if the trash is full, or
  5835. if the file is write-protected, so you should check the return value
  5836. and act appropriately.
  5837. */
  5838. bool moveToTrash() const throw();
  5839. /** Moves or renames a file.
  5840. Tries to move a file to a different location.
  5841. If the target file already exists, this will attempt to delete it first, and
  5842. will fail if this can't be done.
  5843. Note that the destination file isn't the directory to put it in, it's the actual
  5844. filename that you want the new file to have.
  5845. @returns true if the operation succeeds
  5846. */
  5847. bool moveFileTo (const File& targetLocation) const throw();
  5848. /** Copies a file.
  5849. Tries to copy a file to a different location.
  5850. If the target file already exists, this will attempt to delete it first, and
  5851. will fail if this can't be done.
  5852. @returns true if the operation succeeds
  5853. */
  5854. bool copyFileTo (const File& targetLocation) const throw();
  5855. /** Copies a directory.
  5856. Tries to copy an entire directory, recursively.
  5857. If this file isn't a directory or if any target files can't be created, this
  5858. will return false.
  5859. @param newDirectory the directory that this one should be copied to. Note that this
  5860. is the name of the actual directory to create, not the directory
  5861. into which the new one should be placed, so there must be enough
  5862. write privileges to create it if it doesn't exist. Any files inside
  5863. it will be overwritten by similarly named ones that are copied.
  5864. */
  5865. bool copyDirectoryTo (const File& newDirectory) const throw();
  5866. /** Used in file searching, to specify whether to return files, directories, or both.
  5867. */
  5868. enum TypesOfFileToFind
  5869. {
  5870. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  5871. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  5872. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  5873. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  5874. };
  5875. /** Searches inside a directory for files matching a wildcard pattern.
  5876. Assuming that this file is a directory, this method will search it
  5877. for either files or subdirectories whose names match a filename pattern.
  5878. @param results an array to which File objects will be added for the
  5879. files that the search comes up with
  5880. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5881. return files, directories, or both. If the ignoreHiddenFiles flag
  5882. is also added to this value, hidden files won't be returned
  5883. @param searchRecursively if true, all subdirectories will be recursed into to do
  5884. an exhaustive search
  5885. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5886. @returns the number of results that have been found
  5887. @see getNumberOfChildFiles, DirectoryIterator
  5888. */
  5889. int findChildFiles (OwnedArray<File>& results,
  5890. const int whatToLookFor,
  5891. const bool searchRecursively,
  5892. const String& wildCardPattern = JUCE_T("*")) const throw();
  5893. /** Searches inside a directory and counts how many files match a wildcard pattern.
  5894. Assuming that this file is a directory, this method will search it
  5895. for either files or subdirectories whose names match a filename pattern,
  5896. and will return the number of matches found.
  5897. This isn't a recursive call, and will only search this directory, not
  5898. its children.
  5899. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  5900. count files, directories, or both. If the ignoreHiddenFiles flag
  5901. is also added to this value, hidden files won't be counted
  5902. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  5903. @returns the number of matches found
  5904. @see findChildFiles, DirectoryIterator
  5905. */
  5906. int getNumberOfChildFiles (const int whatToLookFor,
  5907. const String& wildCardPattern = JUCE_T("*")) const throw();
  5908. /** Returns true if this file is a directory that contains one or more subdirectories.
  5909. @see isDirectory, findChildFiles
  5910. */
  5911. bool containsSubDirectories() const throw();
  5912. /** Creates a stream to read from this file.
  5913. @returns a stream that will read from this file (initially positioned at the
  5914. start of the file), or 0 if the file can't be opened for some reason
  5915. @see createOutputStream, loadFileAsData
  5916. */
  5917. FileInputStream* createInputStream() const throw();
  5918. /** Creates a stream to write to this file.
  5919. If the file exists, the stream that is returned will be positioned ready for
  5920. writing at the end of the file, so you might want to use deleteFile() first
  5921. to write to an empty file.
  5922. @returns a stream that will write to this file (initially positioned at the
  5923. end of the file), or 0 if the file can't be opened for some reason
  5924. @see createInputStream, printf, appendData, appendText
  5925. */
  5926. FileOutputStream* createOutputStream (const int bufferSize = 0x8000) const throw();
  5927. /** Loads a file's contents into memory as a block of binary data.
  5928. Of course, trying to load a very large file into memory will blow up, so
  5929. it's better to check first.
  5930. @param result the data block to which the file's contents should be appended - note
  5931. that if the memory block might already contain some data, you
  5932. might want to clear it first
  5933. @returns true if the file could all be read into memory
  5934. */
  5935. bool loadFileAsData (MemoryBlock& result) const throw();
  5936. /** Reads a file into memory as a string.
  5937. Attempts to load the entire file as a zero-terminated string.
  5938. This makes use of InputStream::readEntireStreamAsString, which should
  5939. automatically cope with unicode/acsii file formats.
  5940. */
  5941. const String loadFileAsString() const throw();
  5942. /** Writes text to the end of the file.
  5943. This will try to do a printf to the file.
  5944. @returns false if it can't write to the file for some reason
  5945. */
  5946. bool printf (const tchar* format, ...) const throw();
  5947. /** Appends a block of binary data to the end of the file.
  5948. This will try to write the given buffer to the end of the file.
  5949. @returns false if it can't write to the file for some reason
  5950. */
  5951. bool appendData (const void* const dataToAppend,
  5952. const int numberOfBytes) const throw();
  5953. /** Replaces this file's contents with a given block of data.
  5954. This will delete the file and replace it with the given data.
  5955. A nice feature of this method is that it's safe - instead of deleting
  5956. the file first and then re-writing it, it creates a new temporary file,
  5957. writes the data to that, and then moves the new file to replace the existing
  5958. file. This means that if the power gets pulled out or something crashes,
  5959. you're a lot less likely to end up with an empty file..
  5960. Returns true if the operation succeeds, or false if it fails.
  5961. @see appendText
  5962. */
  5963. bool replaceWithData (const void* const dataToWrite,
  5964. const int numberOfBytes) const throw();
  5965. /** Appends a string to the end of the file.
  5966. This will try to append a text string to the file, as either 16-bit unicode
  5967. or 8-bit characters in the default system encoding.
  5968. It can also write the 'ff fe' unicode header bytes before the text to indicate
  5969. the endianness of the file.
  5970. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  5971. @see replaceWithText
  5972. */
  5973. bool appendText (const String& textToAppend,
  5974. const bool asUnicode = false,
  5975. const bool writeUnicodeHeaderBytes = false) const throw();
  5976. /** Replaces this file's contents with a given text string.
  5977. This will delete the file and replace it with the given text.
  5978. A nice feature of this method is that it's safe - instead of deleting
  5979. the file first and then re-writing it, it creates a new temporary file,
  5980. writes the text to that, and then moves the new file to replace the existing
  5981. file. This means that if the power gets pulled out or something crashes,
  5982. you're a lot less likely to end up with an empty file..
  5983. For an explanation of the parameters here, see the appendText() method.
  5984. Returns true if the operation succeeds, or false if it fails.
  5985. @see appendText
  5986. */
  5987. bool replaceWithText (const String& textToWrite,
  5988. const bool asUnicode = false,
  5989. const bool writeUnicodeHeaderBytes = false) const throw();
  5990. /** Creates a set of files to represent each file root.
  5991. e.g. on Windows this will create files for "c:\", "d:\" etc according
  5992. to which ones are available. On the Mac/Linux, this will probably
  5993. just add a single entry for "/".
  5994. */
  5995. static void findFileSystemRoots (OwnedArray<File>& results) throw();
  5996. /** Finds the name of the drive on which this file lives.
  5997. @returns the volume label of the drive, or an empty string if this isn't possible
  5998. */
  5999. const String getVolumeLabel() const throw();
  6000. /** Returns the serial number of the volume on which this file lives.
  6001. @returns the serial number, or zero if there's a problem doing this
  6002. */
  6003. int getVolumeSerialNumber() const throw();
  6004. /** Returns the number of bytes free on the drive that this file lives on.
  6005. @returns the number of bytes free, or 0 if there's a problem finding this out
  6006. @see getVolumeTotalSize
  6007. */
  6008. int64 getBytesFreeOnVolume() const throw();
  6009. /** Returns the total size of the drive that contains this file.
  6010. @returns the total number of bytes that the volume can hold
  6011. @see getBytesFreeOnVolume
  6012. */
  6013. int64 getVolumeTotalSize() const throw();
  6014. /** Returns true if this file is on a CD or DVD drive. */
  6015. bool isOnCDRomDrive() const throw();
  6016. /** Returns true if this file is on a hard disk.
  6017. This will fail if it's a network drive, but will still be true for
  6018. removable hard-disks.
  6019. */
  6020. bool isOnHardDisk() const throw();
  6021. /** Returns true if this file is on a removable disk drive.
  6022. This might be a usb-drive, a CD-rom, or maybe a network drive.
  6023. */
  6024. bool isOnRemovableDrive() const throw();
  6025. /** Launches the file as a process.
  6026. - if the file is executable, this will run it.
  6027. - if it's a document of some kind, it will launch the document with its
  6028. default viewer application.
  6029. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  6030. @see revealToUser
  6031. */
  6032. bool startAsProcess (const String& parameters = String::empty) const throw();
  6033. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  6034. @see startAsProcess
  6035. */
  6036. void revealToUser() const throw();
  6037. /** A set of types of location that can be passed to the getSpecialLocation() method.
  6038. */
  6039. enum SpecialLocationType
  6040. {
  6041. /** The user's home folder. This is the same as using File ("~"). */
  6042. userHomeDirectory,
  6043. /** The user's default documents folder. On Windows, this might be the user's
  6044. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  6045. doesn't tend to have one of these, so it might just return their home folder.
  6046. */
  6047. userDocumentsDirectory,
  6048. /** The folder that contains the user's desktop objects. */
  6049. userDesktopDirectory,
  6050. /** The folder in which applications store their persistent user-specific settings.
  6051. On Windows, this might be "\Documents and Settings\username\Application Data".
  6052. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  6053. always create your own sub-folder to put them in, to avoid making a mess.
  6054. */
  6055. userApplicationDataDirectory,
  6056. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  6057. of the computer, rather than just the current user.
  6058. On the Mac it'll be "/Library", on Windows, it could be something like
  6059. "\Documents and Settings\All Users\Application Data".
  6060. Depending on the setup, this folder may be read-only.
  6061. */
  6062. commonApplicationDataDirectory,
  6063. /** The folder that should be used for temporary files.
  6064. Always delete them when you're finished, to keep the user's computer tidy!
  6065. */
  6066. tempDirectory,
  6067. /** Returns this application's executable file.
  6068. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6069. host app.
  6070. On the mac this will return the unix binary, not the package folder - see
  6071. currentApplicationFile for that.
  6072. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  6073. file link, invokedExecutableFile will return the name of the link.
  6074. */
  6075. currentExecutableFile,
  6076. /** Returns this application's location.
  6077. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6078. host app.
  6079. On the mac this will return the package folder (if it's in one), not the unix binary
  6080. that's inside it - compare with currentExecutableFile.
  6081. */
  6082. currentApplicationFile,
  6083. /** Returns the file that was invoked to launch this executable.
  6084. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  6085. will return the name of the link that was used, whereas currentExecutableFile will return
  6086. the actual location of the target executable.
  6087. */
  6088. invokedExecutableFile,
  6089. /** The directory in which applications normally get installed.
  6090. So on windows, this would be something like "c:\program files", on the
  6091. Mac "/Applications", or "/usr" on linux.
  6092. */
  6093. globalApplicationsDirectory,
  6094. /** The most likely place where a user might store their music files.
  6095. */
  6096. userMusicDirectory,
  6097. /** The most likely place where a user might store their movie files.
  6098. */
  6099. userMoviesDirectory,
  6100. };
  6101. /** Finds the location of a special type of file or directory, such as a home folder or
  6102. documents folder.
  6103. @see SpecialLocationType
  6104. */
  6105. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  6106. /** Returns a temporary file in the system's temp directory.
  6107. This will try to return the name of a non-existent temp file.
  6108. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  6109. */
  6110. static const File createTempFile (const String& fileNameEnding) throw();
  6111. /** Returns the current working directory.
  6112. @see setAsCurrentWorkingDirectory
  6113. */
  6114. static const File getCurrentWorkingDirectory() throw();
  6115. /** Sets the current working directory to be this file.
  6116. For this to work the file must point to a valid directory.
  6117. @returns true if the current directory has been changed.
  6118. @see getCurrentWorkingDirectory
  6119. */
  6120. bool setAsCurrentWorkingDirectory() const throw();
  6121. /** The system-specific file separator character.
  6122. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6123. */
  6124. static const tchar separator;
  6125. /** The system-specific file separator character, as a string.
  6126. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6127. */
  6128. static const tchar* separatorString;
  6129. /** Removes illegal characters from a filename.
  6130. This will return a copy of the given string after removing characters
  6131. that are not allowed in a legal filename, and possibly shortening the
  6132. string if it's too long.
  6133. Because this will remove slashes, don't use it on an absolute pathname.
  6134. @see createLegalPathName
  6135. */
  6136. static const String createLegalFileName (const String& fileNameToFix) throw();
  6137. /** Removes illegal characters from a pathname.
  6138. Similar to createLegalFileName(), but this won't remove slashes, so can
  6139. be used on a complete pathname.
  6140. @see createLegalFileName
  6141. */
  6142. static const String createLegalPathName (const String& pathNameToFix) throw();
  6143. /** Indicates whether filenames are case-sensitive on the current operating system.
  6144. */
  6145. static bool areFileNamesCaseSensitive();
  6146. /** Returns true if the string seems to be a fully-specified absolute path.
  6147. */
  6148. static bool isAbsolutePath (const String& path) throw();
  6149. juce_UseDebuggingNewOperator
  6150. private:
  6151. String fullPath;
  6152. // internal way of contructing a file without checking the path
  6153. friend class DirectoryIterator;
  6154. File (const String&, int) throw();
  6155. const String getPathUpToLastSlash() const throw();
  6156. };
  6157. #endif // __JUCE_FILE_JUCEHEADER__
  6158. /********* End of inlined file: juce_File.h *********/
  6159. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6160. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6161. will be the name of a pointer to each child element.
  6162. E.g. @code
  6163. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6164. forEachXmlChildElement (*myParentXml, child)
  6165. {
  6166. if (child->hasTagName ("FOO"))
  6167. doSomethingWithXmlElement (child);
  6168. }
  6169. @endcode
  6170. @see forEachXmlChildElementWithTagName
  6171. */
  6172. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6173. \
  6174. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6175. childElementVariableName != 0; \
  6176. childElementVariableName = childElementVariableName->getNextElement())
  6177. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6178. which have a specified tag.
  6179. This does the same job as the forEachXmlChildElement macro, but only for those
  6180. elements that have a particular tag name.
  6181. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6182. will be the name of a pointer to each child element. The requiredTagName is the
  6183. tag name to match.
  6184. E.g. @code
  6185. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6186. forEachXmlChildElementWithTagName (*myParentXml, child, T("MYTAG"))
  6187. {
  6188. // the child object is now guaranteed to be a <MYTAG> element..
  6189. doSomethingWithMYTAGElement (child);
  6190. }
  6191. @endcode
  6192. @see forEachXmlChildElement
  6193. */
  6194. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6195. \
  6196. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6197. childElementVariableName != 0; \
  6198. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6199. /** Used to build a tree of elements representing an XML document.
  6200. An XML document can be parsed into a tree of XmlElements, each of which
  6201. represents an XML tag structure, and which may itself contain other
  6202. nested elements.
  6203. An XmlElement can also be converted back into a text document, and has
  6204. lots of useful methods for manipulating its attributes and sub-elements,
  6205. so XmlElements can actually be used as a handy general-purpose data
  6206. structure.
  6207. Here's an example of parsing some elements: @code
  6208. // check we're looking at the right kind of document..
  6209. if (myElement->hasTagName ("ANIMALS"))
  6210. {
  6211. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6212. forEachXmlChildElement (*myElement, e)
  6213. {
  6214. if (e->hasTagName ("GIRAFFE"))
  6215. {
  6216. // found a giraffe, so use some of its attributes..
  6217. String giraffeName = e->getStringAttribute ("name");
  6218. int giraffeAge = e->getIntAttribute ("age");
  6219. bool isFriendly = e->getBoolAttribute ("friendly");
  6220. }
  6221. }
  6222. }
  6223. @endcode
  6224. And here's an example of how to create an XML document from scratch: @code
  6225. // create an outer node called "ANIMALS"
  6226. XmlElement animalsList ("ANIMALS");
  6227. for (int i = 0; i < numAnimals; ++i)
  6228. {
  6229. // create an inner element..
  6230. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6231. giraffe->setAttribute ("name", "nigel");
  6232. giraffe->setAttribute ("age", 10);
  6233. giraffe->setAttribute ("friendly", true);
  6234. // ..and add our new element to the parent node
  6235. animalsList.addChildElement (giraffe);
  6236. }
  6237. // now we can turn the whole thing into a text document..
  6238. String myXmlDoc = animalsList.createDocument (String::empty);
  6239. @endcode
  6240. @see XmlDocument
  6241. */
  6242. class JUCE_API XmlElement
  6243. {
  6244. public:
  6245. /** Creates an XmlElement with this tag name. */
  6246. XmlElement (const String& tagName) throw();
  6247. /** Creates a (deep) copy of another element. */
  6248. XmlElement (const XmlElement& other) throw();
  6249. /** Creates a (deep) copy of another element. */
  6250. const XmlElement& operator= (const XmlElement& other) throw();
  6251. /** Deleting an XmlElement will also delete all its child elements. */
  6252. ~XmlElement() throw();
  6253. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6254. The elements are only considered equivalent if they contain the same attiributes
  6255. with the same values, and have the same sub-nodes.
  6256. @param other the other element to compare to
  6257. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6258. same attributes in a different order will be
  6259. considered the same; if false, the attributes must
  6260. be in the same order as well
  6261. */
  6262. bool isEquivalentTo (const XmlElement* const other,
  6263. const bool ignoreOrderOfAttributes) const throw();
  6264. /** Returns an XML text document that represents this element.
  6265. The string returned can be parsed to recreate the same XmlElement that
  6266. was used to create it.
  6267. @param dtdToUse the DTD to add to the document
  6268. @param allOnOneLine if true, this means that the document will not contain any
  6269. linefeeds, so it'll be smaller but not very easy to read.
  6270. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6271. document
  6272. @param encodingType the character encoding format string to put into the xml
  6273. header
  6274. @param lineWrapLength the line length that will be used before items get placed on
  6275. a new line. This isn't an absolute maximum length, it just
  6276. determines how lists of attributes get broken up
  6277. @see writeToStream, writeToFile
  6278. */
  6279. const String createDocument (const String& dtdToUse,
  6280. const bool allOnOneLine = false,
  6281. const bool includeXmlHeader = true,
  6282. const tchar* const encodingType = JUCE_T("UTF-8"),
  6283. const int lineWrapLength = 60) const throw();
  6284. /** Writes the document to a stream as UTF-8.
  6285. @param output the stream to write to
  6286. @param dtdToUse the DTD to add to the document
  6287. @param allOnOneLine if true, this means that the document will not contain any
  6288. linefeeds, so it'll be smaller but not very easy to read.
  6289. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6290. document
  6291. @param encodingType the character encoding format string to put into the xml
  6292. header
  6293. @param lineWrapLength the line length that will be used before items get placed on
  6294. a new line. This isn't an absolute maximum length, it just
  6295. determines how lists of attributes get broken up
  6296. @see writeToFile, createDocument
  6297. */
  6298. void writeToStream (OutputStream& output,
  6299. const String& dtdToUse,
  6300. const bool allOnOneLine = false,
  6301. const bool includeXmlHeader = true,
  6302. const tchar* const encodingType = JUCE_T("UTF-8"),
  6303. const int lineWrapLength = 60) const throw();
  6304. /** Writes the element to a file as an XML document.
  6305. To improve safety in case something goes wrong while writing the file, this
  6306. will actually write the document to a new temporary file in the same
  6307. directory as the destination file, and if this succeeds, it will rename this
  6308. new file as the destination file (overwriting any existing file that was there).
  6309. @param destinationFile the file to write to. If this already exists, it will be
  6310. overwritten.
  6311. @param dtdToUse the DTD to add to the document
  6312. @param encodingType the character encoding format string to put into the xml
  6313. header
  6314. @param lineWrapLength the line length that will be used before items get placed on
  6315. a new line. This isn't an absolute maximum length, it just
  6316. determines how lists of attributes get broken up
  6317. @returns true if the file is written successfully; false if something goes wrong
  6318. in the process
  6319. @see createDocument
  6320. */
  6321. bool writeToFile (const File& destinationFile,
  6322. const String& dtdToUse,
  6323. const tchar* const encodingType = JUCE_T("UTF-8"),
  6324. const int lineWrapLength = 60) const throw();
  6325. /** Returns this element's tag type name.
  6326. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  6327. "MOOSE".
  6328. @see hasTagName
  6329. */
  6330. inline const String& getTagName() const throw() { return tagName; }
  6331. /** Tests whether this element has a particular tag name.
  6332. @param possibleTagName the tag name you're comparing it with
  6333. @see getTagName
  6334. */
  6335. bool hasTagName (const tchar* const possibleTagName) const throw();
  6336. /** Returns the number of XML attributes this element contains.
  6337. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  6338. return 2.
  6339. */
  6340. int getNumAttributes() const throw();
  6341. /** Returns the name of one of the elements attributes.
  6342. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6343. getAttributeName(1) would return "antlers".
  6344. @see getAttributeValue, getStringAttribute
  6345. */
  6346. const String& getAttributeName (const int attributeIndex) const throw();
  6347. /** Returns the value of one of the elements attributes.
  6348. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  6349. getAttributeName(1) would return "2".
  6350. @see getAttributeName, getStringAttribute
  6351. */
  6352. const String& getAttributeValue (const int attributeIndex) const throw();
  6353. // Attribute-handling methods..
  6354. /** Checks whether the element contains an attribute with a certain name. */
  6355. bool hasAttribute (const tchar* const attributeName) const throw();
  6356. /** Returns the value of a named attribute.
  6357. @param attributeName the name of the attribute to look up
  6358. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6359. with this name
  6360. */
  6361. const String getStringAttribute (const tchar* const attributeName,
  6362. const tchar* const defaultReturnValue = 0) const throw();
  6363. /** Compares the value of a named attribute with a value passed-in.
  6364. @param attributeName the name of the attribute to look up
  6365. @param stringToCompareAgainst the value to compare it with
  6366. @param ignoreCase whether the comparison should be case-insensitive
  6367. @returns true if the value of the attribute is the same as the string passed-in;
  6368. false if it's different (or if no such attribute exists)
  6369. */
  6370. bool compareAttribute (const tchar* const attributeName,
  6371. const tchar* const stringToCompareAgainst,
  6372. const bool ignoreCase = false) const throw();
  6373. /** Returns the value of a named attribute as an integer.
  6374. This will try to find the attribute and convert it to an integer (using
  6375. the String::getIntValue() method).
  6376. @param attributeName the name of the attribute to look up
  6377. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6378. with this name
  6379. @see setAttribute (const tchar* const, int)
  6380. */
  6381. int getIntAttribute (const tchar* const attributeName,
  6382. const int defaultReturnValue = 0) const throw();
  6383. /** Returns the value of a named attribute as floating-point.
  6384. This will try to find the attribute and convert it to an integer (using
  6385. the String::getDoubleValue() method).
  6386. @param attributeName the name of the attribute to look up
  6387. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6388. with this name
  6389. @see setAttribute (const tchar* const, double)
  6390. */
  6391. double getDoubleAttribute (const tchar* const attributeName,
  6392. const double defaultReturnValue = 0.0) const throw();
  6393. /** Returns the value of a named attribute as a boolean.
  6394. This will try to find the attribute and interpret it as a boolean. To do this,
  6395. it'll return true if the value is "1", "true", "y", etc, or false for other
  6396. values.
  6397. @param attributeName the name of the attribute to look up
  6398. @param defaultReturnValue a value to return if the element doesn't have an attribute
  6399. with this name
  6400. */
  6401. bool getBoolAttribute (const tchar* const attributeName,
  6402. const bool defaultReturnValue = false) const throw();
  6403. /** Adds a named attribute to the element.
  6404. If the element already contains an attribute with this name, it's value will
  6405. be updated to the new value. If there's no such attribute yet, a new one will
  6406. be added.
  6407. Note that there are other setAttribute() methods that take integers,
  6408. doubles, etc. to make it easy to store numbers.
  6409. @param attributeName the name of the attribute to set
  6410. @param newValue the value to set it to
  6411. @see removeAttribute
  6412. */
  6413. void setAttribute (const tchar* const attributeName,
  6414. const String& newValue) throw();
  6415. /** Adds a named attribute to the element.
  6416. If the element already contains an attribute with this name, it's value will
  6417. be updated to the new value. If there's no such attribute yet, a new one will
  6418. be added.
  6419. Note that there are other setAttribute() methods that take integers,
  6420. doubles, etc. to make it easy to store numbers.
  6421. @param attributeName the name of the attribute to set
  6422. @param newValue the value to set it to
  6423. */
  6424. void setAttribute (const tchar* const attributeName,
  6425. const tchar* const newValue) throw();
  6426. /** Adds a named attribute to the element, setting it to an integer value.
  6427. If the element already contains an attribute with this name, it's value will
  6428. be updated to the new value. If there's no such attribute yet, a new one will
  6429. be added.
  6430. Note that there are other setAttribute() methods that take integers,
  6431. doubles, etc. to make it easy to store numbers.
  6432. @param attributeName the name of the attribute to set
  6433. @param newValue the value to set it to
  6434. */
  6435. void setAttribute (const tchar* const attributeName,
  6436. const int newValue) throw();
  6437. /** Adds a named attribute to the element, setting it to a floating-point value.
  6438. If the element already contains an attribute with this name, it's value will
  6439. be updated to the new value. If there's no such attribute yet, a new one will
  6440. be added.
  6441. Note that there are other setAttribute() methods that take integers,
  6442. doubles, etc. to make it easy to store numbers.
  6443. @param attributeName the name of the attribute to set
  6444. @param newValue the value to set it to
  6445. */
  6446. void setAttribute (const tchar* const attributeName,
  6447. const double newValue) throw();
  6448. /** Removes a named attribute from the element.
  6449. @param attributeName the name of the attribute to remove
  6450. @see removeAllAttributes
  6451. */
  6452. void removeAttribute (const tchar* const attributeName) throw();
  6453. /** Removes all attributes from this element.
  6454. */
  6455. void removeAllAttributes() throw();
  6456. // Child element methods..
  6457. /** Returns the first of this element's sub-elements.
  6458. see getNextElement() for an example of how to iterate the sub-elements.
  6459. @see forEachXmlChildElement
  6460. */
  6461. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  6462. /** Returns the next of this element's siblings.
  6463. This can be used for iterating an element's sub-elements, e.g.
  6464. @code
  6465. XmlElement* child = myXmlDocument->getFirstChildElement();
  6466. while (child != 0)
  6467. {
  6468. ...do stuff with this child..
  6469. child = child->getNextElement();
  6470. }
  6471. @endcode
  6472. Note that when iterating the child elements, some of them might be
  6473. text elements as well as XML tags - use isTextElement() to work this
  6474. out.
  6475. Also, it's much easier and neater to use this method indirectly via the
  6476. forEachXmlChildElement macro.
  6477. @returns the sibling element that follows this one, or zero if this is the last
  6478. element in its parent
  6479. @see getNextElement, isTextElement, forEachXmlChildElement
  6480. */
  6481. inline XmlElement* getNextElement() const throw() { return nextElement; }
  6482. /** Returns the next of this element's siblings which has the specified tag
  6483. name.
  6484. This is like getNextElement(), but will scan through the list until it
  6485. finds an element with the given tag name.
  6486. @see getNextElement, forEachXmlChildElementWithTagName
  6487. */
  6488. XmlElement* getNextElementWithTagName (const tchar* const requiredTagName) const;
  6489. /** Returns the number of sub-elements in this element.
  6490. @see getChildElement
  6491. */
  6492. int getNumChildElements() const throw();
  6493. /** Returns the sub-element at a certain index.
  6494. It's not very efficient to iterate the sub-elements by index - see
  6495. getNextElement() for an example of how best to iterate.
  6496. @returns the n'th child of this element, or 0 if the index is out-of-range
  6497. @see getNextElement, isTextElement, getChildByName
  6498. */
  6499. XmlElement* getChildElement (const int index) const throw();
  6500. /** Returns the first sub-element with a given tag-name.
  6501. @param tagNameToLookFor the tag name of the element you want to find
  6502. @returns the first element with this tag name, or 0 if none is found
  6503. @see getNextElement, isTextElement, getChildElement
  6504. */
  6505. XmlElement* getChildByName (const tchar* const tagNameToLookFor) const throw();
  6506. /** Appends an element to this element's list of children.
  6507. Child elements are deleted automatically when their parent is deleted, so
  6508. make sure the object that you pass in will not be deleted by anything else,
  6509. and make sure it's not already the child of another element.
  6510. @see getFirstChildElement, getNextElement, getNumChildElements,
  6511. getChildElement, removeChildElement
  6512. */
  6513. void addChildElement (XmlElement* const newChildElement) throw();
  6514. /** Inserts an element into this element's list of children.
  6515. Child elements are deleted automatically when their parent is deleted, so
  6516. make sure the object that you pass in will not be deleted by anything else,
  6517. and make sure it's not already the child of another element.
  6518. @param newChildNode the element to add
  6519. @param indexToInsertAt the index at which to insert the new element - if this is
  6520. below zero, it will be added to the end of the list
  6521. @see addChildElement, insertChildElement
  6522. */
  6523. void insertChildElement (XmlElement* const newChildNode,
  6524. int indexToInsertAt) throw();
  6525. /** Replaces one of this element's children with another node.
  6526. If the current element passed-in isn't actually a child of this element,
  6527. this will return false and the new one won't be added. Otherwise, the
  6528. existing element will be deleted, replaced with the new one, and it
  6529. will return true.
  6530. */
  6531. bool replaceChildElement (XmlElement* const currentChildElement,
  6532. XmlElement* const newChildNode) throw();
  6533. /** Removes a child element.
  6534. @param childToRemove the child to look for and remove
  6535. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  6536. just remove it
  6537. */
  6538. void removeChildElement (XmlElement* const childToRemove,
  6539. const bool shouldDeleteTheChild) throw();
  6540. /** Deletes all the child elements in the element.
  6541. @see removeChildElement, deleteAllChildElementsWithTagName
  6542. */
  6543. void deleteAllChildElements() throw();
  6544. /** Deletes all the child elements with a given tag name.
  6545. @see removeChildElement
  6546. */
  6547. void deleteAllChildElementsWithTagName (const tchar* const tagName) throw();
  6548. /** Returns true if the given element is a child of this one. */
  6549. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  6550. /** Recursively searches all sub-elements to find one that contains the specified
  6551. child element.
  6552. */
  6553. XmlElement* findParentElementOf (const XmlElement* const elementToLookFor) throw();
  6554. /** Sorts the child elements using a comparator.
  6555. This will use a comparator object to sort the elements into order. The object
  6556. passed must have a method of the form:
  6557. @code
  6558. int compareElements (const XmlElement* first, const XmlElement* second);
  6559. @endcode
  6560. ..and this method must return:
  6561. - a value of < 0 if the first comes before the second
  6562. - a value of 0 if the two objects are equivalent
  6563. - a value of > 0 if the second comes before the first
  6564. To improve performance, the compareElements() method can be declared as static or const.
  6565. @param comparator the comparator to use for comparing elements.
  6566. @param retainOrderOfEquivalentItems if this is true, then items
  6567. which the comparator says are equivalent will be
  6568. kept in the order in which they currently appear
  6569. in the array. This is slower to perform, but may
  6570. be important in some cases. If it's false, a faster
  6571. algorithm is used, but equivalent elements may be
  6572. rearranged.
  6573. */
  6574. template <class ElementComparator>
  6575. void sortChildElements (ElementComparator& comparator,
  6576. const bool retainOrderOfEquivalentItems = false) throw()
  6577. {
  6578. const int num = getNumChildElements();
  6579. if (num > 1)
  6580. {
  6581. HeapBlock <XmlElement*> elems (num);
  6582. getChildElementsAsArray (elems);
  6583. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  6584. reorderChildElements (elems, num);
  6585. }
  6586. }
  6587. /** Returns true if this element is a section of text.
  6588. Elements can either be an XML tag element or a secton of text, so this
  6589. is used to find out what kind of element this one is.
  6590. @see getAllText, addTextElement, deleteAllTextElements
  6591. */
  6592. bool isTextElement() const throw();
  6593. /** Returns the text for a text element.
  6594. Note that if you have an element like this:
  6595. @code<xyz>hello</xyz>@endcode
  6596. then calling getText on the "xyz" element won't return "hello", because that is
  6597. actually stored in a special text sub-element inside the xyz element. To get the
  6598. "hello" string, you could either call getText on the (unnamed) sub-element, or
  6599. use getAllSubText() to do this automatically.
  6600. @see isTextElement, getAllSubText, getChildElementAllSubText
  6601. */
  6602. const String getText() const throw();
  6603. /** Sets the text in a text element.
  6604. Note that this is only a valid call if this element is a text element. If it's
  6605. not, then no action will be performed.
  6606. */
  6607. void setText (const String& newText) throw();
  6608. /** Returns all the text from this element's child nodes.
  6609. This iterates all the child elements and when it finds text elements,
  6610. it concatenates their text into a big string which it returns.
  6611. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  6612. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  6613. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  6614. */
  6615. const String getAllSubText() const throw();
  6616. /** Returns all the sub-text of a named child element.
  6617. If there is a child element with the given tag name, this will return
  6618. all of its sub-text (by calling getAllSubText() on it). If there is
  6619. no such child element, this will return the default string passed-in.
  6620. @see getAllSubText
  6621. */
  6622. const String getChildElementAllSubText (const tchar* const childTagName,
  6623. const String& defaultReturnValue) const throw();
  6624. /** Appends a section of text to this element.
  6625. @see isTextElement, getText, getAllSubText
  6626. */
  6627. void addTextElement (const String& text) throw();
  6628. /** Removes all the text elements from this element.
  6629. @see isTextElement, getText, getAllSubText, addTextElement
  6630. */
  6631. void deleteAllTextElements() throw();
  6632. /** Creates a text element that can be added to a parent element.
  6633. */
  6634. static XmlElement* createTextElement (const String& text) throw();
  6635. juce_UseDebuggingNewOperator
  6636. private:
  6637. friend class XmlDocument;
  6638. String tagName;
  6639. XmlElement* firstChildElement;
  6640. XmlElement* nextElement;
  6641. struct XmlAttributeNode
  6642. {
  6643. XmlAttributeNode (const XmlAttributeNode& other) throw();
  6644. XmlAttributeNode (const String& name, const String& value) throw();
  6645. String name, value;
  6646. XmlAttributeNode* next;
  6647. private:
  6648. const XmlAttributeNode& operator= (const XmlAttributeNode&);
  6649. };
  6650. XmlAttributeNode* attributes;
  6651. XmlElement (int) throw(); // for internal use
  6652. XmlElement (const tchar* const tagNameText, const int nameLen) throw();
  6653. void copyChildrenAndAttributesFrom (const XmlElement& other) throw();
  6654. void writeElementAsText (OutputStream& out,
  6655. const int indentationLevel,
  6656. const int lineWrapLength) const throw();
  6657. void getChildElementsAsArray (XmlElement**) const throw();
  6658. void reorderChildElements (XmlElement** const, const int) throw();
  6659. };
  6660. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  6661. /********* End of inlined file: juce_XmlElement.h *********/
  6662. /**
  6663. A set of named property values, which can be strings, integers, floating point, etc.
  6664. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  6665. to load and save types other than strings.
  6666. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  6667. messages and saves/loads the list from a file.
  6668. */
  6669. class JUCE_API PropertySet
  6670. {
  6671. public:
  6672. /** Creates an empty PropertySet.
  6673. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  6674. case-insensitive way
  6675. */
  6676. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  6677. /** Creates a copy of another PropertySet.
  6678. */
  6679. PropertySet (const PropertySet& other) throw();
  6680. /** Copies another PropertySet over this one.
  6681. */
  6682. const PropertySet& operator= (const PropertySet& other) throw();
  6683. /** Destructor. */
  6684. virtual ~PropertySet();
  6685. /** Returns one of the properties as a string.
  6686. If the value isn't found in this set, then this will look for it in a fallback
  6687. property set (if you've specified one with the setFallbackPropertySet() method),
  6688. and if it can't find one there, it'll return the default value passed-in.
  6689. @param keyName the name of the property to retrieve
  6690. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6691. */
  6692. const String getValue (const String& keyName,
  6693. const String& defaultReturnValue = String::empty) const throw();
  6694. /** Returns one of the properties as an integer.
  6695. If the value isn't found in this set, then this will look for it in a fallback
  6696. property set (if you've specified one with the setFallbackPropertySet() method),
  6697. and if it can't find one there, it'll return the default value passed-in.
  6698. @param keyName the name of the property to retrieve
  6699. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6700. */
  6701. int getIntValue (const String& keyName,
  6702. const int defaultReturnValue = 0) const throw();
  6703. /** Returns one of the properties as an double.
  6704. If the value isn't found in this set, then this will look for it in a fallback
  6705. property set (if you've specified one with the setFallbackPropertySet() method),
  6706. and if it can't find one there, it'll return the default value passed-in.
  6707. @param keyName the name of the property to retrieve
  6708. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6709. */
  6710. double getDoubleValue (const String& keyName,
  6711. const double defaultReturnValue = 0.0) const throw();
  6712. /** Returns one of the properties as an boolean.
  6713. The result will be true if the string found for this key name can be parsed as a non-zero
  6714. integer.
  6715. If the value isn't found in this set, then this will look for it in a fallback
  6716. property set (if you've specified one with the setFallbackPropertySet() method),
  6717. and if it can't find one there, it'll return the default value passed-in.
  6718. @param keyName the name of the property to retrieve
  6719. @param defaultReturnValue a value to return if the named property doesn't actually exist
  6720. */
  6721. bool getBoolValue (const String& keyName,
  6722. const bool defaultReturnValue = false) const throw();
  6723. /** Returns one of the properties as an XML element.
  6724. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  6725. key isn't found, or if the entry contains an string that isn't valid XML.
  6726. If the value isn't found in this set, then this will look for it in a fallback
  6727. property set (if you've specified one with the setFallbackPropertySet() method),
  6728. and if it can't find one there, it'll return the default value passed-in.
  6729. @param keyName the name of the property to retrieve
  6730. */
  6731. XmlElement* getXmlValue (const String& keyName) const;
  6732. /** Sets a named property as a string.
  6733. @param keyName the name of the property to set. (This mustn't be an empty string)
  6734. @param value the new value to set it to
  6735. */
  6736. void setValue (const String& keyName, const String& value) throw();
  6737. /** Sets a named property as a string.
  6738. @param keyName the name of the property to set. (This mustn't be an empty string)
  6739. @param value the new value to set it to
  6740. */
  6741. void setValue (const String& keyName, const tchar* const value) throw();
  6742. /** Sets a named property to an integer.
  6743. @param keyName the name of the property to set. (This mustn't be an empty string)
  6744. @param value the new value to set it to
  6745. */
  6746. void setValue (const String& keyName, const int value) throw();
  6747. /** Sets a named property to a double.
  6748. @param keyName the name of the property to set. (This mustn't be an empty string)
  6749. @param value the new value to set it to
  6750. */
  6751. void setValue (const String& keyName, const double value) throw();
  6752. /** Sets a named property to a boolean.
  6753. @param keyName the name of the property to set. (This mustn't be an empty string)
  6754. @param value the new value to set it to
  6755. */
  6756. void setValue (const String& keyName, const bool value) throw();
  6757. /** Sets a named property to an XML element.
  6758. @param keyName the name of the property to set. (This mustn't be an empty string)
  6759. @param xml the new element to set it to. If this is zero, the value will be set to
  6760. an empty string
  6761. @see getXmlValue
  6762. */
  6763. void setValue (const String& keyName, const XmlElement* const xml);
  6764. /** Deletes a property.
  6765. @param keyName the name of the property to delete. (This mustn't be an empty string)
  6766. */
  6767. void removeValue (const String& keyName) throw();
  6768. /** Returns true if the properies include the given key. */
  6769. bool containsKey (const String& keyName) const throw();
  6770. /** Removes all values. */
  6771. void clear();
  6772. /** Returns the keys/value pair array containing all the properties. */
  6773. StringPairArray& getAllProperties() throw() { return properties; }
  6774. /** Returns the lock used when reading or writing to this set */
  6775. const CriticalSection& getLock() const throw() { return lock; }
  6776. /** Returns an XML element which encapsulates all the items in this property set.
  6777. The string parameter is the tag name that should be used for the node.
  6778. @see restoreFromXml
  6779. */
  6780. XmlElement* createXml (const String& nodeName) const throw();
  6781. /** Reloads a set of properties that were previously stored as XML.
  6782. The node passed in must have been created by the createXml() method.
  6783. @see createXml
  6784. */
  6785. void restoreFromXml (const XmlElement& xml) throw();
  6786. /** Sets up a second PopertySet that will be used to look up any values that aren't
  6787. set in this one.
  6788. If you set this up to be a pointer to a second property set, then whenever one
  6789. of the getValue() methods fails to find an entry in this set, it will look up that
  6790. value in the fallback set, and if it finds it, it will return that.
  6791. Make sure that you don't delete the fallback set while it's still being used by
  6792. another set! To remove the fallback set, just call this method with a null pointer.
  6793. @see getFallbackPropertySet
  6794. */
  6795. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  6796. /** Returns the fallback property set.
  6797. @see setFallbackPropertySet
  6798. */
  6799. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  6800. juce_UseDebuggingNewOperator
  6801. protected:
  6802. /** Subclasses can override this to be told when one of the properies has been changed.
  6803. */
  6804. virtual void propertyChanged();
  6805. private:
  6806. StringPairArray properties;
  6807. PropertySet* fallbackProperties;
  6808. CriticalSection lock;
  6809. bool ignoreCaseOfKeys;
  6810. };
  6811. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  6812. /********* End of inlined file: juce_PropertySet.h *********/
  6813. #endif
  6814. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6815. /********* Start of inlined file: juce_ReferenceCountedArray.h *********/
  6816. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6817. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  6818. /********* Start of inlined file: juce_ReferenceCountedObject.h *********/
  6819. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6820. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  6821. /********* Start of inlined file: juce_Atomic.h *********/
  6822. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  6823. #define __JUCE_ATOMIC_JUCEHEADER__
  6824. // Atomic increment/decrement operations..
  6825. #if (JUCE_MAC || JUCE_IPHONE) && ! DOXYGEN
  6826. #include <libkern/OSAtomic.h>
  6827. static forcedinline void atomicIncrement (int& variable) throw() { OSAtomicIncrement32 ((int32_t*) &variable); }
  6828. static forcedinline int atomicIncrementAndReturn (int& variable) throw() { return OSAtomicIncrement32 ((int32_t*) &variable); }
  6829. static forcedinline void atomicDecrement (int& variable) throw() { OSAtomicDecrement32 ((int32_t*) &variable); }
  6830. static forcedinline int atomicDecrementAndReturn (int& variable) throw() { return OSAtomicDecrement32 ((int32_t*) &variable); }
  6831. #elif JUCE_GCC
  6832. #if JUCE_USE_GCC_ATOMIC_INTRINSICS
  6833. forcedinline void atomicIncrement (int& variable) throw() { __sync_add_and_fetch (&variable, 1); }
  6834. forcedinline int atomicIncrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, 1); }
  6835. forcedinline void atomicDecrement (int& variable) throw() { __sync_add_and_fetch (&variable, -1); }
  6836. forcedinline int atomicDecrementAndReturn (int& variable) throw() { return __sync_add_and_fetch (&variable, -1); }
  6837. #else
  6838. /** Increments an integer in a thread-safe way. */
  6839. forcedinline void atomicIncrement (int& variable) throw()
  6840. {
  6841. __asm__ __volatile__ (
  6842. #if JUCE_64BIT
  6843. "lock incl (%%rax)"
  6844. :
  6845. : "a" (&variable)
  6846. : "cc", "memory");
  6847. #else
  6848. "lock incl %0"
  6849. : "=m" (variable)
  6850. : "m" (variable));
  6851. #endif
  6852. }
  6853. /** Increments an integer in a thread-safe way and returns the incremented value. */
  6854. forcedinline int atomicIncrementAndReturn (int& variable) throw()
  6855. {
  6856. int result;
  6857. __asm__ __volatile__ (
  6858. #if JUCE_64BIT
  6859. "lock xaddl %%ebx, (%%rax) \n\
  6860. incl %%ebx"
  6861. : "=b" (result)
  6862. : "a" (&variable), "b" (1)
  6863. : "cc", "memory");
  6864. #else
  6865. "lock xaddl %%eax, (%%ecx) \n\
  6866. incl %%eax"
  6867. : "=a" (result)
  6868. : "c" (&variable), "a" (1)
  6869. : "memory");
  6870. #endif
  6871. return result;
  6872. }
  6873. /** Decrememts an integer in a thread-safe way. */
  6874. forcedinline void atomicDecrement (int& variable) throw()
  6875. {
  6876. __asm__ __volatile__ (
  6877. #if JUCE_64BIT
  6878. "lock decl (%%rax)"
  6879. :
  6880. : "a" (&variable)
  6881. : "cc", "memory");
  6882. #else
  6883. "lock decl %0"
  6884. : "=m" (variable)
  6885. : "m" (variable));
  6886. #endif
  6887. }
  6888. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  6889. forcedinline int atomicDecrementAndReturn (int& variable) throw()
  6890. {
  6891. int result;
  6892. __asm__ __volatile__ (
  6893. #if JUCE_64BIT
  6894. "lock xaddl %%ebx, (%%rax) \n\
  6895. decl %%ebx"
  6896. : "=b" (result)
  6897. : "a" (&variable), "b" (-1)
  6898. : "cc", "memory");
  6899. #else
  6900. "lock xaddl %%eax, (%%ecx) \n\
  6901. decl %%eax"
  6902. : "=a" (result)
  6903. : "c" (&variable), "a" (-1)
  6904. : "memory");
  6905. #endif
  6906. return result;
  6907. }
  6908. #endif
  6909. #elif JUCE_USE_INTRINSICS
  6910. #pragma intrinsic (_InterlockedIncrement)
  6911. #pragma intrinsic (_InterlockedDecrement)
  6912. /** Increments an integer in a thread-safe way. */
  6913. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  6914. {
  6915. _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  6916. }
  6917. /** Increments an integer in a thread-safe way and returns the incremented value. */
  6918. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  6919. {
  6920. return _InterlockedIncrement (reinterpret_cast <volatile long*> (&variable));
  6921. }
  6922. /** Decrememts an integer in a thread-safe way. */
  6923. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  6924. {
  6925. _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  6926. }
  6927. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  6928. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  6929. {
  6930. return _InterlockedDecrement (reinterpret_cast <volatile long*> (&variable));
  6931. }
  6932. #else
  6933. /** Increments an integer in a thread-safe way. */
  6934. forcedinline void __fastcall atomicIncrement (int& variable) throw()
  6935. {
  6936. __asm {
  6937. mov ecx, dword ptr [variable]
  6938. lock inc dword ptr [ecx]
  6939. }
  6940. }
  6941. /** Increments an integer in a thread-safe way and returns the incremented value. */
  6942. forcedinline int __fastcall atomicIncrementAndReturn (int& variable) throw()
  6943. {
  6944. int result;
  6945. __asm {
  6946. mov ecx, dword ptr [variable]
  6947. mov eax, 1
  6948. lock xadd dword ptr [ecx], eax
  6949. inc eax
  6950. mov result, eax
  6951. }
  6952. return result;
  6953. }
  6954. /** Decrememts an integer in a thread-safe way. */
  6955. forcedinline void __fastcall atomicDecrement (int& variable) throw()
  6956. {
  6957. __asm {
  6958. mov ecx, dword ptr [variable]
  6959. lock dec dword ptr [ecx]
  6960. }
  6961. }
  6962. /** Decrememts an integer in a thread-safe way and returns the incremented value. */
  6963. forcedinline int __fastcall atomicDecrementAndReturn (int& variable) throw()
  6964. {
  6965. int result;
  6966. __asm {
  6967. mov ecx, dword ptr [variable]
  6968. mov eax, -1
  6969. lock xadd dword ptr [ecx], eax
  6970. dec eax
  6971. mov result, eax
  6972. }
  6973. return result;
  6974. }
  6975. #endif
  6976. #endif // __JUCE_ATOMIC_JUCEHEADER__
  6977. /********* End of inlined file: juce_Atomic.h *********/
  6978. /**
  6979. Adds reference-counting to an object.
  6980. To add reference-counting to a class, derive it from this class, and
  6981. use the ReferenceCountedObjectPtr class to point to it.
  6982. e.g. @code
  6983. class MyClass : public ReferenceCountedObject
  6984. {
  6985. void foo();
  6986. // This is a neat way of declaring a typedef for a pointer class,
  6987. // rather than typing out the full templated name each time..
  6988. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  6989. };
  6990. MyClass::Ptr p = new MyClass();
  6991. MyClass::Ptr p2 = p;
  6992. p = 0;
  6993. p2->foo();
  6994. @endcode
  6995. Once a new ReferenceCountedObject has been assigned to a pointer, be
  6996. careful not to delete the object manually.
  6997. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  6998. */
  6999. class JUCE_API ReferenceCountedObject
  7000. {
  7001. public:
  7002. /** Increments the object's reference count.
  7003. This is done automatically by the smart pointer, but is public just
  7004. in case it's needed for nefarious purposes.
  7005. */
  7006. inline void incReferenceCount() throw()
  7007. {
  7008. atomicIncrement (refCounts);
  7009. jassert (refCounts > 0);
  7010. }
  7011. /** Decreases the object's reference count.
  7012. If the count gets to zero, the object will be deleted.
  7013. */
  7014. inline void decReferenceCount() throw()
  7015. {
  7016. jassert (refCounts > 0);
  7017. if (atomicDecrementAndReturn (refCounts) == 0)
  7018. delete this;
  7019. }
  7020. /** Returns the object's current reference count. */
  7021. inline int getReferenceCount() const throw()
  7022. {
  7023. return refCounts;
  7024. }
  7025. protected:
  7026. /** Creates the reference-counted object (with an initial ref count of zero). */
  7027. ReferenceCountedObject()
  7028. : refCounts (0)
  7029. {
  7030. }
  7031. /** Destructor. */
  7032. virtual ~ReferenceCountedObject()
  7033. {
  7034. // it's dangerous to delete an object that's still referenced by something else!
  7035. jassert (refCounts == 0);
  7036. }
  7037. private:
  7038. int refCounts;
  7039. };
  7040. /**
  7041. Used to point to an object of type ReferenceCountedObject.
  7042. It's wise to use a typedef instead of typing out the templated name
  7043. each time - e.g.
  7044. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  7045. @see ReferenceCountedObject, ReferenceCountedObjectArray
  7046. */
  7047. template <class ReferenceCountedObjectClass>
  7048. class ReferenceCountedObjectPtr
  7049. {
  7050. public:
  7051. /** Creates a pointer to a null object. */
  7052. inline ReferenceCountedObjectPtr() throw()
  7053. : referencedObject (0)
  7054. {
  7055. }
  7056. /** Creates a pointer to an object.
  7057. This will increment the object's reference-count if it is non-null.
  7058. */
  7059. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  7060. : referencedObject (refCountedObject)
  7061. {
  7062. if (refCountedObject != 0)
  7063. refCountedObject->incReferenceCount();
  7064. }
  7065. /** Copies another pointer.
  7066. This will increment the object's reference-count (if it is non-null).
  7067. */
  7068. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  7069. : referencedObject (other.referencedObject)
  7070. {
  7071. if (referencedObject != 0)
  7072. referencedObject->incReferenceCount();
  7073. }
  7074. /** Changes this pointer to point at a different object.
  7075. The reference count of the old object is decremented, and it might be
  7076. deleted if it hits zero. The new object's count is incremented.
  7077. */
  7078. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  7079. {
  7080. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  7081. if (newObject != referencedObject)
  7082. {
  7083. if (newObject != 0)
  7084. newObject->incReferenceCount();
  7085. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7086. referencedObject = newObject;
  7087. if (oldObject != 0)
  7088. oldObject->decReferenceCount();
  7089. }
  7090. return *this;
  7091. }
  7092. /** Changes this pointer to point at a different object.
  7093. The reference count of the old object is decremented, and it might be
  7094. deleted if it hits zero. The new object's count is incremented.
  7095. */
  7096. const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  7097. {
  7098. if (referencedObject != newObject)
  7099. {
  7100. if (newObject != 0)
  7101. newObject->incReferenceCount();
  7102. ReferenceCountedObjectClass* const oldObject = referencedObject;
  7103. referencedObject = newObject;
  7104. if (oldObject != 0)
  7105. oldObject->decReferenceCount();
  7106. }
  7107. return *this;
  7108. }
  7109. /** Destructor.
  7110. This will decrement the object's reference-count, and may delete it if it
  7111. gets to zero.
  7112. */
  7113. inline ~ReferenceCountedObjectPtr()
  7114. {
  7115. if (referencedObject != 0)
  7116. referencedObject->decReferenceCount();
  7117. }
  7118. /** Returns the object that this pointer references.
  7119. The pointer returned may be zero, of course.
  7120. */
  7121. inline operator ReferenceCountedObjectClass*() const throw()
  7122. {
  7123. return referencedObject;
  7124. }
  7125. /** Returns true if this pointer refers to the given object. */
  7126. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  7127. {
  7128. return referencedObject == object;
  7129. }
  7130. /** Returns true if this pointer doesn't refer to the given object. */
  7131. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  7132. {
  7133. return referencedObject != object;
  7134. }
  7135. // the -> operator is called on the referenced object
  7136. inline ReferenceCountedObjectClass* operator->() const throw()
  7137. {
  7138. return referencedObject;
  7139. }
  7140. private:
  7141. ReferenceCountedObjectClass* referencedObject;
  7142. };
  7143. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7144. /********* End of inlined file: juce_ReferenceCountedObject.h *********/
  7145. /**
  7146. Holds a list of objects derived from ReferenceCountedObject.
  7147. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7148. and takes care of incrementing and decrementing their ref counts when they
  7149. are added and removed from the array.
  7150. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7151. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7152. @see Array, OwnedArray, StringArray
  7153. */
  7154. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7155. class ReferenceCountedArray
  7156. {
  7157. public:
  7158. /** Creates an empty array.
  7159. @param granularity this is the size of increment by which the internal storage
  7160. used by the array will grow. Only change it from the default if you know the
  7161. array is going to be very big and needs to be able to grow efficiently.
  7162. @see ReferenceCountedObject, Array, OwnedArray
  7163. */
  7164. ReferenceCountedArray (const int granularity = juceDefaultArrayGranularity) throw()
  7165. : data (granularity),
  7166. numUsed (0)
  7167. {
  7168. }
  7169. /** Creates a copy of another array */
  7170. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7171. : data (other.data.granularity)
  7172. {
  7173. other.lockArray();
  7174. numUsed = other.numUsed;
  7175. data.setAllocatedSize (numUsed);
  7176. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7177. for (int i = numUsed; --i >= 0;)
  7178. if (data.elements[i] != 0)
  7179. data.elements[i]->incReferenceCount();
  7180. other.unlockArray();
  7181. }
  7182. /** Copies another array into this one.
  7183. Any existing objects in this array will first be released.
  7184. */
  7185. const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7186. {
  7187. if (this != &other)
  7188. {
  7189. other.lockArray();
  7190. lock.enter();
  7191. clear();
  7192. data.granularity = other.granularity;
  7193. data.ensureAllocatedSize (other.numUsed);
  7194. numUsed = other.numUsed;
  7195. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7196. minimiseStorageOverheads();
  7197. for (int i = numUsed; --i >= 0;)
  7198. if (data.elements[i] != 0)
  7199. data.elements[i]->incReferenceCount();
  7200. lock.exit();
  7201. other.unlockArray();
  7202. }
  7203. return *this;
  7204. }
  7205. /** Destructor.
  7206. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7207. */
  7208. ~ReferenceCountedArray()
  7209. {
  7210. clear();
  7211. }
  7212. /** Removes all objects from the array.
  7213. Any objects in the array that are not referenced from elsewhere will be deleted.
  7214. */
  7215. void clear()
  7216. {
  7217. lock.enter();
  7218. while (numUsed > 0)
  7219. if (data.elements [--numUsed] != 0)
  7220. data.elements [numUsed]->decReferenceCount();
  7221. jassert (numUsed == 0);
  7222. data.setAllocatedSize (0);
  7223. lock.exit();
  7224. }
  7225. /** Returns the current number of objects in the array. */
  7226. inline int size() const throw()
  7227. {
  7228. return numUsed;
  7229. }
  7230. /** Returns a pointer to the object at this index in the array.
  7231. If the index is out-of-range, this will return a null pointer, (and
  7232. it could be null anyway, because it's ok for the array to hold null
  7233. pointers as well as objects).
  7234. @see getUnchecked
  7235. */
  7236. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7237. {
  7238. lock.enter();
  7239. const ReferenceCountedObjectPtr<ObjectClass> result ((((unsigned int) index) < (unsigned int) numUsed)
  7240. ? data.elements [index]
  7241. : (ObjectClass*) 0);
  7242. lock.exit();
  7243. return result;
  7244. }
  7245. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7246. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7247. it can be used when you're sure the index if always going to be legal.
  7248. */
  7249. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7250. {
  7251. lock.enter();
  7252. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7253. const ReferenceCountedObjectPtr<ObjectClass> result (data.elements [index]);
  7254. lock.exit();
  7255. return result;
  7256. }
  7257. /** Returns a pointer to the first object in the array.
  7258. This will return a null pointer if the array's empty.
  7259. @see getLast
  7260. */
  7261. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7262. {
  7263. lock.enter();
  7264. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? data.elements [0]
  7265. : (ObjectClass*) 0);
  7266. lock.exit();
  7267. return result;
  7268. }
  7269. /** Returns a pointer to the last object in the array.
  7270. This will return a null pointer if the array's empty.
  7271. @see getFirst
  7272. */
  7273. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7274. {
  7275. lock.enter();
  7276. const ReferenceCountedObjectPtr<ObjectClass> result ((numUsed > 0) ? data.elements [numUsed - 1]
  7277. : (ObjectClass*) 0);
  7278. lock.exit();
  7279. return result;
  7280. }
  7281. /** Finds the index of the first occurrence of an object in the array.
  7282. @param objectToLookFor the object to look for
  7283. @returns the index at which the object was found, or -1 if it's not found
  7284. */
  7285. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7286. {
  7287. int result = -1;
  7288. lock.enter();
  7289. ObjectClass** e = data.elements;
  7290. for (int i = numUsed; --i >= 0;)
  7291. {
  7292. if (objectToLookFor == *e)
  7293. {
  7294. result = (int) (e - data.elements);
  7295. break;
  7296. }
  7297. ++e;
  7298. }
  7299. lock.exit();
  7300. return result;
  7301. }
  7302. /** Returns true if the array contains a specified object.
  7303. @param objectToLookFor the object to look for
  7304. @returns true if the object is in the array
  7305. */
  7306. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7307. {
  7308. lock.enter();
  7309. ObjectClass** e = data.elements;
  7310. for (int i = numUsed; --i >= 0;)
  7311. {
  7312. if (objectToLookFor == *e)
  7313. {
  7314. lock.exit();
  7315. return true;
  7316. }
  7317. ++e;
  7318. }
  7319. lock.exit();
  7320. return false;
  7321. }
  7322. /** Appends a new object to the end of the array.
  7323. This will increase the new object's reference count.
  7324. @param newObject the new object to add to the array
  7325. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7326. */
  7327. void add (ObjectClass* const newObject) throw()
  7328. {
  7329. lock.enter();
  7330. data.ensureAllocatedSize (numUsed + 1);
  7331. data.elements [numUsed++] = newObject;
  7332. if (newObject != 0)
  7333. newObject->incReferenceCount();
  7334. lock.exit();
  7335. }
  7336. /** Inserts a new object into the array at the given index.
  7337. If the index is less than 0 or greater than the size of the array, the
  7338. element will be added to the end of the array.
  7339. Otherwise, it will be inserted into the array, moving all the later elements
  7340. along to make room.
  7341. This will increase the new object's reference count.
  7342. @param indexToInsertAt the index at which the new element should be inserted
  7343. @param newObject the new object to add to the array
  7344. @see add, addSorted, addIfNotAlreadyThere, set
  7345. */
  7346. void insert (int indexToInsertAt,
  7347. ObjectClass* const newObject) throw()
  7348. {
  7349. if (indexToInsertAt >= 0)
  7350. {
  7351. lock.enter();
  7352. if (indexToInsertAt > numUsed)
  7353. indexToInsertAt = numUsed;
  7354. data.ensureAllocatedSize (numUsed + 1);
  7355. ObjectClass** const e = data.elements + indexToInsertAt;
  7356. const int numToMove = numUsed - indexToInsertAt;
  7357. if (numToMove > 0)
  7358. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7359. *e = newObject;
  7360. if (newObject != 0)
  7361. newObject->incReferenceCount();
  7362. ++numUsed;
  7363. lock.exit();
  7364. }
  7365. else
  7366. {
  7367. add (newObject);
  7368. }
  7369. }
  7370. /** Appends a new object at the end of the array as long as the array doesn't
  7371. already contain it.
  7372. If the array already contains a matching object, nothing will be done.
  7373. @param newObject the new object to add to the array
  7374. */
  7375. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7376. {
  7377. lock.enter();
  7378. if (! contains (newObject))
  7379. add (newObject);
  7380. lock.exit();
  7381. }
  7382. /** Replaces an object in the array with a different one.
  7383. If the index is less than zero, this method does nothing.
  7384. If the index is beyond the end of the array, the new object is added to the end of the array.
  7385. The object being added has its reference count increased, and if it's replacing
  7386. another object, then that one has its reference count decreased, and may be deleted.
  7387. @param indexToChange the index whose value you want to change
  7388. @param newObject the new value to set for this index.
  7389. @see add, insert, remove
  7390. */
  7391. void set (const int indexToChange,
  7392. ObjectClass* const newObject)
  7393. {
  7394. if (indexToChange >= 0)
  7395. {
  7396. lock.enter();
  7397. if (newObject != 0)
  7398. newObject->incReferenceCount();
  7399. if (indexToChange < numUsed)
  7400. {
  7401. if (data.elements [indexToChange] != 0)
  7402. data.elements [indexToChange]->decReferenceCount();
  7403. data.elements [indexToChange] = newObject;
  7404. }
  7405. else
  7406. {
  7407. data.ensureAllocatedSize (numUsed + 1);
  7408. data.elements [numUsed++] = newObject;
  7409. }
  7410. lock.exit();
  7411. }
  7412. }
  7413. /** Adds elements from another array to the end of this array.
  7414. @param arrayToAddFrom the array from which to copy the elements
  7415. @param startIndex the first element of the other array to start copying from
  7416. @param numElementsToAdd how many elements to add from the other array. If this
  7417. value is negative or greater than the number of available elements,
  7418. all available elements will be copied.
  7419. @see add
  7420. */
  7421. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7422. int startIndex = 0,
  7423. int numElementsToAdd = -1) throw()
  7424. {
  7425. arrayToAddFrom.lockArray();
  7426. lock.enter();
  7427. if (startIndex < 0)
  7428. {
  7429. jassertfalse
  7430. startIndex = 0;
  7431. }
  7432. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7433. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7434. if (numElementsToAdd > 0)
  7435. {
  7436. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7437. while (--numElementsToAdd >= 0)
  7438. add (arrayToAddFrom.getUnchecked (startIndex++));
  7439. }
  7440. lock.exit();
  7441. arrayToAddFrom.unlockArray();
  7442. }
  7443. /** Inserts a new object into the array assuming that the array is sorted.
  7444. This will use a comparator to find the position at which the new object
  7445. should go. If the array isn't sorted, the behaviour of this
  7446. method will be unpredictable.
  7447. @param comparator the comparator object to use to compare the elements - see the
  7448. sort() method for details about this object's form
  7449. @param newObject the new object to insert to the array
  7450. @see add, sort
  7451. */
  7452. template <class ElementComparator>
  7453. void addSorted (ElementComparator& comparator,
  7454. ObjectClass* newObject) throw()
  7455. {
  7456. lock.enter();
  7457. insert (findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed), newObject);
  7458. lock.exit();
  7459. }
  7460. /** Inserts or replaces an object in the array, assuming it is sorted.
  7461. This is similar to addSorted, but if a matching element already exists, then it will be
  7462. replaced by the new one, rather than the new one being added as well.
  7463. */
  7464. template <class ElementComparator>
  7465. void addOrReplaceSorted (ElementComparator& comparator,
  7466. ObjectClass* newObject) throw()
  7467. {
  7468. lock.enter();
  7469. const int index = findInsertIndexInSortedArray (comparator, data.elements, newObject, 0, numUsed);
  7470. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  7471. set (index - 1, newObject); // replace an existing object that matches
  7472. else
  7473. insert (index, newObject); // no match, so insert the new one
  7474. lock.exit();
  7475. }
  7476. /** Removes an object from the array.
  7477. This will remove the object at a given index and move back all the
  7478. subsequent objects to close the gap.
  7479. If the index passed in is out-of-range, nothing will happen.
  7480. The object that is removed will have its reference count decreased,
  7481. and may be deleted if not referenced from elsewhere.
  7482. @param indexToRemove the index of the element to remove
  7483. @see removeObject, removeRange
  7484. */
  7485. void remove (const int indexToRemove)
  7486. {
  7487. lock.enter();
  7488. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  7489. {
  7490. ObjectClass** const e = data.elements + indexToRemove;
  7491. if (*e != 0)
  7492. (*e)->decReferenceCount();
  7493. --numUsed;
  7494. const int numberToShift = numUsed - indexToRemove;
  7495. if (numberToShift > 0)
  7496. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  7497. if ((numUsed << 1) < data.numAllocated)
  7498. minimiseStorageOverheads();
  7499. }
  7500. lock.exit();
  7501. }
  7502. /** Removes the first occurrence of a specified object from the array.
  7503. If the item isn't found, no action is taken. If it is found, it is
  7504. removed and has its reference count decreased.
  7505. @param objectToRemove the object to try to remove
  7506. @see remove, removeRange
  7507. */
  7508. void removeObject (ObjectClass* const objectToRemove)
  7509. {
  7510. lock.enter();
  7511. remove (indexOf (objectToRemove));
  7512. lock.exit();
  7513. }
  7514. /** Removes a range of objects from the array.
  7515. This will remove a set of objects, starting from the given index,
  7516. and move any subsequent elements down to close the gap.
  7517. If the range extends beyond the bounds of the array, it will
  7518. be safely clipped to the size of the array.
  7519. The objects that are removed will have their reference counts decreased,
  7520. and may be deleted if not referenced from elsewhere.
  7521. @param startIndex the index of the first object to remove
  7522. @param numberToRemove how many objects should be removed
  7523. @see remove, removeObject
  7524. */
  7525. void removeRange (const int startIndex,
  7526. const int numberToRemove)
  7527. {
  7528. lock.enter();
  7529. const int start = jlimit (0, numUsed, startIndex);
  7530. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  7531. if (end > start)
  7532. {
  7533. int i;
  7534. for (i = start; i < end; ++i)
  7535. {
  7536. if (data.elements[i] != 0)
  7537. {
  7538. data.elements[i]->decReferenceCount();
  7539. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  7540. }
  7541. }
  7542. const int rangeSize = end - start;
  7543. ObjectClass** e = data.elements + start;
  7544. i = numUsed - end;
  7545. numUsed -= rangeSize;
  7546. while (--i >= 0)
  7547. {
  7548. *e = e [rangeSize];
  7549. ++e;
  7550. }
  7551. if ((numUsed << 1) < data.numAllocated)
  7552. minimiseStorageOverheads();
  7553. }
  7554. lock.exit();
  7555. }
  7556. /** Removes the last n objects from the array.
  7557. The objects that are removed will have their reference counts decreased,
  7558. and may be deleted if not referenced from elsewhere.
  7559. @param howManyToRemove how many objects to remove from the end of the array
  7560. @see remove, removeObject, removeRange
  7561. */
  7562. void removeLast (int howManyToRemove = 1)
  7563. {
  7564. lock.enter();
  7565. if (howManyToRemove > numUsed)
  7566. howManyToRemove = numUsed;
  7567. while (--howManyToRemove >= 0)
  7568. remove (numUsed - 1);
  7569. lock.exit();
  7570. }
  7571. /** Swaps a pair of objects in the array.
  7572. If either of the indexes passed in is out-of-range, nothing will happen,
  7573. otherwise the two objects at these positions will be exchanged.
  7574. */
  7575. void swap (const int index1,
  7576. const int index2) throw()
  7577. {
  7578. lock.enter();
  7579. if (((unsigned int) index1) < (unsigned int) numUsed
  7580. && ((unsigned int) index2) < (unsigned int) numUsed)
  7581. {
  7582. swapVariables (data.elements [index1],
  7583. data.elements [index2]);
  7584. }
  7585. lock.exit();
  7586. }
  7587. /** Moves one of the objects to a different position.
  7588. This will move the object to a specified index, shuffling along
  7589. any intervening elements as required.
  7590. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  7591. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  7592. @param currentIndex the index of the object to be moved. If this isn't a
  7593. valid index, then nothing will be done
  7594. @param newIndex the index at which you'd like this object to end up. If this
  7595. is less than zero, it will be moved to the end of the array
  7596. */
  7597. void move (const int currentIndex,
  7598. int newIndex) throw()
  7599. {
  7600. if (currentIndex != newIndex)
  7601. {
  7602. lock.enter();
  7603. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  7604. {
  7605. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  7606. newIndex = numUsed - 1;
  7607. ObjectClass* const value = data.elements [currentIndex];
  7608. if (newIndex > currentIndex)
  7609. {
  7610. memmove (data.elements + currentIndex,
  7611. data.elements + currentIndex + 1,
  7612. (newIndex - currentIndex) * sizeof (ObjectClass*));
  7613. }
  7614. else
  7615. {
  7616. memmove (data.elements + newIndex + 1,
  7617. data.elements + newIndex,
  7618. (currentIndex - newIndex) * sizeof (ObjectClass*));
  7619. }
  7620. data.elements [newIndex] = value;
  7621. }
  7622. lock.exit();
  7623. }
  7624. }
  7625. /** Compares this array to another one.
  7626. @returns true only if the other array contains the same objects in the same order
  7627. */
  7628. bool operator== (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7629. {
  7630. other.lockArray();
  7631. lock.enter();
  7632. bool result = numUsed == other.numUsed;
  7633. if (result)
  7634. {
  7635. for (int i = numUsed; --i >= 0;)
  7636. {
  7637. if (data.elements [i] != other.data.elements [i])
  7638. {
  7639. result = false;
  7640. break;
  7641. }
  7642. }
  7643. }
  7644. lock.exit();
  7645. other.unlockArray();
  7646. return result;
  7647. }
  7648. /** Compares this array to another one.
  7649. @see operator==
  7650. */
  7651. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  7652. {
  7653. return ! operator== (other);
  7654. }
  7655. /** Sorts the elements in the array.
  7656. This will use a comparator object to sort the elements into order. The object
  7657. passed must have a method of the form:
  7658. @code
  7659. int compareElements (ElementType first, ElementType second);
  7660. @endcode
  7661. ..and this method must return:
  7662. - a value of < 0 if the first comes before the second
  7663. - a value of 0 if the two objects are equivalent
  7664. - a value of > 0 if the second comes before the first
  7665. To improve performance, the compareElements() method can be declared as static or const.
  7666. @param comparator the comparator to use for comparing elements.
  7667. @param retainOrderOfEquivalentItems if this is true, then items
  7668. which the comparator says are equivalent will be
  7669. kept in the order in which they currently appear
  7670. in the array. This is slower to perform, but may
  7671. be important in some cases. If it's false, a faster
  7672. algorithm is used, but equivalent elements may be
  7673. rearranged.
  7674. @see sortArray
  7675. */
  7676. template <class ElementComparator>
  7677. void sort (ElementComparator& comparator,
  7678. const bool retainOrderOfEquivalentItems = false) const throw()
  7679. {
  7680. (void) comparator; // if you pass in an object with a static compareElements() method, this
  7681. // avoids getting warning messages about the parameter being unused
  7682. lock.enter();
  7683. sortArray (comparator, data.elements, 0, size() - 1, retainOrderOfEquivalentItems);
  7684. lock.exit();
  7685. }
  7686. /** Reduces the amount of storage being used by the array.
  7687. Arrays typically allocate slightly more storage than they need, and after
  7688. removing elements, they may have quite a lot of unused space allocated.
  7689. This method will reduce the amount of allocated storage to a minimum.
  7690. */
  7691. void minimiseStorageOverheads() throw()
  7692. {
  7693. lock.enter();
  7694. if (numUsed == 0)
  7695. {
  7696. data.setAllocatedSize (0);
  7697. }
  7698. else
  7699. {
  7700. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  7701. if (newAllocation < data.numAllocated)
  7702. data.setAllocatedSize (newAllocation);
  7703. }
  7704. lock.exit();
  7705. }
  7706. /** Locks the array's CriticalSection.
  7707. Of course if the type of section used is a DummyCriticalSection, this won't
  7708. have any effect.
  7709. @see unlockArray
  7710. */
  7711. void lockArray() const throw()
  7712. {
  7713. lock.enter();
  7714. }
  7715. /** Unlocks the array's CriticalSection.
  7716. Of course if the type of section used is a DummyCriticalSection, this won't
  7717. have any effect.
  7718. @see lockArray
  7719. */
  7720. void unlockArray() const throw()
  7721. {
  7722. lock.exit();
  7723. }
  7724. juce_UseDebuggingNewOperator
  7725. private:
  7726. ArrayAllocationBase <ObjectClass*> data;
  7727. int numUsed;
  7728. TypeOfCriticalSectionToUse lock;
  7729. };
  7730. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7731. /********* End of inlined file: juce_ReferenceCountedArray.h *********/
  7732. #endif
  7733. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  7734. #endif
  7735. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  7736. #endif
  7737. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7738. /********* Start of inlined file: juce_SortedSet.h *********/
  7739. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  7740. #define __JUCE_SORTEDSET_JUCEHEADER__
  7741. #if JUCE_MSVC
  7742. #pragma warning (push)
  7743. #pragma warning (disable: 4512)
  7744. #endif
  7745. /**
  7746. Holds a set of unique primitive objects, such as ints or doubles.
  7747. A set can only hold one item with a given value, so if for example it's a
  7748. set of integers, attempting to add the same integer twice will do nothing
  7749. the second time.
  7750. Internally, the list of items is kept sorted (which means that whatever
  7751. kind of primitive type is used must support the ==, <, >, <= and >= operators
  7752. to determine the order), and searching the set for known values is very fast
  7753. because it uses a binary-chop method.
  7754. Note that if you're using a class or struct as the element type, it must be
  7755. capable of being copied or moved with a straightforward memcpy, rather than
  7756. needing construction and destruction code.
  7757. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  7758. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7759. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  7760. */
  7761. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7762. class SortedSet
  7763. {
  7764. public:
  7765. /** Creates an empty set.
  7766. @param granularity this is the size of increment by which the internal storage
  7767. used by the array will grow. Only change it from the default if you know the
  7768. array is going to be very big and needs to be able to grow efficiently.
  7769. */
  7770. SortedSet (const int granularity = juceDefaultArrayGranularity) throw()
  7771. : data (granularity),
  7772. numUsed (0)
  7773. {
  7774. }
  7775. /** Creates a copy of another set.
  7776. @param other the set to copy
  7777. */
  7778. SortedSet (const SortedSet<ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7779. : data (other.data.granularity)
  7780. {
  7781. other.lockSet();
  7782. numUsed = other.numUsed;
  7783. data.setAllocatedSize (other.numUsed);
  7784. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  7785. other.unlockSet();
  7786. }
  7787. /** Destructor. */
  7788. ~SortedSet() throw()
  7789. {
  7790. }
  7791. /** Copies another set over this one.
  7792. @param other the set to copy
  7793. */
  7794. const SortedSet <ElementType, TypeOfCriticalSectionToUse>& operator= (const SortedSet <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  7795. {
  7796. if (this != &other)
  7797. {
  7798. other.lockSet();
  7799. lock.enter();
  7800. data.granularity = other.data.granularity;
  7801. data.ensureAllocatedSize (other.size());
  7802. numUsed = other.numUsed;
  7803. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  7804. minimiseStorageOverheads();
  7805. lock.exit();
  7806. other.unlockSet();
  7807. }
  7808. return *this;
  7809. }
  7810. /** Compares this set to another one.
  7811. Two sets are considered equal if they both contain the same set of
  7812. elements.
  7813. @param other the other set to compare with
  7814. */
  7815. bool operator== (const SortedSet<ElementType>& other) const throw()
  7816. {
  7817. lock.enter();
  7818. if (numUsed != other.numUsed)
  7819. {
  7820. lock.exit();
  7821. return false;
  7822. }
  7823. for (int i = numUsed; --i >= 0;)
  7824. {
  7825. if (data.elements [i] != other.data.elements [i])
  7826. {
  7827. lock.exit();
  7828. return false;
  7829. }
  7830. }
  7831. lock.exit();
  7832. return true;
  7833. }
  7834. /** Compares this set to another one.
  7835. Two sets are considered equal if they both contain the same set of
  7836. elements.
  7837. @param other the other set to compare with
  7838. */
  7839. bool operator!= (const SortedSet<ElementType>& other) const throw()
  7840. {
  7841. return ! operator== (other);
  7842. }
  7843. /** Removes all elements from the set.
  7844. This will remove all the elements, and free any storage that the set is
  7845. using. To clear it without freeing the storage, use the clearQuick()
  7846. method instead.
  7847. @see clearQuick
  7848. */
  7849. void clear() throw()
  7850. {
  7851. lock.enter();
  7852. data.setAllocatedSize (0);
  7853. numUsed = 0;
  7854. lock.exit();
  7855. }
  7856. /** Removes all elements from the set without freeing the array's allocated storage.
  7857. @see clear
  7858. */
  7859. void clearQuick() throw()
  7860. {
  7861. lock.enter();
  7862. numUsed = 0;
  7863. lock.exit();
  7864. }
  7865. /** Returns the current number of elements in the set.
  7866. */
  7867. inline int size() const throw()
  7868. {
  7869. return numUsed;
  7870. }
  7871. /** Returns one of the elements in the set.
  7872. If the index passed in is beyond the range of valid elements, this
  7873. will return zero.
  7874. If you're certain that the index will always be a valid element, you
  7875. can call getUnchecked() instead, which is faster.
  7876. @param index the index of the element being requested (0 is the first element in the set)
  7877. @see getUnchecked, getFirst, getLast
  7878. */
  7879. inline ElementType operator[] (const int index) const throw()
  7880. {
  7881. lock.enter();
  7882. const ElementType result = (((unsigned int) index) < (unsigned int) numUsed)
  7883. ? data.elements [index]
  7884. : (ElementType) 0;
  7885. lock.exit();
  7886. return result;
  7887. }
  7888. /** Returns one of the elements in the set, without checking the index passed in.
  7889. Unlike the operator[] method, this will try to return an element without
  7890. checking that the index is within the bounds of the set, so should only
  7891. be used when you're confident that it will always be a valid index.
  7892. @param index the index of the element being requested (0 is the first element in the set)
  7893. @see operator[], getFirst, getLast
  7894. */
  7895. inline ElementType getUnchecked (const int index) const throw()
  7896. {
  7897. lock.enter();
  7898. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7899. const ElementType result = data.elements [index];
  7900. lock.exit();
  7901. return result;
  7902. }
  7903. /** Returns the first element in the set, or 0 if the set is empty.
  7904. @see operator[], getUnchecked, getLast
  7905. */
  7906. inline ElementType getFirst() const throw()
  7907. {
  7908. lock.enter();
  7909. const ElementType result = (numUsed > 0) ? data.elements [0]
  7910. : (ElementType) 0;
  7911. lock.exit();
  7912. return result;
  7913. }
  7914. /** Returns the last element in the set, or 0 if the set is empty.
  7915. @see operator[], getUnchecked, getFirst
  7916. */
  7917. inline ElementType getLast() const throw()
  7918. {
  7919. lock.enter();
  7920. const ElementType result = (numUsed > 0) ? data.elements [numUsed - 1]
  7921. : (ElementType) 0;
  7922. lock.exit();
  7923. return result;
  7924. }
  7925. /** Finds the index of the first element which matches the value passed in.
  7926. This will search the set for the given object, and return the index
  7927. of its first occurrence. If the object isn't found, the method will return -1.
  7928. @param elementToLookFor the value or object to look for
  7929. @returns the index of the object, or -1 if it's not found
  7930. */
  7931. int indexOf (const ElementType elementToLookFor) const throw()
  7932. {
  7933. lock.enter();
  7934. int start = 0;
  7935. int end = numUsed;
  7936. for (;;)
  7937. {
  7938. if (start >= end)
  7939. {
  7940. lock.exit();
  7941. return -1;
  7942. }
  7943. else if (elementToLookFor == data.elements [start])
  7944. {
  7945. lock.exit();
  7946. return start;
  7947. }
  7948. else
  7949. {
  7950. const int halfway = (start + end) >> 1;
  7951. if (halfway == start)
  7952. {
  7953. lock.exit();
  7954. return -1;
  7955. }
  7956. else if (elementToLookFor >= data.elements [halfway])
  7957. start = halfway;
  7958. else
  7959. end = halfway;
  7960. }
  7961. }
  7962. }
  7963. /** Returns true if the set contains at least one occurrence of an object.
  7964. @param elementToLookFor the value or object to look for
  7965. @returns true if the item is found
  7966. */
  7967. bool contains (const ElementType elementToLookFor) const throw()
  7968. {
  7969. lock.enter();
  7970. int start = 0;
  7971. int end = numUsed;
  7972. for (;;)
  7973. {
  7974. if (start >= end)
  7975. {
  7976. lock.exit();
  7977. return false;
  7978. }
  7979. else if (elementToLookFor == data.elements [start])
  7980. {
  7981. lock.exit();
  7982. return true;
  7983. }
  7984. else
  7985. {
  7986. const int halfway = (start + end) >> 1;
  7987. if (halfway == start)
  7988. {
  7989. lock.exit();
  7990. return false;
  7991. }
  7992. else if (elementToLookFor >= data.elements [halfway])
  7993. start = halfway;
  7994. else
  7995. end = halfway;
  7996. }
  7997. }
  7998. }
  7999. /** Adds a new element to the set, (as long as it's not already in there).
  8000. @param newElement the new object to add to the set
  8001. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8002. */
  8003. void add (const ElementType newElement) throw()
  8004. {
  8005. lock.enter();
  8006. int start = 0;
  8007. int end = numUsed;
  8008. for (;;)
  8009. {
  8010. if (start >= end)
  8011. {
  8012. jassert (start <= end);
  8013. insertInternal (start, newElement);
  8014. break;
  8015. }
  8016. else if (newElement == data.elements [start])
  8017. {
  8018. break;
  8019. }
  8020. else
  8021. {
  8022. const int halfway = (start + end) >> 1;
  8023. if (halfway == start)
  8024. {
  8025. if (newElement >= data.elements [halfway])
  8026. insertInternal (start + 1, newElement);
  8027. else
  8028. insertInternal (start, newElement);
  8029. break;
  8030. }
  8031. else if (newElement >= data.elements [halfway])
  8032. start = halfway;
  8033. else
  8034. end = halfway;
  8035. }
  8036. }
  8037. lock.exit();
  8038. }
  8039. /** Adds elements from an array to this set.
  8040. @param elementsToAdd the array of elements to add
  8041. @param numElementsToAdd how many elements are in this other array
  8042. @see add
  8043. */
  8044. void addArray (const ElementType* elementsToAdd,
  8045. int numElementsToAdd) throw()
  8046. {
  8047. lock.enter();
  8048. while (--numElementsToAdd >= 0)
  8049. add (*elementsToAdd++);
  8050. lock.exit();
  8051. }
  8052. /** Adds elements from another set to this one.
  8053. @param setToAddFrom the set from which to copy the elements
  8054. @param startIndex the first element of the other set to start copying from
  8055. @param numElementsToAdd how many elements to add from the other set. If this
  8056. value is negative or greater than the number of available elements,
  8057. all available elements will be copied.
  8058. @see add
  8059. */
  8060. template <class OtherSetType>
  8061. void addSet (const OtherSetType& setToAddFrom,
  8062. int startIndex = 0,
  8063. int numElementsToAdd = -1) throw()
  8064. {
  8065. setToAddFrom.lockSet();
  8066. lock.enter();
  8067. jassert (this != &setToAddFrom);
  8068. if (this != &setToAddFrom)
  8069. {
  8070. if (startIndex < 0)
  8071. {
  8072. jassertfalse
  8073. startIndex = 0;
  8074. }
  8075. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8076. numElementsToAdd = setToAddFrom.size() - startIndex;
  8077. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8078. }
  8079. lock.exit();
  8080. setToAddFrom.unlockSet();
  8081. }
  8082. /** Removes an element from the set.
  8083. This will remove the element at a given index.
  8084. If the index passed in is out-of-range, nothing will happen.
  8085. @param indexToRemove the index of the element to remove
  8086. @returns the element that has been removed
  8087. @see removeValue, removeRange
  8088. */
  8089. ElementType remove (const int indexToRemove) throw()
  8090. {
  8091. lock.enter();
  8092. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8093. {
  8094. --numUsed;
  8095. ElementType* const e = data.elements + indexToRemove;
  8096. ElementType const removed = *e;
  8097. const int numberToShift = numUsed - indexToRemove;
  8098. if (numberToShift > 0)
  8099. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8100. if ((numUsed << 1) < data.numAllocated)
  8101. minimiseStorageOverheads();
  8102. lock.exit();
  8103. return removed;
  8104. }
  8105. else
  8106. {
  8107. lock.exit();
  8108. return 0;
  8109. }
  8110. }
  8111. /** Removes an item from the set.
  8112. This will remove the given element from the set, if it's there.
  8113. @param valueToRemove the object to try to remove
  8114. @see remove, removeRange
  8115. */
  8116. void removeValue (const ElementType valueToRemove) throw()
  8117. {
  8118. lock.enter();
  8119. remove (indexOf (valueToRemove));
  8120. lock.exit();
  8121. }
  8122. /** Removes any elements which are also in another set.
  8123. @param otherSet the other set in which to look for elements to remove
  8124. @see removeValuesNotIn, remove, removeValue, removeRange
  8125. */
  8126. template <class OtherSetType>
  8127. void removeValuesIn (const OtherSetType& otherSet) throw()
  8128. {
  8129. otherSet.lockSet();
  8130. lock.enter();
  8131. if (this == &otherSet)
  8132. {
  8133. clear();
  8134. }
  8135. else
  8136. {
  8137. if (otherSet.size() > 0)
  8138. {
  8139. for (int i = numUsed; --i >= 0;)
  8140. if (otherSet.contains (data.elements [i]))
  8141. remove (i);
  8142. }
  8143. }
  8144. lock.exit();
  8145. otherSet.unlockSet();
  8146. }
  8147. /** Removes any elements which are not found in another set.
  8148. Only elements which occur in this other set will be retained.
  8149. @param otherSet the set in which to look for elements NOT to remove
  8150. @see removeValuesIn, remove, removeValue, removeRange
  8151. */
  8152. template <class OtherSetType>
  8153. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8154. {
  8155. otherSet.lockSet();
  8156. lock.enter();
  8157. if (this != &otherSet)
  8158. {
  8159. if (otherSet.size() <= 0)
  8160. {
  8161. clear();
  8162. }
  8163. else
  8164. {
  8165. for (int i = numUsed; --i >= 0;)
  8166. if (! otherSet.contains (data.elements [i]))
  8167. remove (i);
  8168. }
  8169. }
  8170. lock.exit();
  8171. otherSet.lockSet();
  8172. }
  8173. /** Reduces the amount of storage being used by the set.
  8174. Sets typically allocate slightly more storage than they need, and after
  8175. removing elements, they may have quite a lot of unused space allocated.
  8176. This method will reduce the amount of allocated storage to a minimum.
  8177. */
  8178. void minimiseStorageOverheads() throw()
  8179. {
  8180. lock.enter();
  8181. if (numUsed == 0)
  8182. {
  8183. data.setAllocatedSize (0);
  8184. }
  8185. else
  8186. {
  8187. const int newAllocation = data.granularity * (numUsed / data.granularity + 1);
  8188. if (newAllocation < data.numAllocated)
  8189. data.setAllocatedSize (newAllocation);
  8190. }
  8191. lock.exit();
  8192. }
  8193. /** Locks the set's CriticalSection.
  8194. Of course if the type of section used is a DummyCriticalSection, this won't
  8195. have any effect.
  8196. @see unlockSet
  8197. */
  8198. void lockSet() const throw()
  8199. {
  8200. lock.enter();
  8201. }
  8202. /** Unlocks the set's CriticalSection.
  8203. Of course if the type of section used is a DummyCriticalSection, this won't
  8204. have any effect.
  8205. @see lockSet
  8206. */
  8207. void unlockSet() const throw()
  8208. {
  8209. lock.exit();
  8210. }
  8211. juce_UseDebuggingNewOperator
  8212. private:
  8213. ArrayAllocationBase <ElementType> data;
  8214. int numUsed;
  8215. TypeOfCriticalSectionToUse lock;
  8216. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8217. {
  8218. data.ensureAllocatedSize (numUsed + 1);
  8219. ElementType* const insertPos = data.elements + indexToInsertAt;
  8220. const int numberToMove = numUsed - indexToInsertAt;
  8221. if (numberToMove > 0)
  8222. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8223. *insertPos = newElement;
  8224. ++numUsed;
  8225. }
  8226. };
  8227. #if JUCE_MSVC
  8228. #pragma warning (pop)
  8229. #endif
  8230. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8231. /********* End of inlined file: juce_SortedSet.h *********/
  8232. #endif
  8233. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8234. /********* Start of inlined file: juce_SparseSet.h *********/
  8235. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8236. #define __JUCE_SPARSESET_JUCEHEADER__
  8237. /**
  8238. Holds a set of primitive values, storing them as a set of ranges.
  8239. This container acts like a simple BitArray, but can efficiently hold large
  8240. continguous ranges of values. It's quite a specialised class, mostly useful
  8241. for things like keeping the set of selected rows in a listbox.
  8242. The type used as a template paramter must be an integer type, such as int, short,
  8243. int64, etc.
  8244. */
  8245. template <class Type>
  8246. class SparseSet
  8247. {
  8248. public:
  8249. /** Creates a new empty set. */
  8250. SparseSet() throw()
  8251. {
  8252. }
  8253. /** Creates a copy of another SparseSet. */
  8254. SparseSet (const SparseSet<Type>& other) throw()
  8255. : values (other.values)
  8256. {
  8257. }
  8258. /** Destructor. */
  8259. ~SparseSet() throw()
  8260. {
  8261. }
  8262. /** Clears the set. */
  8263. void clear() throw()
  8264. {
  8265. values.clear();
  8266. }
  8267. /** Checks whether the set is empty.
  8268. This is much quicker than using (size() == 0).
  8269. */
  8270. bool isEmpty() const throw()
  8271. {
  8272. return values.size() == 0;
  8273. }
  8274. /** Returns the number of values in the set.
  8275. Because of the way the data is stored, this method can take longer if there
  8276. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8277. are any items.
  8278. */
  8279. Type size() const throw()
  8280. {
  8281. Type num = 0;
  8282. for (int i = 0; i < values.size(); i += 2)
  8283. num += values[i + 1] - values[i];
  8284. return num;
  8285. }
  8286. /** Returns one of the values in the set.
  8287. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8288. @returns the value at this index, or 0 if it's out-of-range
  8289. */
  8290. Type operator[] (int index) const throw()
  8291. {
  8292. for (int i = 0; i < values.size(); i += 2)
  8293. {
  8294. const Type s = values.getUnchecked(i);
  8295. const Type e = values.getUnchecked(i + 1);
  8296. if (index < e - s)
  8297. return s + index;
  8298. index -= e - s;
  8299. }
  8300. return (Type) 0;
  8301. }
  8302. /** Checks whether a particular value is in the set. */
  8303. bool contains (const Type valueToLookFor) const throw()
  8304. {
  8305. bool on = false;
  8306. for (int i = 0; i < values.size(); ++i)
  8307. {
  8308. if (values.getUnchecked(i) > valueToLookFor)
  8309. return on;
  8310. on = ! on;
  8311. }
  8312. return false;
  8313. }
  8314. /** Returns the number of contiguous blocks of values.
  8315. @see getRange
  8316. */
  8317. int getNumRanges() const throw()
  8318. {
  8319. return values.size() >> 1;
  8320. }
  8321. /** Returns one of the contiguous ranges of values stored.
  8322. @param rangeIndex the index of the range to look up, between 0
  8323. and (getNumRanges() - 1)
  8324. @param startValue on return, the value at the start of the range
  8325. @param numValues on return, the number of values in the range
  8326. @see getTotalRange
  8327. */
  8328. bool getRange (const int rangeIndex,
  8329. Type& startValue,
  8330. Type& numValues) const throw()
  8331. {
  8332. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8333. {
  8334. startValue = values [rangeIndex << 1];
  8335. numValues = values [(rangeIndex << 1) + 1] - startValue;
  8336. return true;
  8337. }
  8338. return false;
  8339. }
  8340. /** Returns the lowest and highest values in the set.
  8341. @see getRange
  8342. */
  8343. bool getTotalRange (Type& lowestValue,
  8344. Type& highestValue) const throw()
  8345. {
  8346. if (values.size() > 0)
  8347. {
  8348. lowestValue = values.getUnchecked (0);
  8349. highestValue = values.getUnchecked (values.size() - 1);
  8350. return true;
  8351. }
  8352. return false;
  8353. }
  8354. /** Adds a range of contiguous values to the set.
  8355. e.g. addRange (10, 4) will add (10, 11, 12, 13) to the set.
  8356. @param firstValue the start of the range of values to add
  8357. @param numValuesToAdd how many values to add
  8358. */
  8359. void addRange (const Type firstValue,
  8360. const Type numValuesToAdd) throw()
  8361. {
  8362. jassert (numValuesToAdd >= 0);
  8363. if (numValuesToAdd > 0)
  8364. {
  8365. removeRange (firstValue, numValuesToAdd);
  8366. IntegerElementComparator<Type> sorter;
  8367. values.addSorted (sorter, firstValue);
  8368. values.addSorted (sorter, firstValue + numValuesToAdd);
  8369. simplify();
  8370. }
  8371. }
  8372. /** Removes a range of values from the set.
  8373. e.g. removeRange (10, 4) will remove (10, 11, 12, 13) from the set.
  8374. @param firstValue the start of the range of values to remove
  8375. @param numValuesToRemove how many values to remove
  8376. */
  8377. void removeRange (const Type firstValue,
  8378. const Type numValuesToRemove) throw()
  8379. {
  8380. jassert (numValuesToRemove >= 0);
  8381. if (numValuesToRemove >= 0
  8382. && firstValue < values.getLast())
  8383. {
  8384. const bool onAtStart = contains (firstValue - 1);
  8385. const Type lastValue = firstValue + jmin (numValuesToRemove, values.getLast() - firstValue);
  8386. const bool onAtEnd = contains (lastValue);
  8387. for (int i = values.size(); --i >= 0;)
  8388. {
  8389. if (values.getUnchecked(i) <= lastValue)
  8390. {
  8391. while (values.getUnchecked(i) >= firstValue)
  8392. {
  8393. values.remove (i);
  8394. if (--i < 0)
  8395. break;
  8396. }
  8397. break;
  8398. }
  8399. }
  8400. IntegerElementComparator<Type> sorter;
  8401. if (onAtStart)
  8402. values.addSorted (sorter, firstValue);
  8403. if (onAtEnd)
  8404. values.addSorted (sorter, lastValue);
  8405. simplify();
  8406. }
  8407. }
  8408. /** Does an XOR of the values in a given range. */
  8409. void invertRange (const Type firstValue,
  8410. const Type numValues)
  8411. {
  8412. SparseSet newItems;
  8413. newItems.addRange (firstValue, numValues);
  8414. int i;
  8415. for (i = getNumRanges(); --i >= 0;)
  8416. {
  8417. const int start = values [i << 1];
  8418. const int end = values [(i << 1) + 1];
  8419. newItems.removeRange (start, end);
  8420. }
  8421. removeRange (firstValue, numValues);
  8422. for (i = newItems.getNumRanges(); --i >= 0;)
  8423. {
  8424. const int start = newItems.values [i << 1];
  8425. const int end = newItems.values [(i << 1) + 1];
  8426. addRange (start, end);
  8427. }
  8428. }
  8429. /** Checks whether any part of a given range overlaps any part of this one. */
  8430. bool overlapsRange (const Type firstValue,
  8431. const Type numValues) throw()
  8432. {
  8433. jassert (numValues >= 0);
  8434. if (numValues > 0)
  8435. {
  8436. for (int i = getNumRanges(); --i >= 0;)
  8437. {
  8438. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8439. return false;
  8440. if (firstValue + numValues > values.getUnchecked (i << 1))
  8441. return true;
  8442. }
  8443. }
  8444. return false;
  8445. }
  8446. /** Checks whether the whole of a given range is contained within this one. */
  8447. bool containsRange (const Type firstValue,
  8448. const Type numValues) throw()
  8449. {
  8450. jassert (numValues >= 0);
  8451. if (numValues > 0)
  8452. {
  8453. for (int i = getNumRanges(); --i >= 0;)
  8454. {
  8455. if (firstValue >= values.getUnchecked ((i << 1) + 1))
  8456. return false;
  8457. if (firstValue >= values.getUnchecked (i << 1)
  8458. && firstValue + numValues <= values.getUnchecked ((i << 1) + 1))
  8459. return true;
  8460. }
  8461. }
  8462. return false;
  8463. }
  8464. bool operator== (const SparseSet<Type>& other) throw()
  8465. {
  8466. return values == other.values;
  8467. }
  8468. bool operator!= (const SparseSet<Type>& other) throw()
  8469. {
  8470. return values != other.values;
  8471. }
  8472. juce_UseDebuggingNewOperator
  8473. private:
  8474. // alternating start/end values of ranges of values that are present.
  8475. Array<Type> values;
  8476. void simplify() throw()
  8477. {
  8478. jassert ((values.size() & 1) == 0);
  8479. for (int i = values.size(); --i > 0;)
  8480. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8481. values.removeRange (i - 1, 2);
  8482. }
  8483. };
  8484. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8485. /********* End of inlined file: juce_SparseSet.h *********/
  8486. #endif
  8487. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  8488. /********* Start of inlined file: juce_ValueTree.h *********/
  8489. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  8490. #define __JUCE_VALUETREE_JUCEHEADER__
  8491. /********* Start of inlined file: juce_Variant.h *********/
  8492. #ifndef __JUCE_VARIANT_JUCEHEADER__
  8493. #define __JUCE_VARIANT_JUCEHEADER__
  8494. class JUCE_API DynamicObject;
  8495. /**
  8496. A variant class, that can be used to hold a range of primitive values.
  8497. A var object can hold a range of simple primitive values, strings, or
  8498. a reference-counted pointer to a DynamicObject. The var class is intended
  8499. to act like the values used in dynamic scripting languages.
  8500. @see DynamicObject
  8501. */
  8502. class JUCE_API var
  8503. {
  8504. public:
  8505. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  8506. /** Creates a void variant. */
  8507. var() throw();
  8508. /** Destructor. */
  8509. ~var();
  8510. var (const var& valueToCopy) throw();
  8511. var (const int value) throw();
  8512. var (const bool value) throw();
  8513. var (const double value) throw();
  8514. var (const char* const value) throw();
  8515. var (const juce_wchar* const value) throw();
  8516. var (const String& value) throw();
  8517. var (DynamicObject* const object) throw();
  8518. var (MethodFunction method) throw();
  8519. const var& operator= (const var& valueToCopy) throw();
  8520. const var& operator= (const int value) throw();
  8521. const var& operator= (const bool value) throw();
  8522. const var& operator= (const double value) throw();
  8523. const var& operator= (const char* const value) throw();
  8524. const var& operator= (const juce_wchar* const value) throw();
  8525. const var& operator= (const String& value) throw();
  8526. const var& operator= (DynamicObject* const object) throw();
  8527. const var& operator= (MethodFunction method) throw();
  8528. operator int() const throw();
  8529. operator bool() const throw();
  8530. operator float() const throw();
  8531. operator double() const throw();
  8532. operator const String() const throw();
  8533. const String toString() const throw();
  8534. DynamicObject* getObject() const throw();
  8535. bool isVoid() const throw() { return type == voidType; }
  8536. bool isInt() const throw() { return type == intType; }
  8537. bool isBool() const throw() { return type == boolType; }
  8538. bool isDouble() const throw() { return type == doubleType; }
  8539. bool isString() const throw() { return type == stringType; }
  8540. bool isObject() const throw() { return type == objectType; }
  8541. bool isMethod() const throw() { return type == methodType; }
  8542. bool operator== (const var& other) const throw();
  8543. bool operator!= (const var& other) const throw();
  8544. /** Writes a binary representation of this value to a stream.
  8545. The data can be read back later using readFromStream().
  8546. */
  8547. void writeToStream (OutputStream& output) const throw();
  8548. /** Reads back a stored binary representation of a value.
  8549. The data in the stream must have been written using writeToStream(), or this
  8550. will have unpredictable results.
  8551. */
  8552. static const var readFromStream (InputStream& input) throw();
  8553. class JUCE_API identifier
  8554. {
  8555. public:
  8556. identifier (const char* const name) throw();
  8557. identifier (const String& name) throw();
  8558. ~identifier() throw();
  8559. bool operator== (const identifier& other) const throw()
  8560. {
  8561. jassert (hashCode != other.hashCode || name == other.name); // check for name hash collisions
  8562. return hashCode == other.hashCode;
  8563. }
  8564. String name;
  8565. int hashCode;
  8566. };
  8567. /** If this variant is an object, this returns one of its properties. */
  8568. const var operator[] (const identifier& propertyName) const throw();
  8569. /** If this variant is an object, this invokes one of its methods with no arguments. */
  8570. const var call (const identifier& method) const;
  8571. /** If this variant is an object, this invokes one of its methods with one argument. */
  8572. const var call (const identifier& method, const var& arg1) const;
  8573. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  8574. const var call (const identifier& method, const var& arg1, const var& arg2) const;
  8575. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  8576. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3);
  8577. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  8578. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  8579. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  8580. const var call (const identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  8581. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  8582. const var invoke (const identifier& method, const var* arguments, int numArguments) const;
  8583. /** If this variant is a method pointer, this invokes it on a target object. */
  8584. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  8585. juce_UseDebuggingNewOperator
  8586. private:
  8587. enum Type
  8588. {
  8589. voidType = 0,
  8590. intType,
  8591. boolType,
  8592. doubleType,
  8593. stringType,
  8594. objectType,
  8595. methodType
  8596. };
  8597. Type type;
  8598. union
  8599. {
  8600. int intValue;
  8601. bool boolValue;
  8602. double doubleValue;
  8603. String* stringValue;
  8604. DynamicObject* objectValue;
  8605. MethodFunction methodValue;
  8606. } value;
  8607. void releaseValue() throw();
  8608. };
  8609. /**
  8610. Represents a dynamically implemented object.
  8611. An instance of this class can be used to store named properties, and
  8612. by subclassing hasMethod() and invokeMethod(), you can give your object
  8613. methods.
  8614. This is intended for use as a wrapper for scripting language objects.
  8615. */
  8616. class JUCE_API DynamicObject : public ReferenceCountedObject
  8617. {
  8618. public:
  8619. DynamicObject();
  8620. /** Destructor. */
  8621. virtual ~DynamicObject();
  8622. /** Returns true if the object has a property with this name.
  8623. Note that if the property is actually a method, this will return false.
  8624. */
  8625. virtual bool hasProperty (const var::identifier& propertyName) const;
  8626. /** Returns a named property.
  8627. This returns a void if no such property exists.
  8628. */
  8629. virtual const var getProperty (const var::identifier& propertyName) const;
  8630. /** Sets a named property. */
  8631. virtual void setProperty (const var::identifier& propertyName, const var& newValue);
  8632. /** Removes a named property. */
  8633. virtual void removeProperty (const var::identifier& propertyName);
  8634. /** Checks whether this object has the specified method.
  8635. The default implementation of this just checks whether there's a property
  8636. with this name that's actually a method, but this can be overridden for
  8637. building objects with dynamic invocation.
  8638. */
  8639. virtual bool hasMethod (const var::identifier& methodName) const;
  8640. /** Invokes a named method on this object.
  8641. The default implementation looks up the named property, and if it's a method
  8642. call, then it invokes it.
  8643. This method is virtual to allow more dynamic invocation to used for objects
  8644. where the methods may not already be set as properies.
  8645. */
  8646. virtual const var invokeMethod (const var::identifier& methodName,
  8647. const var* parameters,
  8648. int numParameters);
  8649. /** Sets up a method.
  8650. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  8651. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  8652. the code easier to read,
  8653. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  8654. @code
  8655. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  8656. @endcode
  8657. */
  8658. void setMethod (const var::identifier& methodName,
  8659. var::MethodFunction methodFunction);
  8660. /** Removes all properties and methods from the object. */
  8661. void clear();
  8662. juce_UseDebuggingNewOperator
  8663. private:
  8664. Array <int> propertyIds;
  8665. OwnedArray <var> propertyValues;
  8666. };
  8667. #endif // __JUCE_VARIANT_JUCEHEADER__
  8668. /********* End of inlined file: juce_Variant.h *********/
  8669. /********* Start of inlined file: juce_UndoManager.h *********/
  8670. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  8671. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  8672. /********* Start of inlined file: juce_ChangeBroadcaster.h *********/
  8673. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  8674. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  8675. /********* Start of inlined file: juce_ChangeListenerList.h *********/
  8676. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  8677. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  8678. /********* Start of inlined file: juce_ChangeListener.h *********/
  8679. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  8680. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  8681. /**
  8682. Receives callbacks about changes to some kind of object.
  8683. Many objects use a ChangeListenerList to keep a set of listeners which they
  8684. will inform when something changes. A subclass of ChangeListener
  8685. is used to receive these callbacks.
  8686. Note that the major difference between an ActionListener and a ChangeListener
  8687. is that for a ChangeListener, multiple changes will be coalesced into fewer
  8688. callbacks, but ActionListeners perform one callback for every event posted.
  8689. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  8690. */
  8691. class JUCE_API ChangeListener
  8692. {
  8693. public:
  8694. /** Destructor. */
  8695. virtual ~ChangeListener() {}
  8696. /** Overridden by your subclass to receive the callback.
  8697. @param objectThatHasChanged the value that was passed to the
  8698. ChangeListenerList::sendChangeMessage() method
  8699. */
  8700. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  8701. };
  8702. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  8703. /********* End of inlined file: juce_ChangeListener.h *********/
  8704. /********* Start of inlined file: juce_MessageListener.h *********/
  8705. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  8706. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  8707. /********* Start of inlined file: juce_Message.h *********/
  8708. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  8709. #define __JUCE_MESSAGE_JUCEHEADER__
  8710. class MessageListener;
  8711. class MessageManager;
  8712. /** The base class for objects that can be delivered to a MessageListener.
  8713. The simplest Message object contains a few integer and pointer parameters
  8714. that the user can set, and this is enough for a lot of purposes. For passing more
  8715. complex data, subclasses of Message can also be used.
  8716. @see MessageListener, MessageManager, ActionListener, ChangeListener
  8717. */
  8718. class JUCE_API Message
  8719. {
  8720. public:
  8721. /** Creates an uninitialised message.
  8722. The class's variables will also be left uninitialised.
  8723. */
  8724. Message() throw();
  8725. /** Creates a message object, filling in the member variables.
  8726. The corresponding public member variables will be set from the parameters
  8727. passed in.
  8728. */
  8729. Message (const int intParameter1,
  8730. const int intParameter2,
  8731. const int intParameter3,
  8732. void* const pointerParameter) throw();
  8733. /** Destructor. */
  8734. virtual ~Message() throw();
  8735. // These values can be used for carrying simple data that the application needs to
  8736. // pass around. For more complex messages, just create a subclass.
  8737. int intParameter1; /**< user-defined integer value. */
  8738. int intParameter2; /**< user-defined integer value. */
  8739. int intParameter3; /**< user-defined integer value. */
  8740. void* pointerParameter; /**< user-defined pointer value. */
  8741. juce_UseDebuggingNewOperator
  8742. private:
  8743. friend class MessageListener;
  8744. friend class MessageManager;
  8745. MessageListener* messageRecipient;
  8746. Message (const Message&);
  8747. const Message& operator= (const Message&);
  8748. };
  8749. #endif // __JUCE_MESSAGE_JUCEHEADER__
  8750. /********* End of inlined file: juce_Message.h *********/
  8751. /**
  8752. MessageListener subclasses can post and receive Message objects.
  8753. @see Message, MessageManager, ActionListener, ChangeListener
  8754. */
  8755. class JUCE_API MessageListener
  8756. {
  8757. protected:
  8758. /** Creates a MessageListener. */
  8759. MessageListener() throw();
  8760. public:
  8761. /** Destructor.
  8762. When a MessageListener is deleted, it removes itself from a global list
  8763. of registered listeners, so that the isValidMessageListener() method
  8764. will no longer return true.
  8765. */
  8766. virtual ~MessageListener();
  8767. /** This is the callback method that receives incoming messages.
  8768. This is called by the MessageManager from its dispatch loop.
  8769. @see postMessage
  8770. */
  8771. virtual void handleMessage (const Message& message) = 0;
  8772. /** Sends a message to the message queue, for asynchronous delivery to this listener
  8773. later on.
  8774. This method can be called safely by any thread.
  8775. @param message the message object to send - this will be deleted
  8776. automatically by the message queue, so don't keep any
  8777. references to it after calling this method.
  8778. @see handleMessage
  8779. */
  8780. void postMessage (Message* const message) const throw();
  8781. /** Checks whether this MessageListener has been deleted.
  8782. Although not foolproof, this method is safe to call on dangling or null
  8783. pointers. A list of active MessageListeners is kept internally, so this
  8784. checks whether the object is on this list or not.
  8785. Note that it's possible to get a false-positive here, if an object is
  8786. deleted and another is subsequently created that happens to be at the
  8787. exact same memory location, but I can't think of a good way of avoiding
  8788. this.
  8789. */
  8790. bool isValidMessageListener() const throw();
  8791. };
  8792. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  8793. /********* End of inlined file: juce_MessageListener.h *********/
  8794. /********* Start of inlined file: juce_ScopedLock.h *********/
  8795. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  8796. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  8797. /**
  8798. Automatically locks and unlocks a CriticalSection object.
  8799. Use one of these as a local variable to control access to a CriticalSection.
  8800. e.g. @code
  8801. CriticalSection myCriticalSection;
  8802. for (;;)
  8803. {
  8804. const ScopedLock myScopedLock (myCriticalSection);
  8805. // myCriticalSection is now locked
  8806. ...do some stuff...
  8807. // myCriticalSection gets unlocked here.
  8808. }
  8809. @endcode
  8810. @see CriticalSection, ScopedUnlock
  8811. */
  8812. class JUCE_API ScopedLock
  8813. {
  8814. public:
  8815. /** Creates a ScopedLock.
  8816. As soon as it is created, this will lock the CriticalSection, and
  8817. when the ScopedLock object is deleted, the CriticalSection will
  8818. be unlocked.
  8819. Make sure this object is created and deleted by the same thread,
  8820. otherwise there are no guarantees what will happen! Best just to use it
  8821. as a local stack object, rather than creating one with the new() operator.
  8822. */
  8823. inline ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  8824. /** Destructor.
  8825. The CriticalSection will be unlocked when the destructor is called.
  8826. Make sure this object is created and deleted by the same thread,
  8827. otherwise there are no guarantees what will happen!
  8828. */
  8829. inline ~ScopedLock() throw() { lock_.exit(); }
  8830. private:
  8831. const CriticalSection& lock_;
  8832. ScopedLock (const ScopedLock&);
  8833. const ScopedLock& operator= (const ScopedLock&);
  8834. };
  8835. /**
  8836. Automatically unlocks and re-locks a CriticalSection object.
  8837. This is the reverse of a ScopedLock object - instead of locking the critical
  8838. section for the lifetime of this object, it unlocks it.
  8839. Make sure you don't try to unlock critical sections that aren't actually locked!
  8840. e.g. @code
  8841. CriticalSection myCriticalSection;
  8842. for (;;)
  8843. {
  8844. const ScopedLock myScopedLock (myCriticalSection);
  8845. // myCriticalSection is now locked
  8846. ... do some stuff with it locked ..
  8847. while (xyz)
  8848. {
  8849. ... do some stuff with it locked ..
  8850. const ScopedUnlock unlocker (myCriticalSection);
  8851. // myCriticalSection is now unlocked for the remainder of this block,
  8852. // and re-locked at the end.
  8853. ...do some stuff with it unlocked ...
  8854. }
  8855. // myCriticalSection gets unlocked here.
  8856. }
  8857. @endcode
  8858. @see CriticalSection, ScopedLock
  8859. */
  8860. class ScopedUnlock
  8861. {
  8862. public:
  8863. /** Creates a ScopedUnlock.
  8864. As soon as it is created, this will unlock the CriticalSection, and
  8865. when the ScopedLock object is deleted, the CriticalSection will
  8866. be re-locked.
  8867. Make sure this object is created and deleted by the same thread,
  8868. otherwise there are no guarantees what will happen! Best just to use it
  8869. as a local stack object, rather than creating one with the new() operator.
  8870. */
  8871. inline ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  8872. /** Destructor.
  8873. The CriticalSection will be unlocked when the destructor is called.
  8874. Make sure this object is created and deleted by the same thread,
  8875. otherwise there are no guarantees what will happen!
  8876. */
  8877. inline ~ScopedUnlock() throw() { lock_.enter(); }
  8878. private:
  8879. const CriticalSection& lock_;
  8880. ScopedUnlock (const ScopedLock&);
  8881. const ScopedUnlock& operator= (const ScopedUnlock&);
  8882. };
  8883. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  8884. /********* End of inlined file: juce_ScopedLock.h *********/
  8885. /**
  8886. A set of ChangeListeners.
  8887. Listeners can be added and removed from the list, and change messages can be
  8888. broadcast to all the listeners.
  8889. @see ChangeListener, ChangeBroadcaster
  8890. */
  8891. class JUCE_API ChangeListenerList : public MessageListener
  8892. {
  8893. public:
  8894. /** Creates an empty list. */
  8895. ChangeListenerList() throw();
  8896. /** Destructor. */
  8897. ~ChangeListenerList() throw();
  8898. /** Adds a listener to the list.
  8899. (Trying to add a listener that's already on the list will have no effect).
  8900. */
  8901. void addChangeListener (ChangeListener* const listener) throw();
  8902. /** Removes a listener from the list.
  8903. If the listener isn't on the list, this won't have any effect.
  8904. */
  8905. void removeChangeListener (ChangeListener* const listener) throw();
  8906. /** Removes all listeners from the list. */
  8907. void removeAllChangeListeners() throw();
  8908. /** Posts an asynchronous change message to all the listeners.
  8909. If a message has already been sent and hasn't yet been delivered, this
  8910. method won't send another - in this way it coalesces multiple frequent
  8911. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  8912. with the ActionListener, which posts a new event for every call to its
  8913. sendActionMessage() method.
  8914. Only listeners which are on the list when the change event is delivered
  8915. will receive the event - and this may include listeners that weren't on
  8916. the list when the change message was sent.
  8917. @param objectThatHasChanged this pointer is passed to the
  8918. ChangeListener::changeListenerCallback() method,
  8919. and can be any value the application needs
  8920. @see sendSynchronousChangeMessage
  8921. */
  8922. void sendChangeMessage (void* objectThatHasChanged) throw();
  8923. /** This will synchronously callback all the ChangeListeners.
  8924. Use this if you need to synchronously force a call to all the
  8925. listeners' ChangeListener::changeListenerCallback() methods.
  8926. */
  8927. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  8928. /** If a change message has been sent but not yet dispatched, this will
  8929. use sendSynchronousChangeMessage() to make the callback immediately.
  8930. */
  8931. void dispatchPendingMessages();
  8932. /** @internal */
  8933. void handleMessage (const Message&);
  8934. juce_UseDebuggingNewOperator
  8935. private:
  8936. SortedSet <void*> listeners;
  8937. CriticalSection lock;
  8938. void* lastChangedObject;
  8939. bool messagePending;
  8940. ChangeListenerList (const ChangeListenerList&);
  8941. const ChangeListenerList& operator= (const ChangeListenerList&);
  8942. };
  8943. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  8944. /********* End of inlined file: juce_ChangeListenerList.h *********/
  8945. /** Manages a list of ChangeListeners, and can send them messages.
  8946. To quickly add methods to your class that can add/remove change
  8947. listeners and broadcast to them, you can derive from this.
  8948. @see ChangeListenerList, ChangeListener
  8949. */
  8950. class JUCE_API ChangeBroadcaster
  8951. {
  8952. public:
  8953. /** Creates an ChangeBroadcaster. */
  8954. ChangeBroadcaster() throw();
  8955. /** Destructor. */
  8956. virtual ~ChangeBroadcaster();
  8957. /** Adds a listener to the list.
  8958. (Trying to add a listener that's already on the list will have no effect).
  8959. */
  8960. void addChangeListener (ChangeListener* const listener) throw();
  8961. /** Removes a listener from the list.
  8962. If the listener isn't on the list, this won't have any effect.
  8963. */
  8964. void removeChangeListener (ChangeListener* const listener) throw();
  8965. /** Removes all listeners from the list. */
  8966. void removeAllChangeListeners() throw();
  8967. /** Broadcasts a change message to all the registered listeners.
  8968. The message will be delivered asynchronously by the event thread, so this
  8969. method will not directly call any of the listeners. For a synchronous
  8970. message, use sendSynchronousChangeMessage().
  8971. @see ChangeListenerList::sendActionMessage
  8972. */
  8973. void sendChangeMessage (void* objectThatHasChanged) throw();
  8974. /** Sends a synchronous change message to all the registered listeners.
  8975. @see ChangeListenerList::sendSynchronousChangeMessage
  8976. */
  8977. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  8978. /** If a change message has been sent but not yet dispatched, this will
  8979. use sendSynchronousChangeMessage() to make the callback immediately.
  8980. */
  8981. void dispatchPendingMessages();
  8982. private:
  8983. ChangeListenerList changeListenerList;
  8984. ChangeBroadcaster (const ChangeBroadcaster&);
  8985. const ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  8986. };
  8987. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  8988. /********* End of inlined file: juce_ChangeBroadcaster.h *********/
  8989. /********* Start of inlined file: juce_UndoableAction.h *********/
  8990. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  8991. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  8992. /**
  8993. Used by the UndoManager class to store an action which can be done
  8994. and undone.
  8995. @see UndoManager
  8996. */
  8997. class JUCE_API UndoableAction
  8998. {
  8999. protected:
  9000. /** Creates an action. */
  9001. UndoableAction() throw() {}
  9002. public:
  9003. /** Destructor. */
  9004. virtual ~UndoableAction() {}
  9005. /** Overridden by a subclass to perform the action.
  9006. This method is called by the UndoManager, and shouldn't be used directly by
  9007. applications.
  9008. Be careful not to make any calls in a perform() method that could call
  9009. recursively back into the UndoManager::perform() method
  9010. @returns true if the action could be performed.
  9011. @see UndoManager::perform
  9012. */
  9013. virtual bool perform() = 0;
  9014. /** Overridden by a subclass to undo the action.
  9015. This method is called by the UndoManager, and shouldn't be used directly by
  9016. applications.
  9017. Be careful not to make any calls in an undo() method that could call
  9018. recursively back into the UndoManager::perform() method
  9019. @returns true if the action could be undone without any errors.
  9020. @see UndoManager::perform
  9021. */
  9022. virtual bool undo() = 0;
  9023. /** Returns a value to indicate how much memory this object takes up.
  9024. Because the UndoManager keeps a list of UndoableActions, this is used
  9025. to work out how much space each one will take up, so that the UndoManager
  9026. can work out how many to keep.
  9027. The default value returned here is 10 - units are arbitrary and
  9028. don't have to be accurate.
  9029. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9030. UndoManager::setMaxNumberOfStoredUnits
  9031. */
  9032. virtual int getSizeInUnits() { return 10; }
  9033. };
  9034. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9035. /********* End of inlined file: juce_UndoableAction.h *********/
  9036. /**
  9037. Manages a list of undo/redo commands.
  9038. An UndoManager object keeps a list of past actions and can use these actions
  9039. to move backwards and forwards through an undo history.
  9040. To use it, create subclasses of UndoableAction which perform all the
  9041. actions you need, then when you need to actually perform an action, create one
  9042. and pass it to the UndoManager's perform() method.
  9043. The manager also uses the concept of 'transactions' to group the actions
  9044. together - all actions performed between calls to beginNewTransaction() are
  9045. grouped together and are all undone/redone as a group.
  9046. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9047. when actions are performed or undone.
  9048. @see UndoableAction
  9049. */
  9050. class JUCE_API UndoManager : public ChangeBroadcaster
  9051. {
  9052. public:
  9053. /** Creates an UndoManager.
  9054. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9055. to indicate how much storage it takes up
  9056. (UndoableAction::getSizeInUnits()), so this
  9057. lets you specify the maximum total number of
  9058. units that the undomanager is allowed to
  9059. keep in memory before letting the older actions
  9060. drop off the end of the list.
  9061. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9062. that will be kept, even if this involves exceeding
  9063. the amount of space specified in maxNumberOfUnitsToKeep
  9064. */
  9065. UndoManager (const int maxNumberOfUnitsToKeep = 30000,
  9066. const int minimumTransactionsToKeep = 30);
  9067. /** Destructor. */
  9068. ~UndoManager();
  9069. /** Deletes all stored actions in the list. */
  9070. void clearUndoHistory();
  9071. /** Returns the current amount of space to use for storing UndoableAction objects.
  9072. @see setMaxNumberOfStoredUnits
  9073. */
  9074. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9075. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9076. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9077. to indicate how much storage it takes up
  9078. (UndoableAction::getSizeInUnits()), so this
  9079. lets you specify the maximum total number of
  9080. units that the undomanager is allowed to
  9081. keep in memory before letting the older actions
  9082. drop off the end of the list.
  9083. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9084. that will be kept, even if this involves exceeding
  9085. the amount of space specified in maxNumberOfUnitsToKeep
  9086. @see getNumberOfUnitsTakenUpByStoredCommands
  9087. */
  9088. void setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  9089. const int minimumTransactionsToKeep);
  9090. /** Performs an action and adds it to the undo history list.
  9091. @param action the action to perform - this will be deleted by the UndoManager
  9092. when no longer needed
  9093. @param actionName if this string is non-empty, the current transaction will be
  9094. given this name; if it's empty, the current transaction name will
  9095. be left unchanged. See setCurrentTransactionName()
  9096. @returns true if the command succeeds - see UndoableAction::perform
  9097. @see beginNewTransaction
  9098. */
  9099. bool perform (UndoableAction* const action,
  9100. const String& actionName = String::empty);
  9101. /** Starts a new group of actions that together will be treated as a single transaction.
  9102. All actions that are passed to the perform() method between calls to this
  9103. method are grouped together and undone/redone together by a single call to
  9104. undo() or redo().
  9105. @param actionName a description of the transaction that is about to be
  9106. performed
  9107. */
  9108. void beginNewTransaction (const String& actionName = String::empty);
  9109. /** Changes the name stored for the current transaction.
  9110. Each transaction is given a name when the beginNewTransaction() method is
  9111. called, but this can be used to change that name without starting a new
  9112. transaction.
  9113. */
  9114. void setCurrentTransactionName (const String& newName);
  9115. /** Returns true if there's at least one action in the list to undo.
  9116. @see getUndoDescription, undo, canRedo
  9117. */
  9118. bool canUndo() const;
  9119. /** Returns the description of the transaction that would be next to get undone.
  9120. The description returned is the one that was passed into beginNewTransaction
  9121. before the set of actions was performed.
  9122. @see undo
  9123. */
  9124. const String getUndoDescription() const;
  9125. /** Tries to roll-back the last transaction.
  9126. @returns true if the transaction can be undone, and false if it fails, or
  9127. if there aren't any transactions to undo
  9128. */
  9129. bool undo();
  9130. /** Tries to roll-back any actions that were added to the current transaction.
  9131. This will perform an undo() only if there are some actions in the undo list
  9132. that were added after the last call to beginNewTransaction().
  9133. This is useful because it lets you call beginNewTransaction(), then
  9134. perform an operation which may or may not actually perform some actions, and
  9135. then call this method to get rid of any actions that might have been done
  9136. without it rolling back the previous transaction if nothing was actually
  9137. done.
  9138. @returns true if any actions were undone.
  9139. */
  9140. bool undoCurrentTransactionOnly();
  9141. /** Returns a list of the UndoableAction objects that have been performed during the
  9142. transaction that is currently open.
  9143. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9144. were to be called now.
  9145. The first item in the list is the earliest action performed.
  9146. */
  9147. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9148. /** Returns true if there's at least one action in the list to redo.
  9149. @see getRedoDescription, redo, canUndo
  9150. */
  9151. bool canRedo() const;
  9152. /** Returns the description of the transaction that would be next to get redone.
  9153. The description returned is the one that was passed into beginNewTransaction
  9154. before the set of actions was performed.
  9155. @see redo
  9156. */
  9157. const String getRedoDescription() const;
  9158. /** Tries to redo the last transaction that was undone.
  9159. @returns true if the transaction can be redone, and false if it fails, or
  9160. if there aren't any transactions to redo
  9161. */
  9162. bool redo();
  9163. juce_UseDebuggingNewOperator
  9164. private:
  9165. OwnedArray <OwnedArray <UndoableAction> > transactions;
  9166. StringArray transactionNames;
  9167. String currentTransactionName;
  9168. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  9169. bool newTransaction, reentrancyCheck;
  9170. // disallow copy constructor
  9171. UndoManager (const UndoManager&);
  9172. const UndoManager& operator= (const UndoManager&);
  9173. };
  9174. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  9175. /********* End of inlined file: juce_UndoManager.h *********/
  9176. /**
  9177. A powerful tree structure that can be used to hold free-form data, and which can
  9178. handle its own undo and redo behaviour.
  9179. A ValueTree contains a list of named properties as var objects, and also holds
  9180. any number of sub-trees.
  9181. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  9182. they're simply a lightweight reference to a shared data container. Creating a copy
  9183. of another ValueTree simply creates a new reference to the same underlying object - to
  9184. make a separate, deep copy of a tree you should explicitly call createCopy().
  9185. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  9186. and much of the structure of a ValueTree is similar to an XmlElement tree.
  9187. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  9188. contain text elements, the conversion works well and makes a good serialisation
  9189. format. They can also be serialised to a binary format, which is very fast and compact.
  9190. All the methods that change data take an optional UndoManager, which will be used
  9191. to track any changes to the object. For this to work, you have to be careful to
  9192. consistently always use the same UndoManager for all operations to any node inside
  9193. the tree.
  9194. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  9195. one tree to another, be careful to always remove it first, before adding it. This
  9196. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  9197. assertions if you try to do anything dangerous, but there are still plenty of ways it
  9198. could go wrong.
  9199. Listeners can be added to a ValueTree to be told when properies change and when
  9200. nodes are added or removed.
  9201. @see var, XmlElement
  9202. */
  9203. class JUCE_API ValueTree
  9204. {
  9205. public:
  9206. /** Creates an empty ValueTree with the given type name.
  9207. Like an XmlElement, each ValueTree node has a type, which you can access with
  9208. getType() and hasType().
  9209. */
  9210. ValueTree (const String& type) throw();
  9211. /** Creates a reference to another ValueTree. */
  9212. ValueTree (const ValueTree& other) throw();
  9213. /** Makes this object reference another node. */
  9214. const ValueTree& operator= (const ValueTree& other) throw();
  9215. /** Destructor. */
  9216. ~ValueTree() throw();
  9217. /** Returns true if both this and the other tree node refer to the same underlying structure.
  9218. Note that this isn't a value comparison - two independently-created trees which
  9219. contain identical data are not considered equal.
  9220. */
  9221. bool operator== (const ValueTree& other) const throw();
  9222. /** Returns true if this and the other node refer to different underlying structures.
  9223. Note that this isn't a value comparison - two independently-created trees which
  9224. contain identical data are not considered equal.
  9225. */
  9226. bool operator!= (const ValueTree& other) const throw();
  9227. /** Returns true if this node refers to some valid data.
  9228. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  9229. call to getChild().
  9230. */
  9231. bool isValid() const throw() { return object != 0; }
  9232. /** Returns a deep copy of this tree and all its sub-nodes. */
  9233. ValueTree createCopy() const throw();
  9234. /** Returns the type of this node.
  9235. The type is specified when the ValueTree is created.
  9236. @see hasType
  9237. */
  9238. const String getType() const throw();
  9239. /** Returns true if the node has this type.
  9240. The comparison is case-sensitive.
  9241. */
  9242. bool hasType (const String& typeName) const throw();
  9243. /** Returns the value of a named property.
  9244. If no such property has been set, this will return a void variant.
  9245. You can also use operator[] to get a property.
  9246. @see var, setProperty, hasProperty
  9247. */
  9248. const var getProperty (const var::identifier& name) const throw();
  9249. /** Returns the value of a named property.
  9250. If no such property has been set, this will return a void variant. This is the same as
  9251. calling getProperty().
  9252. @see getProperty
  9253. */
  9254. const var operator[] (const var::identifier& name) const throw();
  9255. /** Changes a named property of the node.
  9256. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9257. so that this change can be undone.
  9258. @see var, getProperty, removeProperty
  9259. */
  9260. void setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager) throw();
  9261. /** Returns true if the node contains a named property. */
  9262. bool hasProperty (const var::identifier& name) const throw();
  9263. /** Removes a property from the node.
  9264. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9265. so that this change can be undone.
  9266. */
  9267. void removeProperty (const var::identifier& name, UndoManager* const undoManager) throw();
  9268. /** Removes all properties from the node.
  9269. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9270. so that this change can be undone.
  9271. */
  9272. void removeAllProperties (UndoManager* const undoManager) throw();
  9273. /** Returns the total number of properties that the node contains.
  9274. @see getProperty.
  9275. */
  9276. int getNumProperties() const throw();
  9277. /** Returns the identifier of the property with a given index.
  9278. @see getNumProperties
  9279. */
  9280. const var::identifier getPropertyName (int index) const throw();
  9281. /** Returns the number of child nodes belonging to this one.
  9282. @see getChild
  9283. */
  9284. int getNumChildren() const throw();
  9285. /** Returns one of this node's child nodes.
  9286. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  9287. whether a node is valid).
  9288. */
  9289. ValueTree getChild (int index) const throw();
  9290. /** Looks for a child node with the speficied type name.
  9291. If no such node is found, it'll return an invalid node. (See isValid() to find out
  9292. whether a node is valid).
  9293. */
  9294. ValueTree getChildWithName (const String& type) const throw();
  9295. /** Looks for the first child node that has the speficied property value.
  9296. This will scan the child nodes in order, until it finds one that has property that matches
  9297. the specified value.
  9298. If no such node is found, it'll return an invalid node. (See isValid() to find out
  9299. whether a node is valid).
  9300. */
  9301. ValueTree getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const throw();
  9302. /** Adds a child to this node.
  9303. Make sure that the child is removed from any former parent node before calling this, or
  9304. you'll hit an assertion.
  9305. If the index is < 0 or greater than the current number of child nodes, the new node will
  9306. be added at the end of the list.
  9307. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9308. so that this change can be undone.
  9309. */
  9310. void addChild (ValueTree child, int index, UndoManager* const undoManager) throw();
  9311. /** Removes the specified child from this node's child-list.
  9312. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9313. so that this change can be undone.
  9314. */
  9315. void removeChild (ValueTree& child, UndoManager* const undoManager) throw();
  9316. /** Removes a child from this node's child-list.
  9317. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9318. so that this change can be undone.
  9319. */
  9320. void removeChild (const int childIndex, UndoManager* const undoManager) throw();
  9321. /** Removes all child-nodes from this node.
  9322. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9323. so that this change can be undone.
  9324. */
  9325. void removeAllChildren (UndoManager* const undoManager) throw();
  9326. /** Returns true if this node is anywhere below the specified parent node.
  9327. This returns true if the node is a child-of-a-child, as well as a direct child.
  9328. */
  9329. bool isAChildOf (const ValueTree& possibleParent) const throw();
  9330. /** Returns the parent node that contains this one.
  9331. If the node has no parent, this will return an invalid node. (See isValid() to find out
  9332. whether a node is valid).
  9333. */
  9334. ValueTree getParent() const throw();
  9335. /** Creates an XmlElement that holds a complete image of this node and all its children.
  9336. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  9337. be used to recreate a similar node by calling fromXml()
  9338. @see fromXml
  9339. */
  9340. XmlElement* createXml() const throw();
  9341. /** Tries to recreate a node from its XML representation.
  9342. This isn't designed to cope with random XML data - for a sensible result, it should only
  9343. be fed XML that was created by the createXml() method.
  9344. */
  9345. static ValueTree fromXml (const XmlElement& xml) throw();
  9346. /** Stores this tree (and all its children) in a binary format.
  9347. Once written, the data can be read back with readFromStream().
  9348. It's much faster to load/save your tree in binary form than as XML, but
  9349. obviously isn't human-readable.
  9350. */
  9351. void writeToStream (OutputStream& output) throw();
  9352. /** Reloads a tree from a stream that was written with writeToStream().
  9353. */
  9354. static ValueTree readFromStream (InputStream& input) throw();
  9355. /** Listener class for events that happen to a ValueTree.
  9356. To get events from a ValueTree, make your class implement this interface, and use
  9357. ValueTree::addListener() and ValueTree::removeListener() to register it.
  9358. */
  9359. class JUCE_API Listener
  9360. {
  9361. public:
  9362. /** Destructor. */
  9363. virtual ~Listener() {}
  9364. /** This method is called when one or more of the properties of this node have changed. */
  9365. virtual void valueTreePropertyChanged (ValueTree& tree) = 0;
  9366. /** This method is called when one or more of the children of this node have been added or removed. */
  9367. virtual void valueTreeChildrenChanged (ValueTree& tree) = 0;
  9368. /** This method is called when this node has been added or removed from a parent node. */
  9369. virtual void valueTreeParentChanged() = 0;
  9370. };
  9371. /** Adds a listener to receive callbacks when this node is changed. */
  9372. void addListener (Listener* listener) throw();
  9373. /** Removes a listener that was previously added with addListener(). */
  9374. void removeListener (Listener* listener) throw();
  9375. juce_UseDebuggingNewOperator
  9376. private:
  9377. friend class ValueTreeSetPropertyAction;
  9378. friend class ValueTreeChildChangeAction;
  9379. class SharedObject : public ReferenceCountedObject
  9380. {
  9381. public:
  9382. SharedObject (const String& type) throw();
  9383. SharedObject (const SharedObject& other) throw();
  9384. ~SharedObject() throw();
  9385. struct Property
  9386. {
  9387. Property (const var::identifier& name, const var& value) throw();
  9388. var::identifier name;
  9389. var value;
  9390. };
  9391. const String type;
  9392. OwnedArray <Property> properties;
  9393. ReferenceCountedArray <SharedObject> children;
  9394. SortedSet <Listener*> listeners;
  9395. SharedObject* parent;
  9396. void sendPropertyChangeMessage();
  9397. void sendChildChangeMessage();
  9398. void sendParentChangeMessage();
  9399. const var getProperty (const var::identifier& name) const throw();
  9400. void setProperty (const var::identifier& name, const var& newValue, UndoManager* const undoManager) throw();
  9401. bool hasProperty (const var::identifier& name) const throw();
  9402. void removeProperty (const var::identifier& name, UndoManager* const undoManager) throw();
  9403. void removeAllProperties (UndoManager* const undoManager) throw();
  9404. bool isAChildOf (const SharedObject* const possibleParent) const throw();
  9405. ValueTree getChildWithName (const String& type) const throw();
  9406. ValueTree getChildWithProperty (const var::identifier& propertyName, const var& propertyValue) const throw();
  9407. void addChild (SharedObject* child, int index, UndoManager* const undoManager) throw();
  9408. void removeChild (const int childIndex, UndoManager* const undoManager) throw();
  9409. void removeAllChildren (UndoManager* const undoManager) throw();
  9410. XmlElement* createXml() const throw();
  9411. };
  9412. friend class SharedObject;
  9413. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  9414. ReferenceCountedObjectPtr <SharedObject> object;
  9415. ValueTree (SharedObject* const object_) throw();
  9416. };
  9417. #endif // __JUCE_VALUETREE_JUCEHEADER__
  9418. /********* End of inlined file: juce_ValueTree.h *********/
  9419. #endif
  9420. #ifndef __JUCE_VARIANT_JUCEHEADER__
  9421. #endif
  9422. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  9423. /********* Start of inlined file: juce_VoidArray.h *********/
  9424. #ifndef __JUCE_VOIDARRAY_JUCEHEADER__
  9425. #define __JUCE_VOIDARRAY_JUCEHEADER__
  9426. /**
  9427. A typedef for an Array of void*'s.
  9428. VoidArrays are used in various places throughout the library instead of
  9429. more strongly-typed arrays, to keep code-size low.
  9430. */
  9431. typedef Array <void*> VoidArray;
  9432. #endif // __JUCE_VOIDARRAY_JUCEHEADER__
  9433. /********* End of inlined file: juce_VoidArray.h *********/
  9434. #endif
  9435. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  9436. #endif
  9437. #ifndef __JUCE_DATACONVERSIONS_JUCEHEADER__
  9438. #endif
  9439. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  9440. /********* Start of inlined file: juce_FileLogger.h *********/
  9441. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  9442. #define __JUCE_FILELOGGER_JUCEHEADER__
  9443. /**
  9444. A simple implemenation of a Logger that writes to a file.
  9445. @see Logger
  9446. */
  9447. class JUCE_API FileLogger : public Logger
  9448. {
  9449. public:
  9450. /** Creates a FileLogger for a given file.
  9451. @param fileToWriteTo the file that to use - new messages will be appended
  9452. to the file. If the file doesn't exist, it will be created,
  9453. along with any parent directories that are needed.
  9454. @param welcomeMessage when opened, the logger will write a header to the log, along
  9455. with the current date and time, and this welcome message
  9456. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  9457. but is larger than this number of bytes, then the start of the
  9458. file will be truncated to keep the size down. This prevents a log
  9459. file getting ridiculously large over time. The file will be truncated
  9460. at a new-line boundary. If this value is less than zero, no size limit
  9461. will be imposed; if it's zero, the file will always be deleted. Note that
  9462. the size is only checked once when this object is created - any logging
  9463. that is done later will be appended without any checking
  9464. */
  9465. FileLogger (const File& fileToWriteTo,
  9466. const String& welcomeMessage,
  9467. const int maxInitialFileSizeBytes = 128 * 1024);
  9468. /** Destructor. */
  9469. ~FileLogger();
  9470. void logMessage (const String& message);
  9471. /** Helper function to create a log file in the correct place for this platform.
  9472. On Windows this will return a logger with a path such as:
  9473. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  9474. On the Mac it'll create something like:
  9475. ~/Library/Logs/[logFileName]
  9476. The method might return 0 if the file can't be created for some reason.
  9477. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  9478. it's best to use the something like the name of your application here.
  9479. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  9480. call it "log.txt" because if it goes in a directory with logs
  9481. from other applications (as it will do on the Mac) then no-one
  9482. will know which one is yours!
  9483. @param welcomeMessage a message that will be written to the log when it's opened.
  9484. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  9485. */
  9486. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  9487. const String& logFileName,
  9488. const String& welcomeMessage,
  9489. const int maxInitialFileSizeBytes = 128 * 1024);
  9490. juce_UseDebuggingNewOperator
  9491. private:
  9492. File logFile;
  9493. CriticalSection logLock;
  9494. ScopedPointer <FileOutputStream> logStream;
  9495. void trimFileSize (int maxFileSizeBytes) const;
  9496. FileLogger (const FileLogger&);
  9497. const FileLogger& operator= (const FileLogger&);
  9498. };
  9499. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  9500. /********* End of inlined file: juce_FileLogger.h *********/
  9501. #endif
  9502. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  9503. /********* Start of inlined file: juce_Initialisation.h *********/
  9504. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  9505. #define __JUCE_INITIALISATION_JUCEHEADER__
  9506. /** Initialises Juce's GUI classes.
  9507. If you're embedding Juce into an application that uses its own event-loop rather
  9508. than using the START_JUCE_APPLICATION macro, call this function before making any
  9509. Juce calls, to make sure things are initialised correctly.
  9510. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  9511. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  9512. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  9513. */
  9514. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  9515. /** Clears up any static data being used by Juce's GUI classes.
  9516. If you're embedding Juce into an application that uses its own event-loop rather
  9517. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  9518. code to clean up any juce objects that might be lying around.
  9519. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  9520. */
  9521. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  9522. /** Initialises the core parts of Juce.
  9523. If you're embedding Juce into either a command-line program, call this function
  9524. at the start of your main() function to make sure that Juce is initialised correctly.
  9525. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  9526. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  9527. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  9528. */
  9529. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  9530. /** Clears up any static data being used by Juce's non-gui core classes.
  9531. If you're embedding Juce into either a command-line program, call this function
  9532. at the end of your main() function if you want to make sure any Juce objects are
  9533. cleaned up correctly.
  9534. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  9535. */
  9536. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  9537. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  9538. /********* End of inlined file: juce_Initialisation.h *********/
  9539. #endif
  9540. #ifndef __JUCE_LOGGER_JUCEHEADER__
  9541. #endif
  9542. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  9543. #endif
  9544. #ifndef __JUCE_MEMORY_JUCEHEADER__
  9545. #endif
  9546. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9547. /********* Start of inlined file: juce_PerformanceCounter.h *********/
  9548. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9549. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9550. /** A timer for measuring performance of code and dumping the results to a file.
  9551. e.g. @code
  9552. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  9553. for (;;)
  9554. {
  9555. pc.start();
  9556. doSomethingFishy();
  9557. pc.stop();
  9558. }
  9559. @endcode
  9560. In this example, the time of each period between calling start/stop will be
  9561. measured and averaged over 50 runs, and the results printed to a file
  9562. every 50 times round the loop.
  9563. */
  9564. class JUCE_API PerformanceCounter
  9565. {
  9566. public:
  9567. /** Creates a PerformanceCounter object.
  9568. @param counterName the name used when printing out the statistics
  9569. @param runsPerPrintout the number of start/stop iterations before calling
  9570. printStatistics()
  9571. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  9572. the results are just written to the debugger output
  9573. */
  9574. PerformanceCounter (const String& counterName,
  9575. int runsPerPrintout = 100,
  9576. const File& loggingFile = File::nonexistent);
  9577. /** Destructor. */
  9578. ~PerformanceCounter();
  9579. /** Starts timing.
  9580. @see stop
  9581. */
  9582. void start();
  9583. /** Stops timing and prints out the results.
  9584. The number of iterations before doing a printout of the
  9585. results is set in the constructor.
  9586. @see start
  9587. */
  9588. void stop();
  9589. /** Dumps the current metrics to the debugger output and to a file.
  9590. As well as using Logger::outputDebugString to print the results,
  9591. this will write then to the file specified in the constructor (if
  9592. this was valid).
  9593. */
  9594. void printStatistics();
  9595. juce_UseDebuggingNewOperator
  9596. private:
  9597. String name;
  9598. int numRuns, runsPerPrint;
  9599. double totalTime;
  9600. int64 started;
  9601. File outputFile;
  9602. };
  9603. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  9604. /********* End of inlined file: juce_PerformanceCounter.h *********/
  9605. #endif
  9606. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  9607. #endif
  9608. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9609. /********* Start of inlined file: juce_PlatformUtilities.h *********/
  9610. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9611. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9612. /**
  9613. A collection of miscellaneous platform-specific utilities.
  9614. */
  9615. class JUCE_API PlatformUtilities
  9616. {
  9617. public:
  9618. /** Plays the operating system's default alert 'beep' sound. */
  9619. static void beep();
  9620. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  9621. const String& emailSubject,
  9622. const String& bodyText,
  9623. const StringArray& filesToAttach);
  9624. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  9625. /** MAC ONLY - Turns a Core CF String into a juce one. */
  9626. static const String cfStringToJuceString (CFStringRef cfString);
  9627. /** MAC ONLY - Turns a juce string into a Core CF one. */
  9628. static CFStringRef juceStringToCFString (const String& s);
  9629. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  9630. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  9631. /** MAC ONLY - Turns an FSRef into a juce string path. */
  9632. static const String makePathFromFSRef (FSRef* file);
  9633. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  9634. their precomposed equivalents.
  9635. */
  9636. static const String convertToPrecomposedUnicode (const String& s);
  9637. /** MAC ONLY - Gets the type of a file from the file's resources. */
  9638. static OSType getTypeOfFile (const String& filename);
  9639. /** MAC ONLY - Returns true if this file is actually a bundle. */
  9640. static bool isBundle (const String& filename);
  9641. /** MAC ONLY - Adds an item to the dock */
  9642. static void addItemToDock (const File& file);
  9643. /** MAC ONLY - Returns the current OS version number.
  9644. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  9645. */
  9646. static int getOSXMinorVersionNumber() throw();
  9647. #endif
  9648. #if JUCE_WINDOWS || DOXYGEN
  9649. // Some registry helper functions:
  9650. /** WIN32 ONLY - Returns a string from the registry.
  9651. The path is a string for the entire path of a value in the registry,
  9652. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  9653. */
  9654. static const String getRegistryValue (const String& regValuePath,
  9655. const String& defaultValue = String::empty);
  9656. /** WIN32 ONLY - Sets a registry value as a string.
  9657. This will take care of creating any groups needed to get to the given
  9658. registry value.
  9659. */
  9660. static void setRegistryValue (const String& regValuePath,
  9661. const String& value);
  9662. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  9663. static bool registryValueExists (const String& regValuePath);
  9664. /** WIN32 ONLY - Deletes a registry value. */
  9665. static void deleteRegistryValue (const String& regValuePath);
  9666. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  9667. static void deleteRegistryKey (const String& regKeyPath);
  9668. /** WIN32 ONLY - Creates a file association in the registry.
  9669. This lets you set the exe that should be launched by a given file extension.
  9670. @param fileExtension the file extension to associate, including the
  9671. initial dot, e.g. ".txt"
  9672. @param symbolicDescription a space-free short token to identify the file type
  9673. @param fullDescription a human-readable description of the file type
  9674. @param targetExecutable the executable that should be launched
  9675. @param iconResourceNumber the icon that gets displayed for the file type will be
  9676. found by looking up this resource number in the
  9677. executable. Pass 0 here to not use an icon
  9678. */
  9679. static void registerFileAssociation (const String& fileExtension,
  9680. const String& symbolicDescription,
  9681. const String& fullDescription,
  9682. const File& targetExecutable,
  9683. int iconResourceNumber);
  9684. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  9685. In a normal Juce application this will be set to the module handle
  9686. of the application executable.
  9687. If you're writing a DLL using Juce and plan to use any Juce messaging or
  9688. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  9689. to set the correct module handle in your DllMain() function, because
  9690. the win32 system relies on the correct instance handle when opening windows.
  9691. */
  9692. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  9693. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  9694. @see getCurrentModuleInstanceHandle()
  9695. */
  9696. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  9697. /** WIN32 ONLY - Gets the command-line params as a string.
  9698. This is needed to avoid unicode problems with the argc type params.
  9699. */
  9700. static const String JUCE_CALLTYPE getCurrentCommandLineParams() throw();
  9701. #endif
  9702. /** Clears the floating point unit's flags.
  9703. Only has an effect under win32, currently.
  9704. */
  9705. static void fpuReset();
  9706. #if JUCE_LINUX || JUCE_WINDOWS
  9707. /** Loads a dynamically-linked library into the process's address space.
  9708. @param pathOrFilename the platform-dependent name and search path
  9709. @returns a handle which can be used by getProcedureEntryPoint(), or
  9710. zero if it fails.
  9711. @see freeDynamicLibrary, getProcedureEntryPoint
  9712. */
  9713. static void* loadDynamicLibrary (const String& pathOrFilename);
  9714. /** Frees a dynamically-linked library.
  9715. @param libraryHandle a handle created by loadDynamicLibrary
  9716. @see loadDynamicLibrary, getProcedureEntryPoint
  9717. */
  9718. static void freeDynamicLibrary (void* libraryHandle);
  9719. /** Finds a procedure call in a dynamically-linked library.
  9720. @param libraryHandle a library handle returned by loadDynamicLibrary
  9721. @param procedureName the name of the procedure call to try to load
  9722. @returns a pointer to the function if found, or 0 if it fails
  9723. @see loadDynamicLibrary
  9724. */
  9725. static void* getProcedureEntryPoint (void* libraryHandle,
  9726. const String& procedureName);
  9727. #endif
  9728. #if JUCE_LINUX || DOXYGEN
  9729. #endif
  9730. };
  9731. #if JUCE_MAC || JUCE_IPHONE
  9732. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  9733. using RAII.
  9734. */
  9735. class ScopedAutoReleasePool
  9736. {
  9737. public:
  9738. ScopedAutoReleasePool();
  9739. ~ScopedAutoReleasePool();
  9740. private:
  9741. void* pool;
  9742. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  9743. const ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  9744. };
  9745. #endif
  9746. #if JUCE_MAC
  9747. /**
  9748. A wrapper class for picking up events from an Apple IR remote control device.
  9749. To use it, just create a subclass of this class, implementing the buttonPressed()
  9750. callback, then call start() and stop() to start or stop receiving events.
  9751. */
  9752. class JUCE_API AppleRemoteDevice
  9753. {
  9754. public:
  9755. AppleRemoteDevice();
  9756. virtual ~AppleRemoteDevice();
  9757. /** The set of buttons that may be pressed.
  9758. @see buttonPressed
  9759. */
  9760. enum ButtonType
  9761. {
  9762. menuButton = 0, /**< The menu button (if it's held for a short time). */
  9763. playButton, /**< The play button. */
  9764. plusButton, /**< The plus or volume-up button. */
  9765. minusButton, /**< The minus or volume-down button. */
  9766. rightButton, /**< The right button (if it's held for a short time). */
  9767. leftButton, /**< The left button (if it's held for a short time). */
  9768. rightButton_Long, /**< The right button (if it's held for a long time). */
  9769. leftButton_Long, /**< The menu button (if it's held for a long time). */
  9770. menuButton_Long, /**< The menu button (if it's held for a long time). */
  9771. playButtonSleepMode,
  9772. switched
  9773. };
  9774. /** Override this method to receive the callback about a button press.
  9775. The callback will happen on the application's message thread.
  9776. Some buttons trigger matching up and down events, in which the isDown parameter
  9777. will be true and then false. Others only send a single event when the
  9778. button is pressed.
  9779. */
  9780. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  9781. /** Starts the device running and responding to events.
  9782. Returns true if it managed to open the device.
  9783. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  9784. and will not be available to any other part of the system. If
  9785. false, it will be shared with other apps.
  9786. @see stop
  9787. */
  9788. bool start (const bool inExclusiveMode) throw();
  9789. /** Stops the device running.
  9790. @see start
  9791. */
  9792. void stop() throw();
  9793. /** Returns true if the device has been started successfully.
  9794. */
  9795. bool isActive() const throw();
  9796. /** Returns the ID number of the remote, if it has sent one.
  9797. */
  9798. int getRemoteId() const throw() { return remoteId; }
  9799. juce_UseDebuggingNewOperator
  9800. /** @internal */
  9801. void handleCallbackInternal();
  9802. private:
  9803. void* device;
  9804. void* queue;
  9805. int remoteId;
  9806. bool open (const bool openInExclusiveMode) throw();
  9807. AppleRemoteDevice (const AppleRemoteDevice&);
  9808. const AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  9809. };
  9810. #endif
  9811. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  9812. /********* End of inlined file: juce_PlatformUtilities.h *********/
  9813. #endif
  9814. #ifndef __JUCE_RANDOM_JUCEHEADER__
  9815. /********* Start of inlined file: juce_Random.h *********/
  9816. #ifndef __JUCE_RANDOM_JUCEHEADER__
  9817. #define __JUCE_RANDOM_JUCEHEADER__
  9818. /**
  9819. A simple pseudo-random number generator.
  9820. */
  9821. class JUCE_API Random
  9822. {
  9823. public:
  9824. /** Creates a Random object based on a seed value.
  9825. For a given seed value, the subsequent numbers generated by this object
  9826. will be predictable, so a good idea is to set this value based
  9827. on the time, e.g.
  9828. new Random (Time::currentTimeMillis())
  9829. */
  9830. Random (const int64 seedValue) throw();
  9831. /** Destructor. */
  9832. ~Random() throw();
  9833. /** Returns the next random 32 bit integer.
  9834. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  9835. */
  9836. int nextInt() throw();
  9837. /** Returns the next random number, limited to a given range.
  9838. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  9839. */
  9840. int nextInt (const int maxValue) throw();
  9841. /** Returns the next 64-bit random number.
  9842. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  9843. */
  9844. int64 nextInt64() throw();
  9845. /** Returns the next random floating-point number.
  9846. @returns a random value in the range 0 to 1.0
  9847. */
  9848. float nextFloat() throw();
  9849. /** Returns the next random floating-point number.
  9850. @returns a random value in the range 0 to 1.0
  9851. */
  9852. double nextDouble() throw();
  9853. /** Returns the next random boolean value.
  9854. */
  9855. bool nextBool() throw();
  9856. /** Returns a BitArray containing a random number.
  9857. @returns a random value in the range 0 to (maximumValue - 1).
  9858. */
  9859. const BitArray nextLargeNumber (const BitArray& maximumValue) throw();
  9860. /** Sets a range of bits in a BitArray to random values. */
  9861. void fillBitsRandomly (BitArray& arrayToChange, int startBit, int numBits) throw();
  9862. /** To avoid the overhead of having to create a new Random object whenever
  9863. you need a number, this is a shared application-wide object that
  9864. can be used.
  9865. It's not thread-safe though, so threads should use their own Random object.
  9866. */
  9867. static Random& getSystemRandom() throw();
  9868. /** Resets this Random object to a given seed value. */
  9869. void setSeed (const int64 newSeed) throw();
  9870. /** Reseeds this generator using a value generated from various semi-random system
  9871. properties like the current time, etc.
  9872. Because this function convolves the time with the last seed value, calling
  9873. it repeatedly will increase the randomness of the final result.
  9874. */
  9875. void setSeedRandomly();
  9876. juce_UseDebuggingNewOperator
  9877. private:
  9878. int64 seed;
  9879. };
  9880. #endif // __JUCE_RANDOM_JUCEHEADER__
  9881. /********* End of inlined file: juce_Random.h *********/
  9882. #endif
  9883. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  9884. #endif
  9885. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  9886. /********* Start of inlined file: juce_Singleton.h *********/
  9887. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  9888. #define __JUCE_SINGLETON_JUCEHEADER__
  9889. /**
  9890. Macro to declare member variables and methods for a singleton class.
  9891. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  9892. to the class's definition.
  9893. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  9894. implementation code.
  9895. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  9896. destructor, in case it is deleted by other means than deleteInstance()
  9897. Clients can then call the static method MyClass::getInstance() to get a pointer
  9898. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  9899. no instance currently exists.
  9900. e.g. @code
  9901. class MySingleton
  9902. {
  9903. public:
  9904. MySingleton()
  9905. {
  9906. }
  9907. ~MySingleton()
  9908. {
  9909. // this ensures that no dangling pointers are left when the
  9910. // singleton is deleted.
  9911. clearSingletonInstance();
  9912. }
  9913. juce_DeclareSingleton (MySingleton, false)
  9914. };
  9915. juce_ImplementSingleton (MySingleton)
  9916. // example of usage:
  9917. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  9918. ...
  9919. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  9920. @endcode
  9921. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  9922. than once during the process's lifetime - i.e. after you've created and deleted the
  9923. object, getInstance() will refuse to create another one. This can be useful to stop
  9924. objects being accidentally re-created during your app's shutdown code.
  9925. If you know that your object will only be created and deleted by a single thread, you
  9926. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  9927. of this one.
  9928. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  9929. */
  9930. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  9931. \
  9932. static classname* _singletonInstance; \
  9933. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  9934. \
  9935. static classname* getInstance() \
  9936. { \
  9937. if (_singletonInstance == 0) \
  9938. {\
  9939. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  9940. \
  9941. if (_singletonInstance == 0) \
  9942. { \
  9943. static bool alreadyInside = false; \
  9944. static bool createdOnceAlready = false; \
  9945. \
  9946. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  9947. jassert (! problem); \
  9948. if (! problem) \
  9949. { \
  9950. createdOnceAlready = true; \
  9951. alreadyInside = true; \
  9952. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  9953. alreadyInside = false; \
  9954. \
  9955. _singletonInstance = newObject; \
  9956. } \
  9957. } \
  9958. } \
  9959. \
  9960. return _singletonInstance; \
  9961. } \
  9962. \
  9963. static inline classname* getInstanceWithoutCreating() throw() \
  9964. { \
  9965. return _singletonInstance; \
  9966. } \
  9967. \
  9968. static void deleteInstance() \
  9969. { \
  9970. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  9971. if (_singletonInstance != 0) \
  9972. { \
  9973. classname* const old = _singletonInstance; \
  9974. _singletonInstance = 0; \
  9975. delete old; \
  9976. } \
  9977. } \
  9978. \
  9979. void clearSingletonInstance() throw() \
  9980. { \
  9981. if (_singletonInstance == this) \
  9982. _singletonInstance = 0; \
  9983. }
  9984. /** This is a counterpart to the juce_DeclareSingleton macro.
  9985. After adding the juce_DeclareSingleton to the class definition, this macro has
  9986. to be used in the cpp file.
  9987. */
  9988. #define juce_ImplementSingleton(classname) \
  9989. \
  9990. classname* classname::_singletonInstance = 0; \
  9991. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  9992. /**
  9993. Macro to declare member variables and methods for a singleton class.
  9994. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  9995. section to make access to it thread-safe. If you know that your object will
  9996. only ever be created or deleted by a single thread, then this is a
  9997. more efficient version to use.
  9998. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  9999. than once during the process's lifetime - i.e. after you've created and deleted the
  10000. object, getInstance() will refuse to create another one. This can be useful to stop
  10001. objects being accidentally re-created during your app's shutdown code.
  10002. See the documentation for juce_DeclareSingleton for more information about
  10003. how to use it, the only difference being that you have to use
  10004. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  10005. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  10006. */
  10007. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  10008. \
  10009. static classname* _singletonInstance; \
  10010. \
  10011. static classname* getInstance() \
  10012. { \
  10013. if (_singletonInstance == 0) \
  10014. { \
  10015. static bool alreadyInside = false; \
  10016. static bool createdOnceAlready = false; \
  10017. \
  10018. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10019. jassert (! problem); \
  10020. if (! problem) \
  10021. { \
  10022. createdOnceAlready = true; \
  10023. alreadyInside = true; \
  10024. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10025. alreadyInside = false; \
  10026. \
  10027. _singletonInstance = newObject; \
  10028. } \
  10029. } \
  10030. \
  10031. return _singletonInstance; \
  10032. } \
  10033. \
  10034. static inline classname* getInstanceWithoutCreating() throw() \
  10035. { \
  10036. return _singletonInstance; \
  10037. } \
  10038. \
  10039. static void deleteInstance() \
  10040. { \
  10041. if (_singletonInstance != 0) \
  10042. { \
  10043. classname* const old = _singletonInstance; \
  10044. _singletonInstance = 0; \
  10045. delete old; \
  10046. } \
  10047. } \
  10048. \
  10049. void clearSingletonInstance() throw() \
  10050. { \
  10051. if (_singletonInstance == this) \
  10052. _singletonInstance = 0; \
  10053. }
  10054. /**
  10055. Macro to declare member variables and methods for a singleton class.
  10056. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  10057. for recursion or repeated instantiation. It's intended for use as a lightweight
  10058. version of a singleton, where you're using it in very straightforward
  10059. circumstances and don't need the extra checking.
  10060. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  10061. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  10062. See the documentation for juce_DeclareSingleton for more information about
  10063. how to use it, the only difference being that you have to use
  10064. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  10065. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  10066. */
  10067. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  10068. \
  10069. static classname* _singletonInstance; \
  10070. \
  10071. static classname* getInstance() \
  10072. { \
  10073. if (_singletonInstance == 0) \
  10074. _singletonInstance = new classname(); \
  10075. \
  10076. return _singletonInstance; \
  10077. } \
  10078. \
  10079. static inline classname* getInstanceWithoutCreating() throw() \
  10080. { \
  10081. return _singletonInstance; \
  10082. } \
  10083. \
  10084. static void deleteInstance() \
  10085. { \
  10086. if (_singletonInstance != 0) \
  10087. { \
  10088. classname* const old = _singletonInstance; \
  10089. _singletonInstance = 0; \
  10090. delete old; \
  10091. } \
  10092. } \
  10093. \
  10094. void clearSingletonInstance() throw() \
  10095. { \
  10096. if (_singletonInstance == this) \
  10097. _singletonInstance = 0; \
  10098. }
  10099. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  10100. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  10101. to the class definition, this macro has to be used somewhere in the cpp file.
  10102. */
  10103. #define juce_ImplementSingleton_SingleThreaded(classname) \
  10104. \
  10105. classname* classname::_singletonInstance = 0;
  10106. #endif // __JUCE_SINGLETON_JUCEHEADER__
  10107. /********* End of inlined file: juce_Singleton.h *********/
  10108. #endif
  10109. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  10110. #endif
  10111. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  10112. /********* Start of inlined file: juce_SystemStats.h *********/
  10113. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  10114. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  10115. /**
  10116. Contains methods for finding out about the current hardware and OS configuration.
  10117. */
  10118. class JUCE_API SystemStats
  10119. {
  10120. public:
  10121. /** Returns the current version of JUCE,
  10122. (just in case you didn't already know at compile-time.)
  10123. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  10124. */
  10125. static const String getJUCEVersion() throw();
  10126. /** The set of possible results of the getOperatingSystemType() method.
  10127. */
  10128. enum OperatingSystemType
  10129. {
  10130. UnknownOS = 0,
  10131. MacOSX = 0x1000,
  10132. Linux = 0x2000,
  10133. Win95 = 0x4001,
  10134. Win98 = 0x4002,
  10135. WinNT351 = 0x4103,
  10136. WinNT40 = 0x4104,
  10137. Win2000 = 0x4105,
  10138. WinXP = 0x4106,
  10139. WinVista = 0x4107,
  10140. Windows7 = 0x4108,
  10141. Windows = 0x4000, /**< To test whether any version of Windows is running,
  10142. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  10143. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  10144. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  10145. };
  10146. /** Returns the type of operating system we're running on.
  10147. @returns one of the values from the OperatingSystemType enum.
  10148. @see getOperatingSystemName
  10149. */
  10150. static OperatingSystemType getOperatingSystemType() throw();
  10151. /** Returns the name of the type of operating system we're running on.
  10152. @returns a string describing the OS type.
  10153. @see getOperatingSystemType
  10154. */
  10155. static const String getOperatingSystemName() throw();
  10156. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  10157. */
  10158. static bool isOperatingSystem64Bit() throw();
  10159. // CPU and memory information..
  10160. /** Returns the approximate CPU speed.
  10161. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  10162. what year you're reading this...)
  10163. */
  10164. static int getCpuSpeedInMegaherz() throw();
  10165. /** Returns a string to indicate the CPU vendor.
  10166. Might not be known on some systems.
  10167. */
  10168. static const String getCpuVendor() throw();
  10169. /** Checks whether Intel MMX instructions are available. */
  10170. static bool hasMMX() throw();
  10171. /** Checks whether Intel SSE instructions are available. */
  10172. static bool hasSSE() throw();
  10173. /** Checks whether Intel SSE2 instructions are available. */
  10174. static bool hasSSE2() throw();
  10175. /** Checks whether AMD 3DNOW instructions are available. */
  10176. static bool has3DNow() throw();
  10177. /** Returns the number of CPUs.
  10178. */
  10179. static int getNumCpus() throw();
  10180. /** Returns a clock-cycle tick counter, if available.
  10181. If the machine can do it, this will return a tick-count
  10182. where each tick is one cpu clock cycle - used for profiling
  10183. code.
  10184. @returns the tick count, or zero if not available.
  10185. */
  10186. static int64 getClockCycleCounter() throw();
  10187. /** Finds out how much RAM is in the machine.
  10188. @returns the approximate number of megabytes of memory, or zero if
  10189. something goes wrong when finding out.
  10190. */
  10191. static int getMemorySizeInMegabytes() throw();
  10192. /** Returns the system page-size.
  10193. This is only used by programmers with beards.
  10194. */
  10195. static int getPageSize() throw();
  10196. /** Returns a list of MAC addresses found on this machine.
  10197. @param addresses an array into which the MAC addresses should be copied
  10198. @param maxNum the number of elements in this array
  10199. @param littleEndian the endianness of the numbers to return. If this is true,
  10200. the least-significant byte of each number is the first byte
  10201. of the mac address. If false, the least significant byte is
  10202. the last number. Note that the default values of this parameter
  10203. are different on Mac/PC to avoid breaking old software that was
  10204. written before this parameter was added (when the two systems
  10205. defaulted to using different endiannesses). In newer
  10206. software you probably want to specify an explicit value
  10207. for this.
  10208. @returns the number of MAC addresses that were found
  10209. */
  10210. static int getMACAddresses (int64* addresses, int maxNum,
  10211. #if JUCE_MAC
  10212. const bool littleEndian = true) throw();
  10213. #else
  10214. const bool littleEndian = false) throw();
  10215. #endif
  10216. // not-for-public-use platform-specific method gets called at startup to initialise things.
  10217. static void initialiseStats() throw();
  10218. };
  10219. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  10220. /********* End of inlined file: juce_SystemStats.h *********/
  10221. #endif
  10222. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  10223. #endif
  10224. #ifndef __JUCE_TIME_JUCEHEADER__
  10225. #endif
  10226. #ifndef __JUCE_UUID_JUCEHEADER__
  10227. /********* Start of inlined file: juce_Uuid.h *********/
  10228. #ifndef __JUCE_UUID_JUCEHEADER__
  10229. #define __JUCE_UUID_JUCEHEADER__
  10230. /**
  10231. A universally unique 128-bit identifier.
  10232. This class generates very random unique numbers based on the system time
  10233. and MAC addresses if any are available. It's extremely unlikely that two identical
  10234. UUIDs would ever be created by chance.
  10235. The class includes methods for saving the ID as a string or as raw binary data.
  10236. */
  10237. class JUCE_API Uuid
  10238. {
  10239. public:
  10240. /** Creates a new unique ID. */
  10241. Uuid();
  10242. /** Destructor. */
  10243. ~Uuid() throw();
  10244. /** Creates a copy of another UUID. */
  10245. Uuid (const Uuid& other);
  10246. /** Copies another UUID. */
  10247. Uuid& operator= (const Uuid& other);
  10248. /** Returns true if the ID is zero. */
  10249. bool isNull() const throw();
  10250. /** Compares two UUIDs. */
  10251. bool operator== (const Uuid& other) const;
  10252. /** Compares two UUIDs. */
  10253. bool operator!= (const Uuid& other) const;
  10254. /** Returns a stringified version of this UUID.
  10255. A Uuid object can later be reconstructed from this string using operator= or
  10256. the constructor that takes a string parameter.
  10257. @returns a 32 character hex string.
  10258. */
  10259. const String toString() const;
  10260. /** Creates an ID from an encoded string version.
  10261. @see toString
  10262. */
  10263. Uuid (const String& uuidString);
  10264. /** Copies from a stringified UUID.
  10265. The string passed in should be one that was created with the toString() method.
  10266. */
  10267. Uuid& operator= (const String& uuidString);
  10268. /** Returns a pointer to the internal binary representation of the ID.
  10269. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  10270. the constructor or operator= method that takes an array of uint8s.
  10271. */
  10272. const uint8* getRawData() const throw() { return value.asBytes; }
  10273. /** Creates a UUID from a 16-byte array.
  10274. @see getRawData
  10275. */
  10276. Uuid (const uint8* const rawData);
  10277. /** Sets this UUID from 16-bytes of raw data. */
  10278. Uuid& operator= (const uint8* const rawData);
  10279. juce_UseDebuggingNewOperator
  10280. private:
  10281. union
  10282. {
  10283. uint8 asBytes [16];
  10284. int asInt[4];
  10285. int64 asInt64[2];
  10286. } value;
  10287. };
  10288. #endif // __JUCE_UUID_JUCEHEADER__
  10289. /********* End of inlined file: juce_Uuid.h *********/
  10290. #endif
  10291. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  10292. /********* Start of inlined file: juce_BlowFish.h *********/
  10293. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  10294. #define __JUCE_BLOWFISH_JUCEHEADER__
  10295. /**
  10296. BlowFish encryption class.
  10297. */
  10298. class JUCE_API BlowFish
  10299. {
  10300. public:
  10301. /** Creates an object that can encode/decode based on the specified key.
  10302. The key data can be up to 72 bytes long.
  10303. */
  10304. BlowFish (const uint8* keyData, int keyBytes);
  10305. /** Creates a copy of another blowfish object. */
  10306. BlowFish (const BlowFish& other);
  10307. /** Copies another blowfish object. */
  10308. const BlowFish& operator= (const BlowFish& other);
  10309. /** Destructor. */
  10310. ~BlowFish();
  10311. /** Encrypts a pair of 32-bit integers. */
  10312. void encrypt (uint32& data1, uint32& data2) const;
  10313. /** Decrypts a pair of 32-bit integers. */
  10314. void decrypt (uint32& data1, uint32& data2) const;
  10315. juce_UseDebuggingNewOperator
  10316. private:
  10317. uint32 p[18];
  10318. HeapBlock <uint32> s[4];
  10319. uint32 F (uint32 x) const;
  10320. };
  10321. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  10322. /********* End of inlined file: juce_BlowFish.h *********/
  10323. #endif
  10324. #ifndef __JUCE_MD5_JUCEHEADER__
  10325. /********* Start of inlined file: juce_MD5.h *********/
  10326. #ifndef __JUCE_MD5_JUCEHEADER__
  10327. #define __JUCE_MD5_JUCEHEADER__
  10328. /**
  10329. MD5 checksum class.
  10330. Create one of these with a block of source data or a string, and it calculates the
  10331. MD5 checksum of that data.
  10332. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  10333. */
  10334. class JUCE_API MD5
  10335. {
  10336. public:
  10337. /** Creates a null MD5 object. */
  10338. MD5();
  10339. /** Creates a copy of another MD5. */
  10340. MD5 (const MD5& other);
  10341. /** Copies another MD5. */
  10342. const MD5& operator= (const MD5& other);
  10343. /** Creates a checksum for a block of binary data. */
  10344. MD5 (const MemoryBlock& data);
  10345. /** Creates a checksum for a block of binary data. */
  10346. MD5 (const char* data, const int numBytes);
  10347. /** Creates a checksum for a string.
  10348. Note that this operates on the string as a block of unicode characters, so the
  10349. result you get will differ from the value you'd get if the string was treated
  10350. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  10351. of this method with a checksum created by a different framework, which may have
  10352. used a different encoding.
  10353. */
  10354. MD5 (const String& text);
  10355. /** Creates a checksum for the input from a stream.
  10356. This will read up to the given number of bytes from the stream, and produce the
  10357. checksum of that. If the number of bytes to read is negative, it'll read
  10358. until the stream is exhausted.
  10359. */
  10360. MD5 (InputStream& input, int numBytesToRead = -1);
  10361. /** Creates a checksum for a file. */
  10362. MD5 (const File& file);
  10363. /** Destructor. */
  10364. ~MD5();
  10365. /** Returns the checksum as a 16-byte block of data. */
  10366. const MemoryBlock getRawChecksumData() const;
  10367. /** Returns the checksum as a 32-digit hex string. */
  10368. const String toHexString() const;
  10369. /** Compares this to another MD5. */
  10370. bool operator== (const MD5& other) const;
  10371. /** Compares this to another MD5. */
  10372. bool operator!= (const MD5& other) const;
  10373. juce_UseDebuggingNewOperator
  10374. private:
  10375. uint8 result [16];
  10376. struct ProcessContext
  10377. {
  10378. uint8 buffer [64];
  10379. uint32 state [4];
  10380. uint32 count [2];
  10381. ProcessContext();
  10382. void processBlock (const uint8* const data, int dataSize);
  10383. void transform (const uint8* const buffer);
  10384. void finish (uint8* const result);
  10385. };
  10386. void processStream (InputStream& input, int numBytesToRead);
  10387. };
  10388. #endif // __JUCE_MD5_JUCEHEADER__
  10389. /********* End of inlined file: juce_MD5.h *********/
  10390. #endif
  10391. #ifndef __JUCE_PRIMES_JUCEHEADER__
  10392. /********* Start of inlined file: juce_Primes.h *********/
  10393. #ifndef __JUCE_PRIMES_JUCEHEADER__
  10394. #define __JUCE_PRIMES_JUCEHEADER__
  10395. /**
  10396. Prime number creation class.
  10397. This class contains static methods for generating and testing prime numbers.
  10398. @see BitArray
  10399. */
  10400. class JUCE_API Primes
  10401. {
  10402. public:
  10403. /** Creates a random prime number with a given bit-length.
  10404. The certainty parameter specifies how many iterations to use when testing
  10405. for primality. A safe value might be anything over about 20-30.
  10406. The randomSeeds parameter lets you optionally pass it a set of values with
  10407. which to seed the random number generation, improving the security of the
  10408. keys generated.
  10409. */
  10410. static const BitArray createProbablePrime (int bitLength,
  10411. int certainty,
  10412. const int* randomSeeds = 0,
  10413. int numRandomSeeds = 0) throw();
  10414. /** Tests a number to see if it's prime.
  10415. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  10416. whether the number is prime.
  10417. The certainty parameter specifies how many iterations to use when testing - a
  10418. safe value might be anything over about 20-30.
  10419. */
  10420. static bool isProbablyPrime (const BitArray& number,
  10421. int certainty) throw();
  10422. };
  10423. #endif // __JUCE_PRIMES_JUCEHEADER__
  10424. /********* End of inlined file: juce_Primes.h *********/
  10425. #endif
  10426. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  10427. /********* Start of inlined file: juce_RSAKey.h *********/
  10428. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  10429. #define __JUCE_RSAKEY_JUCEHEADER__
  10430. /**
  10431. RSA public/private key-pair encryption class.
  10432. An object of this type makes up one half of a public/private RSA key pair. Use the
  10433. createKeyPair() method to create a matching pair for encoding/decoding.
  10434. */
  10435. class JUCE_API RSAKey
  10436. {
  10437. public:
  10438. /** Creates a null key object.
  10439. Initialise a pair of objects for use with the createKeyPair() method.
  10440. */
  10441. RSAKey() throw();
  10442. /** Loads a key from an encoded string representation.
  10443. This reloads a key from a string created by the toString() method.
  10444. */
  10445. RSAKey (const String& stringRepresentation) throw();
  10446. /** Destructor. */
  10447. ~RSAKey() throw();
  10448. /** Turns the key into a string representation.
  10449. This can be reloaded using the constructor that takes a string.
  10450. */
  10451. const String toString() const throw();
  10452. /** Encodes or decodes a value.
  10453. Call this on the public key object to encode some data, then use the matching
  10454. private key object to decode it.
  10455. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  10456. initialised correctly.
  10457. NOTE: This method dumbly applies this key to this data. If you encode some data
  10458. and then try to decode it with a key that doesn't match, this method will still
  10459. happily do its job and return true, but the result won't be what you were expecting.
  10460. It's your responsibility to check that the result is what you wanted.
  10461. */
  10462. bool applyToValue (BitArray& value) const throw();
  10463. /** Creates a public/private key-pair.
  10464. Each key will perform one-way encryption that can only be reversed by
  10465. using the other key.
  10466. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  10467. sizes are more secure, but this method will take longer to execute.
  10468. The randomSeeds parameter lets you optionally pass it a set of values with
  10469. which to seed the random number generation, improving the security of the
  10470. keys generated.
  10471. */
  10472. static void createKeyPair (RSAKey& publicKey,
  10473. RSAKey& privateKey,
  10474. const int numBits,
  10475. const int* randomSeeds = 0,
  10476. const int numRandomSeeds = 0) throw();
  10477. juce_UseDebuggingNewOperator
  10478. protected:
  10479. BitArray part1, part2;
  10480. };
  10481. #endif // __JUCE_RSAKEY_JUCEHEADER__
  10482. /********* End of inlined file: juce_RSAKey.h *********/
  10483. #endif
  10484. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10485. /********* Start of inlined file: juce_DirectoryIterator.h *********/
  10486. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10487. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10488. /**
  10489. Searches through a the files in a directory, returning each file that is found.
  10490. A DirectoryIterator will search through a directory and its subdirectories using
  10491. a wildcard filepattern match.
  10492. If you may be finding a large number of files, this is better than
  10493. using File::findChildFiles() because it doesn't block while it finds them
  10494. all, and this is more memory-efficient.
  10495. It can also guess how far it's got using a wildly inaccurate algorithm.
  10496. */
  10497. class JUCE_API DirectoryIterator
  10498. {
  10499. public:
  10500. /** Creates a DirectoryIterator for a given directory.
  10501. After creating one of these, call its next() method to get the
  10502. first file - e.g. @code
  10503. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  10504. while (iter.next())
  10505. {
  10506. File theFileItFound (iter.getFile());
  10507. ... etc
  10508. }
  10509. @endcode
  10510. @param directory the directory to search in
  10511. @param isRecursive whether all the subdirectories should also be searched
  10512. @param wildCard the file pattern to match
  10513. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  10514. whether to look for files, directories, or both.
  10515. */
  10516. DirectoryIterator (const File& directory,
  10517. bool isRecursive,
  10518. const String& wildCard = JUCE_T("*"),
  10519. const int whatToLookFor = File::findFiles) throw();
  10520. /** Destructor. */
  10521. ~DirectoryIterator() throw();
  10522. /** Call this to move the iterator along to the next file.
  10523. @returns true if a file was found (you can then use getFile() to see what it was) - or
  10524. false if there are no more matching files.
  10525. */
  10526. bool next() throw();
  10527. /** Returns the file that the iterator is currently pointing at.
  10528. The result of this call is only valid after a call to next() has returned true.
  10529. */
  10530. const File getFile() const throw();
  10531. /** Returns a guess of how far through the search the iterator has got.
  10532. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  10533. very accurate.
  10534. */
  10535. float getEstimatedProgress() const throw();
  10536. juce_UseDebuggingNewOperator
  10537. private:
  10538. OwnedArray <File> filesFound;
  10539. OwnedArray <File> dirsFound;
  10540. String wildCard;
  10541. int index;
  10542. const int whatToLookFor;
  10543. ScopedPointer <DirectoryIterator> subIterator;
  10544. DirectoryIterator (const DirectoryIterator&);
  10545. const DirectoryIterator& operator= (const DirectoryIterator&);
  10546. };
  10547. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  10548. /********* End of inlined file: juce_DirectoryIterator.h *********/
  10549. #endif
  10550. #ifndef __JUCE_FILE_JUCEHEADER__
  10551. #endif
  10552. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10553. /********* Start of inlined file: juce_FileInputStream.h *********/
  10554. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10555. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10556. /**
  10557. An input stream that reads from a local file.
  10558. @see InputStream, FileOutputStream, File::createInputStream
  10559. */
  10560. class JUCE_API FileInputStream : public InputStream
  10561. {
  10562. public:
  10563. /** Creates a FileInputStream.
  10564. @param fileToRead the file to read from - if the file can't be accessed for some
  10565. reason, then the stream will just contain no data
  10566. */
  10567. FileInputStream (const File& fileToRead);
  10568. /** Destructor. */
  10569. ~FileInputStream();
  10570. const File& getFile() const throw() { return file; }
  10571. int64 getTotalLength();
  10572. int read (void* destBuffer, int maxBytesToRead);
  10573. bool isExhausted();
  10574. int64 getPosition();
  10575. bool setPosition (int64 pos);
  10576. juce_UseDebuggingNewOperator
  10577. private:
  10578. File file;
  10579. void* fileHandle;
  10580. int64 currentPosition, totalSize;
  10581. bool needToSeek;
  10582. FileInputStream (const FileInputStream&);
  10583. const FileInputStream& operator= (const FileInputStream&);
  10584. };
  10585. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  10586. /********* End of inlined file: juce_FileInputStream.h *********/
  10587. #endif
  10588. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10589. /********* Start of inlined file: juce_FileOutputStream.h *********/
  10590. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10591. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10592. /**
  10593. An output stream that writes into a local file.
  10594. @see OutputStream, FileInputStream, File::createOutputStream
  10595. */
  10596. class JUCE_API FileOutputStream : public OutputStream
  10597. {
  10598. public:
  10599. /** Creates a FileOutputStream.
  10600. If the file doesn't exist, it will first be created. If the file can't be
  10601. created or opened, the failedToOpen() method will return
  10602. true.
  10603. If the file already exists when opened, the stream's write-postion will
  10604. be set to the end of the file. To overwrite an existing file,
  10605. use File::deleteFile() before opening the stream, or use setPosition(0)
  10606. after it's opened (although this won't truncate the file).
  10607. It's better to use File::createOutputStream() to create one of these, rather
  10608. than using the class directly.
  10609. */
  10610. FileOutputStream (const File& fileToWriteTo,
  10611. const int bufferSizeToUse = 16384);
  10612. /** Destructor. */
  10613. ~FileOutputStream();
  10614. /** Returns the file that this stream is writing to.
  10615. */
  10616. const File& getFile() const throw() { return file; }
  10617. /** Returns true if the stream couldn't be opened for some reason.
  10618. */
  10619. bool failedToOpen() const throw() { return fileHandle == 0; }
  10620. void flush();
  10621. int64 getPosition();
  10622. bool setPosition (int64 pos);
  10623. bool write (const void* data, int numBytes);
  10624. juce_UseDebuggingNewOperator
  10625. private:
  10626. File file;
  10627. void* fileHandle;
  10628. int64 currentPosition;
  10629. int bufferSize, bytesInBuffer;
  10630. HeapBlock <char> buffer;
  10631. };
  10632. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  10633. /********* End of inlined file: juce_FileOutputStream.h *********/
  10634. #endif
  10635. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  10636. /********* Start of inlined file: juce_FileSearchPath.h *********/
  10637. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  10638. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  10639. /**
  10640. Encapsulates a set of folders that make up a search path.
  10641. @see File
  10642. */
  10643. class JUCE_API FileSearchPath
  10644. {
  10645. public:
  10646. /** Creates an empty search path. */
  10647. FileSearchPath();
  10648. /** Creates a search path from a string of pathnames.
  10649. The path can be semicolon- or comma-separated, e.g.
  10650. "/foo/bar;/foo/moose;/fish/moose"
  10651. The separate folders are tokenised and added to the search path.
  10652. */
  10653. FileSearchPath (const String& path);
  10654. /** Creates a copy of another search path. */
  10655. FileSearchPath (const FileSearchPath& other);
  10656. /** Destructor. */
  10657. ~FileSearchPath();
  10658. /** Uses a string containing a list of pathnames to re-initialise this list.
  10659. This search path is cleared and the semicolon- or comma-separated folders
  10660. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  10661. */
  10662. const FileSearchPath& operator= (const String& path);
  10663. /** Returns the number of folders in this search path.
  10664. @see operator[]
  10665. */
  10666. int getNumPaths() const;
  10667. /** Returns one of the folders in this search path.
  10668. The file returned isn't guaranteed to actually be a valid directory.
  10669. @see getNumPaths
  10670. */
  10671. const File operator[] (const int index) const;
  10672. /** Returns the search path as a semicolon-separated list of directories. */
  10673. const String toString() const;
  10674. /** Adds a new directory to the search path.
  10675. The new directory is added to the end of the list if the insertIndex parameter is
  10676. less than zero, otherwise it is inserted at the given index.
  10677. */
  10678. void add (const File& directoryToAdd,
  10679. const int insertIndex = -1);
  10680. /** Adds a new directory to the search path if it's not already in there. */
  10681. void addIfNotAlreadyThere (const File& directoryToAdd);
  10682. /** Removes a directory from the search path. */
  10683. void remove (const int indexToRemove);
  10684. /** Merges another search path into this one.
  10685. This will remove any duplicate directories.
  10686. */
  10687. void addPath (const FileSearchPath& other);
  10688. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  10689. If the search is intended to be recursive, there's no point having nested folders in the search
  10690. path, because they'll just get searched twice and you'll get duplicate results.
  10691. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  10692. */
  10693. void removeRedundantPaths();
  10694. /** Removes any directories that don't actually exist. */
  10695. void removeNonExistentPaths();
  10696. /** Searches the path for a wildcard.
  10697. This will search all the directories in the search path in order, adding any
  10698. matching files to the results array.
  10699. @param results an array to append the results to
  10700. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  10701. return files, directories, or both.
  10702. @param searchRecursively whether to recursively search the subdirectories too
  10703. @param wildCardPattern a pattern to match against the filenames
  10704. @returns the number of files added to the array
  10705. @see File::findChildFiles
  10706. */
  10707. int findChildFiles (OwnedArray<File>& results,
  10708. const int whatToLookFor,
  10709. const bool searchRecursively,
  10710. const String& wildCardPattern = JUCE_T("*")) const;
  10711. /** Finds out whether a file is inside one of the path's directories.
  10712. This will return true if the specified file is a child of one of the
  10713. directories specified by this path. Note that this doesn't actually do any
  10714. searching or check that the files exist - it just looks at the pathnames
  10715. to work out whether the file would be inside a directory.
  10716. @param fileToCheck the file to look for
  10717. @param checkRecursively if true, then this will return true if the file is inside a
  10718. subfolder of one of the path's directories (at any depth). If false
  10719. it will only return true if the file is actually a direct child
  10720. of one of the directories.
  10721. @see File::isAChildOf
  10722. */
  10723. bool isFileInPath (const File& fileToCheck,
  10724. const bool checkRecursively) const;
  10725. juce_UseDebuggingNewOperator
  10726. private:
  10727. StringArray directories;
  10728. void init (const String& path);
  10729. };
  10730. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  10731. /********* End of inlined file: juce_FileSearchPath.h *********/
  10732. #endif
  10733. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  10734. /********* Start of inlined file: juce_NamedPipe.h *********/
  10735. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  10736. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  10737. /**
  10738. A cross-process pipe that can have data written to and read from it.
  10739. Two or more processes can use these for inter-process communication.
  10740. @see InterprocessConnection
  10741. */
  10742. class JUCE_API NamedPipe
  10743. {
  10744. public:
  10745. /** Creates a NamedPipe. */
  10746. NamedPipe();
  10747. /** Destructor. */
  10748. ~NamedPipe();
  10749. /** Tries to open a pipe that already exists.
  10750. Returns true if it succeeds.
  10751. */
  10752. bool openExisting (const String& pipeName);
  10753. /** Tries to create a new pipe.
  10754. Returns true if it succeeds.
  10755. */
  10756. bool createNewPipe (const String& pipeName);
  10757. /** Closes the pipe, if it's open. */
  10758. void close();
  10759. /** True if the pipe is currently open. */
  10760. bool isOpen() const throw();
  10761. /** Returns the last name that was used to try to open this pipe. */
  10762. const String getName() const throw();
  10763. /** Reads data from the pipe.
  10764. This will block until another thread has written enough data into the pipe to fill
  10765. the number of bytes specified, or until another thread calls the cancelPendingReads()
  10766. method.
  10767. If the operation fails, it returns -1, otherwise, it will return the number of
  10768. bytes read.
  10769. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  10770. this is a maximum timeout for reading from the pipe.
  10771. */
  10772. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  10773. /** Writes some data to the pipe.
  10774. If the operation fails, it returns -1, otherwise, it will return the number of
  10775. bytes written.
  10776. */
  10777. int write (const void* sourceBuffer, int numBytesToWrite,
  10778. int timeOutMilliseconds = 2000);
  10779. /** If any threads are currently blocked on a read operation, this tells them to abort.
  10780. */
  10781. void cancelPendingReads();
  10782. juce_UseDebuggingNewOperator
  10783. private:
  10784. void* internal;
  10785. String currentPipeName;
  10786. NamedPipe (const NamedPipe&);
  10787. const NamedPipe& operator= (const NamedPipe&);
  10788. bool openInternal (const String& pipeName, const bool createPipe);
  10789. };
  10790. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  10791. /********* End of inlined file: juce_NamedPipe.h *********/
  10792. #endif
  10793. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10794. /********* Start of inlined file: juce_ZipFile.h *********/
  10795. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  10796. #define __JUCE_ZIPFILE_JUCEHEADER__
  10797. /********* Start of inlined file: juce_InputSource.h *********/
  10798. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  10799. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  10800. /**
  10801. A lightweight object that can create a stream to read some kind of resource.
  10802. This may be used to refer to a file, or some other kind of source, allowing a
  10803. caller to create an input stream that can read from it when required.
  10804. @see FileInputSource
  10805. */
  10806. class JUCE_API InputSource
  10807. {
  10808. public:
  10809. InputSource() throw() {}
  10810. /** Destructor. */
  10811. virtual ~InputSource() {}
  10812. /** Returns a new InputStream to read this item.
  10813. @returns an inputstream that the caller will delete, or 0 if
  10814. the filename isn't found.
  10815. */
  10816. virtual InputStream* createInputStream() = 0;
  10817. /** Returns a new InputStream to read an item, relative.
  10818. @param relatedItemPath the relative pathname of the resource that is required
  10819. @returns an inputstream that the caller will delete, or 0 if
  10820. the item isn't found.
  10821. */
  10822. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  10823. /** Returns a hash code that uniquely represents this item.
  10824. */
  10825. virtual int64 hashCode() const = 0;
  10826. juce_UseDebuggingNewOperator
  10827. };
  10828. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  10829. /********* End of inlined file: juce_InputSource.h *********/
  10830. /**
  10831. Decodes a ZIP file from a stream.
  10832. This can enumerate the items in a ZIP file and can create suitable stream objects
  10833. to read each one.
  10834. */
  10835. class JUCE_API ZipFile
  10836. {
  10837. public:
  10838. /** Creates a ZipFile for a given stream.
  10839. @param inputStream the stream to read from
  10840. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  10841. will be deleted when this ZipFile object is deleted
  10842. */
  10843. ZipFile (InputStream* const inputStream,
  10844. const bool deleteStreamWhenDestroyed) throw();
  10845. /** Creates a ZipFile based for a file. */
  10846. ZipFile (const File& file);
  10847. /** Creates a ZipFile for an input source.
  10848. The inputSource object will be owned by the zip file, which will delete
  10849. it later when not needed.
  10850. */
  10851. ZipFile (InputSource* const inputSource);
  10852. /** Destructor. */
  10853. ~ZipFile() throw();
  10854. /**
  10855. Contains information about one of the entries in a ZipFile.
  10856. @see ZipFile::getEntry
  10857. */
  10858. struct ZipEntry
  10859. {
  10860. /** The name of the file, which may also include a partial pathname. */
  10861. String filename;
  10862. /** The file's original size. */
  10863. unsigned int uncompressedSize;
  10864. /** The last time the file was modified. */
  10865. Time fileTime;
  10866. };
  10867. /** Returns the number of items in the zip file. */
  10868. int getNumEntries() const throw();
  10869. /** Returns a structure that describes one of the entries in the zip file.
  10870. This may return zero if the index is out of range.
  10871. @see ZipFile::ZipEntry
  10872. */
  10873. const ZipEntry* getEntry (const int index) const throw();
  10874. /** Returns the index of the first entry with a given filename.
  10875. This uses a case-sensitive comparison to look for a filename in the
  10876. list of entries. It might return -1 if no match is found.
  10877. @see ZipFile::ZipEntry
  10878. */
  10879. int getIndexOfFileName (const String& fileName) const throw();
  10880. /** Returns a structure that describes one of the entries in the zip file.
  10881. This uses a case-sensitive comparison to look for a filename in the
  10882. list of entries. It might return 0 if no match is found.
  10883. @see ZipFile::ZipEntry
  10884. */
  10885. const ZipEntry* getEntry (const String& fileName) const throw();
  10886. /** Sorts the list of entries, based on the filename.
  10887. */
  10888. void sortEntriesByFilename();
  10889. /** Creates a stream that can read from one of the zip file's entries.
  10890. The stream that is returned must be deleted by the caller (and
  10891. zero might be returned if a stream can't be opened for some reason).
  10892. The stream must not be used after the ZipFile object that created
  10893. has been deleted.
  10894. */
  10895. InputStream* createStreamForEntry (const int index);
  10896. /** Uncompresses all of the files in the zip file.
  10897. This will expand all the entires into a target directory. The relative
  10898. paths of the entries are used.
  10899. @param targetDirectory the root folder to uncompress to
  10900. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  10901. */
  10902. void uncompressTo (const File& targetDirectory,
  10903. const bool shouldOverwriteFiles = true);
  10904. juce_UseDebuggingNewOperator
  10905. private:
  10906. VoidArray entries;
  10907. friend class ZipInputStream;
  10908. CriticalSection lock;
  10909. InputStream* inputStream;
  10910. ScopedPointer <InputSource> inputSource;
  10911. bool deleteStreamWhenDestroyed;
  10912. int numEntries, centralRecStart;
  10913. #ifdef JUCE_DEBUG
  10914. int numOpenStreams;
  10915. #endif
  10916. void init();
  10917. int findEndOfZipEntryTable (InputStream* in);
  10918. ZipFile (const ZipFile&);
  10919. const ZipFile& operator= (const ZipFile&);
  10920. };
  10921. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  10922. /********* End of inlined file: juce_ZipFile.h *********/
  10923. #endif
  10924. #ifndef __JUCE_SOCKET_JUCEHEADER__
  10925. /********* Start of inlined file: juce_Socket.h *********/
  10926. #ifndef __JUCE_SOCKET_JUCEHEADER__
  10927. #define __JUCE_SOCKET_JUCEHEADER__
  10928. /**
  10929. A wrapper for a streaming (TCP) socket.
  10930. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  10931. sockets, you could also try the InterprocessConnection class.
  10932. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  10933. */
  10934. class JUCE_API StreamingSocket
  10935. {
  10936. public:
  10937. /** Creates an uninitialised socket.
  10938. To connect it, use the connect() method, after which you can read() or write()
  10939. to it.
  10940. To wait for other sockets to connect to this one, the createListener() method
  10941. enters "listener" mode, and can be used to spawn new sockets for each connection
  10942. that comes along.
  10943. */
  10944. StreamingSocket();
  10945. /** Destructor. */
  10946. ~StreamingSocket();
  10947. /** Binds the socket to the specified local port.
  10948. @returns true on success; false may indicate that another socket is already bound
  10949. on the same port
  10950. */
  10951. bool bindToPort (const int localPortNumber);
  10952. /** Tries to connect the socket to hostname:port.
  10953. If timeOutMillisecs is 0, then this method will block until the operating system
  10954. rejects the connection (which could take a long time).
  10955. @returns true if it succeeds.
  10956. @see isConnected
  10957. */
  10958. bool connect (const String& remoteHostname,
  10959. const int remotePortNumber,
  10960. const int timeOutMillisecs = 3000);
  10961. /** True if the socket is currently connected. */
  10962. bool isConnected() const throw() { return connected; }
  10963. /** Closes the connection. */
  10964. void close();
  10965. /** Returns the name of the currently connected host. */
  10966. const String& getHostName() const throw() { return hostName; }
  10967. /** Returns the port number that's currently open. */
  10968. int getPort() const throw() { return portNumber; }
  10969. /** True if the socket is connected to this machine rather than over the network. */
  10970. bool isLocal() const throw();
  10971. /** Waits until the socket is ready for reading or writing.
  10972. If readyForReading is true, it will wait until the socket is ready for
  10973. reading; if false, it will wait until it's ready for writing.
  10974. If the timeout is < 0, it will wait forever, or else will give up after
  10975. the specified time.
  10976. If the socket is ready on return, this returns 1. If it times-out before
  10977. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  10978. */
  10979. int waitUntilReady (const bool readyForReading,
  10980. const int timeoutMsecs) const;
  10981. /** Reads bytes from the socket.
  10982. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  10983. maxBytesToRead bytes have been read, (or until an error occurs). If this
  10984. flag is false, the method will return as much data as is currently available
  10985. without blocking.
  10986. @returns the number of bytes read, or -1 if there was an error.
  10987. @see waitUntilReady
  10988. */
  10989. int read (void* destBuffer, const int maxBytesToRead,
  10990. const bool blockUntilSpecifiedAmountHasArrived);
  10991. /** Writes bytes to the socket from a buffer.
  10992. Note that this method will block unless you have checked the socket is ready
  10993. for writing before calling it (see the waitUntilReady() method).
  10994. @returns the number of bytes written, or -1 if there was an error.
  10995. */
  10996. int write (const void* sourceBuffer, const int numBytesToWrite);
  10997. /** Puts this socket into "listener" mode.
  10998. When in this mode, your thread can call waitForNextConnection() repeatedly,
  10999. which will spawn new sockets for each new connection, so that these can
  11000. be handled in parallel by other threads.
  11001. @param portNumber the port number to listen on
  11002. @param localHostName the interface address to listen on - pass an empty
  11003. string to listen on all addresses
  11004. @returns true if it manages to open the socket successfully.
  11005. @see waitForNextConnection
  11006. */
  11007. bool createListener (const int portNumber, const String& localHostName = String::empty);
  11008. /** When in "listener" mode, this waits for a connection and spawns it as a new
  11009. socket.
  11010. The object that gets returned will be owned by the caller.
  11011. This method can only be called after using createListener().
  11012. @see createListener
  11013. */
  11014. StreamingSocket* waitForNextConnection() const;
  11015. juce_UseDebuggingNewOperator
  11016. private:
  11017. String hostName;
  11018. int volatile portNumber, handle;
  11019. bool connected, isListener;
  11020. StreamingSocket (const String& hostname, const int portNumber, const int handle);
  11021. StreamingSocket (const StreamingSocket&);
  11022. const StreamingSocket& operator= (const StreamingSocket&);
  11023. };
  11024. /**
  11025. A wrapper for a datagram (UDP) socket.
  11026. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  11027. sockets, you could also try the InterprocessConnection class.
  11028. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  11029. */
  11030. class JUCE_API DatagramSocket
  11031. {
  11032. public:
  11033. /**
  11034. Creates an (uninitialised) datagram socket.
  11035. The localPortNumber is the port on which to bind this socket. If this value is 0,
  11036. the port number is assigned by the operating system.
  11037. To use the socket for sending, call the connect() method. This will not immediately
  11038. make a connection, but will save the destination you've provided. After this, you can
  11039. call read() or write().
  11040. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  11041. (may require extra privileges on linux)
  11042. To wait for other sockets to connect to this one, call waitForNextConnection().
  11043. */
  11044. DatagramSocket (const int localPortNumber,
  11045. const bool enableBroadcasting = false);
  11046. /** Destructor. */
  11047. ~DatagramSocket();
  11048. /** Binds the socket to the specified local port.
  11049. @returns true on success; false may indicate that another socket is already bound
  11050. on the same port
  11051. */
  11052. bool bindToPort (const int localPortNumber);
  11053. /** Tries to connect the socket to hostname:port.
  11054. If timeOutMillisecs is 0, then this method will block until the operating system
  11055. rejects the connection (which could take a long time).
  11056. @returns true if it succeeds.
  11057. @see isConnected
  11058. */
  11059. bool connect (const String& remoteHostname,
  11060. const int remotePortNumber,
  11061. const int timeOutMillisecs = 3000);
  11062. /** True if the socket is currently connected. */
  11063. bool isConnected() const throw() { return connected; }
  11064. /** Closes the connection. */
  11065. void close();
  11066. /** Returns the name of the currently connected host. */
  11067. const String& getHostName() const throw() { return hostName; }
  11068. /** Returns the port number that's currently open. */
  11069. int getPort() const throw() { return portNumber; }
  11070. /** True if the socket is connected to this machine rather than over the network. */
  11071. bool isLocal() const throw();
  11072. /** Waits until the socket is ready for reading or writing.
  11073. If readyForReading is true, it will wait until the socket is ready for
  11074. reading; if false, it will wait until it's ready for writing.
  11075. If the timeout is < 0, it will wait forever, or else will give up after
  11076. the specified time.
  11077. If the socket is ready on return, this returns 1. If it times-out before
  11078. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  11079. */
  11080. int waitUntilReady (const bool readyForReading,
  11081. const int timeoutMsecs) const;
  11082. /** Reads bytes from the socket.
  11083. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  11084. maxBytesToRead bytes have been read, (or until an error occurs). If this
  11085. flag is false, the method will return as much data as is currently available
  11086. without blocking.
  11087. @returns the number of bytes read, or -1 if there was an error.
  11088. @see waitUntilReady
  11089. */
  11090. int read (void* destBuffer, const int maxBytesToRead,
  11091. const bool blockUntilSpecifiedAmountHasArrived);
  11092. /** Writes bytes to the socket from a buffer.
  11093. Note that this method will block unless you have checked the socket is ready
  11094. for writing before calling it (see the waitUntilReady() method).
  11095. @returns the number of bytes written, or -1 if there was an error.
  11096. */
  11097. int write (const void* sourceBuffer, const int numBytesToWrite);
  11098. /** This waits for incoming data to be sent, and returns a socket that can be used
  11099. to read it.
  11100. The object that gets returned is owned by the caller, and can't be used for
  11101. sending, but can be used to read the data.
  11102. */
  11103. DatagramSocket* waitForNextConnection() const;
  11104. juce_UseDebuggingNewOperator
  11105. private:
  11106. String hostName;
  11107. int volatile portNumber, handle;
  11108. bool connected, allowBroadcast;
  11109. void* serverAddress;
  11110. DatagramSocket (const String& hostname, const int portNumber, const int handle, const int localPortNumber);
  11111. DatagramSocket (const DatagramSocket&);
  11112. const DatagramSocket& operator= (const DatagramSocket&);
  11113. };
  11114. #endif // __JUCE_SOCKET_JUCEHEADER__
  11115. /********* End of inlined file: juce_Socket.h *********/
  11116. #endif
  11117. #ifndef __JUCE_URL_JUCEHEADER__
  11118. /********* Start of inlined file: juce_URL.h *********/
  11119. #ifndef __JUCE_URL_JUCEHEADER__
  11120. #define __JUCE_URL_JUCEHEADER__
  11121. /**
  11122. Represents a URL and has a bunch of useful functions to manipulate it.
  11123. This class can be used to launch URLs in browsers, and also to create
  11124. InputStreams that can read from remote http or ftp sources.
  11125. */
  11126. class JUCE_API URL
  11127. {
  11128. public:
  11129. /** Creates an empty URL. */
  11130. URL() throw();
  11131. /** Creates a URL from a string. */
  11132. URL (const String& url);
  11133. /** Creates a copy of another URL. */
  11134. URL (const URL& other);
  11135. /** Destructor. */
  11136. ~URL() throw();
  11137. /** Copies this URL from another one. */
  11138. const URL& operator= (const URL& other);
  11139. /** Returns a string version of the URL.
  11140. If includeGetParameters is true and any parameters have been set with the
  11141. withParameter() method, then the string will have these appended on the
  11142. end and url-encoded.
  11143. */
  11144. const String toString (const bool includeGetParameters) const;
  11145. /** True if it seems to be valid. */
  11146. bool isWellFormed() const;
  11147. /** Returns just the domain part of the URL.
  11148. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  11149. */
  11150. const String getDomain() const;
  11151. /** Returns the path part of the URL.
  11152. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  11153. */
  11154. const String getSubPath() const;
  11155. /** Returns the scheme of the URL.
  11156. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  11157. include the colon).
  11158. */
  11159. const String getScheme() const;
  11160. /** Returns a new version of this URL that uses a different sub-path.
  11161. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  11162. "bar", it'll return "http://www.xyz.com/bar?x=1".
  11163. */
  11164. const URL withNewSubPath (const String& newPath) const;
  11165. /** Returns a copy of this URL, with a GET parameter added to the end.
  11166. Any control characters in the value will be encoded.
  11167. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  11168. would produce a new url whose toString(true) method would return
  11169. "www.fish.com?amount=some+fish".
  11170. */
  11171. const URL withParameter (const String& parameterName,
  11172. const String& parameterValue) const;
  11173. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  11174. When performing a POST where one of your parameters is a binary file, this
  11175. lets you specify the file.
  11176. Note that the filename is stored, but the file itself won't actually be read
  11177. until this URL is later used to create a network input stream.
  11178. */
  11179. const URL withFileToUpload (const String& parameterName,
  11180. const File& fileToUpload,
  11181. const String& mimeType) const;
  11182. /** Returns a set of all the parameters encoded into the url.
  11183. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  11184. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  11185. The values returned will have been cleaned up to remove any escape characters.
  11186. @see getNamedParameter, withParameter
  11187. */
  11188. const StringPairArray& getParameters() const throw();
  11189. /** Returns the set of files that should be uploaded as part of a POST operation.
  11190. This is the set of files that were added to the URL with the withFileToUpload()
  11191. method.
  11192. */
  11193. const StringPairArray& getFilesToUpload() const throw();
  11194. /** Returns the set of mime types associated with each of the upload files.
  11195. */
  11196. const StringPairArray& getMimeTypesOfUploadFiles() const throw();
  11197. /** Returns a copy of this URL, with a block of data to send as the POST data.
  11198. If you're setting the POST data, be careful not to have any parameters set
  11199. as well, otherwise it'll all get thrown in together, and might not have the
  11200. desired effect.
  11201. If the URL already contains some POST data, this will replace it, rather
  11202. than being appended to it.
  11203. This data will only be used if you specify a post operation when you call
  11204. createInputStream().
  11205. */
  11206. const URL withPOSTData (const String& postData) const;
  11207. /** Returns the data that was set using withPOSTData().
  11208. */
  11209. const String getPostData() const throw() { return postData; }
  11210. /** Tries to launch the system's default browser to open the URL.
  11211. Returns true if this seems to have worked.
  11212. */
  11213. bool launchInDefaultBrowser() const;
  11214. /** Takes a guess as to whether a string might be a valid website address.
  11215. This isn't foolproof!
  11216. */
  11217. static bool isProbablyAWebsiteURL (const String& possibleURL);
  11218. /** Takes a guess as to whether a string might be a valid email address.
  11219. This isn't foolproof!
  11220. */
  11221. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  11222. /** This callback function can be used by the createInputStream() method.
  11223. It allows your app to receive progress updates during a lengthy POST operation. If you
  11224. want to continue the operation, this should return true, or false to abort.
  11225. */
  11226. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  11227. /** Attempts to open a stream that can read from this URL.
  11228. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  11229. the paramters, otherwise it'll encode them into the
  11230. URL and do a 'GET'.
  11231. @param progressCallback if this is non-zero, it lets you supply a callback function
  11232. to keep track of the operation's progress. This can be useful
  11233. for lengthy POST operations, so that you can provide user feedback.
  11234. @param progressCallbackContext if a callback is specified, this value will be passed to
  11235. the function
  11236. @param extraHeaders if not empty, this string is appended onto the headers that
  11237. are used for the request. It must therefore be a valid set of HTML
  11238. header directives, separated by newlines.
  11239. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  11240. a negative number, it will be infinite. Otherwise it specifies a
  11241. time in milliseconds.
  11242. */
  11243. InputStream* createInputStream (const bool usePostCommand,
  11244. OpenStreamProgressCallback* const progressCallback = 0,
  11245. void* const progressCallbackContext = 0,
  11246. const String& extraHeaders = String::empty,
  11247. const int connectionTimeOutMs = 0) const;
  11248. /** Tries to download the entire contents of this URL into a binary data block.
  11249. If it succeeds, this will return true and append the data it read onto the end
  11250. of the memory block.
  11251. @param destData the memory block to append the new data to
  11252. @param usePostCommand whether to use a POST command to get the data (uses
  11253. a GET command if this is false)
  11254. @see readEntireTextStream, readEntireXmlStream
  11255. */
  11256. bool readEntireBinaryStream (MemoryBlock& destData,
  11257. const bool usePostCommand = false) const;
  11258. /** Tries to download the entire contents of this URL as a string.
  11259. If it fails, this will return an empty string, otherwise it will return the
  11260. contents of the downloaded file. If you need to distinguish between a read
  11261. operation that fails and one that returns an empty string, you'll need to use
  11262. a different method, such as readEntireBinaryStream().
  11263. @param usePostCommand whether to use a POST command to get the data (uses
  11264. a GET command if this is false)
  11265. @see readEntireBinaryStream, readEntireXmlStream
  11266. */
  11267. const String readEntireTextStream (const bool usePostCommand = false) const;
  11268. /** Tries to download the entire contents of this URL and parse it as XML.
  11269. If it fails, or if the text that it reads can't be parsed as XML, this will
  11270. return 0.
  11271. When it returns a valid XmlElement object, the caller is responsibile for deleting
  11272. this object when no longer needed.
  11273. @param usePostCommand whether to use a POST command to get the data (uses
  11274. a GET command if this is false)
  11275. @see readEntireBinaryStream, readEntireTextStream
  11276. */
  11277. XmlElement* readEntireXmlStream (const bool usePostCommand = false) const;
  11278. /** Adds escape sequences to a string to encode any characters that aren't
  11279. legal in a URL.
  11280. E.g. any spaces will be replaced with "%20".
  11281. This is the opposite of removeEscapeChars().
  11282. If isParameter is true, it means that the string is going to be used
  11283. as a parameter, so it also encodes '$' and ',' (which would otherwise
  11284. be legal in a URL.
  11285. @see removeEscapeChars
  11286. */
  11287. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  11288. const bool isParameter);
  11289. /** Replaces any escape character sequences in a string with their original
  11290. character codes.
  11291. E.g. any instances of "%20" will be replaced by a space.
  11292. This is the opposite of addEscapeChars().
  11293. @see addEscapeChars
  11294. */
  11295. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  11296. juce_UseDebuggingNewOperator
  11297. private:
  11298. String url, postData;
  11299. StringPairArray parameters, filesToUpload, mimeTypes;
  11300. };
  11301. #endif // __JUCE_URL_JUCEHEADER__
  11302. /********* End of inlined file: juce_URL.h *********/
  11303. #endif
  11304. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11305. /********* Start of inlined file: juce_BufferedInputStream.h *********/
  11306. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11307. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11308. /** Wraps another input stream, and reads from it using an intermediate buffer
  11309. If you're using an input stream such as a file input stream, and making lots of
  11310. small read accesses to it, it's probably sensible to wrap it in one of these,
  11311. so that the source stream gets accessed in larger chunk sizes, meaning less
  11312. work for the underlying stream.
  11313. */
  11314. class JUCE_API BufferedInputStream : public InputStream
  11315. {
  11316. public:
  11317. /** Creates a BufferedInputStream from an input source.
  11318. @param sourceStream the source stream to read from
  11319. @param bufferSize the size of reservoir to use to buffer the source
  11320. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  11321. deleted by this object when it is itself deleted.
  11322. */
  11323. BufferedInputStream (InputStream* const sourceStream,
  11324. const int bufferSize,
  11325. const bool deleteSourceWhenDestroyed) throw();
  11326. /** Destructor.
  11327. This may also delete the source stream, if that option was chosen when the
  11328. buffered stream was created.
  11329. */
  11330. ~BufferedInputStream() throw();
  11331. int64 getTotalLength();
  11332. int64 getPosition();
  11333. bool setPosition (int64 newPosition);
  11334. int read (void* destBuffer, int maxBytesToRead);
  11335. const String readString();
  11336. bool isExhausted();
  11337. juce_UseDebuggingNewOperator
  11338. private:
  11339. InputStream* const source;
  11340. const bool deleteSourceWhenDestroyed;
  11341. int bufferSize;
  11342. int64 position, lastReadPos, bufferStart, bufferOverlap;
  11343. HeapBlock <char> buffer;
  11344. void ensureBuffered();
  11345. BufferedInputStream (const BufferedInputStream&);
  11346. const BufferedInputStream& operator= (const BufferedInputStream&);
  11347. };
  11348. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  11349. /********* End of inlined file: juce_BufferedInputStream.h *********/
  11350. #endif
  11351. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11352. /********* Start of inlined file: juce_FileInputSource.h *********/
  11353. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11354. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11355. /**
  11356. A type of InputSource that represents a normal file.
  11357. @see InputSource
  11358. */
  11359. class JUCE_API FileInputSource : public InputSource
  11360. {
  11361. public:
  11362. FileInputSource (const File& file) throw();
  11363. ~FileInputSource();
  11364. InputStream* createInputStream();
  11365. InputStream* createInputStreamFor (const String& relatedItemPath);
  11366. int64 hashCode() const;
  11367. juce_UseDebuggingNewOperator
  11368. private:
  11369. const File file;
  11370. FileInputSource (const FileInputSource&);
  11371. const FileInputSource& operator= (const FileInputSource&);
  11372. };
  11373. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  11374. /********* End of inlined file: juce_FileInputSource.h *********/
  11375. #endif
  11376. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11377. /********* Start of inlined file: juce_GZIPCompressorOutputStream.h *********/
  11378. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11379. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11380. /**
  11381. A stream which uses zlib to compress the data written into it.
  11382. @see GZIPDecompressorInputStream
  11383. */
  11384. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  11385. {
  11386. public:
  11387. /** Creates a compression stream.
  11388. @param destStream the stream into which the compressed data should
  11389. be written
  11390. @param compressionLevel how much to compress the data, between 1 and 9, where
  11391. 1 is the fastest/lowest compression, and 9 is the
  11392. slowest/highest compression. Any value outside this range
  11393. indicates that a default compression level should be used.
  11394. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  11395. this stream is destroyed
  11396. @param noWrap this is used internally by the ZipFile class
  11397. and should be ignored by user applications
  11398. */
  11399. GZIPCompressorOutputStream (OutputStream* const destStream,
  11400. int compressionLevel = 0,
  11401. const bool deleteDestStreamWhenDestroyed = false,
  11402. const bool noWrap = false);
  11403. /** Destructor. */
  11404. ~GZIPCompressorOutputStream();
  11405. void flush();
  11406. int64 getPosition();
  11407. bool setPosition (int64 newPosition);
  11408. bool write (const void* destBuffer, int howMany);
  11409. juce_UseDebuggingNewOperator
  11410. private:
  11411. OutputStream* const destStream;
  11412. const bool deleteDestStream;
  11413. HeapBlock <uint8> buffer;
  11414. void* helper;
  11415. bool doNextBlock();
  11416. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  11417. const GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  11418. };
  11419. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  11420. /********* End of inlined file: juce_GZIPCompressorOutputStream.h *********/
  11421. #endif
  11422. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11423. /********* Start of inlined file: juce_GZIPDecompressorInputStream.h *********/
  11424. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11425. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11426. /**
  11427. This stream will decompress a source-stream using zlib.
  11428. Tip: if you're reading lots of small items from one of these streams, you
  11429. can increase the performance enormously by passing it through a
  11430. BufferedInputStream, so that it has to read larger blocks less often.
  11431. @see GZIPCompressorOutputStream
  11432. */
  11433. class JUCE_API GZIPDecompressorInputStream : public InputStream
  11434. {
  11435. public:
  11436. /** Creates a decompressor stream.
  11437. @param sourceStream the stream to read from
  11438. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  11439. when this object is destroyed
  11440. @param noWrap this is used internally by the ZipFile class
  11441. and should be ignored by user applications
  11442. @param uncompressedStreamLength if the creator knows the length that the
  11443. uncompressed stream will be, then it can supply this
  11444. value, which will be returned by getTotalLength()
  11445. */
  11446. GZIPDecompressorInputStream (InputStream* const sourceStream,
  11447. const bool deleteSourceWhenDestroyed,
  11448. const bool noWrap = false,
  11449. const int64 uncompressedStreamLength = -1);
  11450. /** Destructor. */
  11451. ~GZIPDecompressorInputStream();
  11452. int64 getPosition();
  11453. bool setPosition (int64 pos);
  11454. int64 getTotalLength();
  11455. bool isExhausted();
  11456. int read (void* destBuffer, int maxBytesToRead);
  11457. juce_UseDebuggingNewOperator
  11458. private:
  11459. InputStream* const sourceStream;
  11460. const int64 uncompressedStreamLength;
  11461. const bool deleteSourceWhenDestroyed, noWrap;
  11462. bool isEof;
  11463. int activeBufferSize;
  11464. int64 originalSourcePos, currentPos;
  11465. HeapBlock <uint8> buffer;
  11466. void* helper;
  11467. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  11468. const GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  11469. };
  11470. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  11471. /********* End of inlined file: juce_GZIPDecompressorInputStream.h *********/
  11472. #endif
  11473. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  11474. #endif
  11475. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  11476. #endif
  11477. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11478. /********* Start of inlined file: juce_MemoryInputStream.h *********/
  11479. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11480. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11481. /**
  11482. Allows a block of data and to be accessed as a stream.
  11483. This can either be used to refer to a shared block of memory, or can make its
  11484. own internal copy of the data when the MemoryInputStream is created.
  11485. */
  11486. class JUCE_API MemoryInputStream : public InputStream
  11487. {
  11488. public:
  11489. /** Creates a MemoryInputStream.
  11490. @param sourceData the block of data to use as the stream's source
  11491. @param sourceDataSize the number of bytes in the source data block
  11492. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  11493. the source data, so this data shouldn't be changed
  11494. for the lifetime of the stream; if this parameter is
  11495. true, the stream will make its own copy of the
  11496. data and use that.
  11497. */
  11498. MemoryInputStream (const void* const sourceData,
  11499. const int sourceDataSize,
  11500. const bool keepInternalCopyOfData) throw();
  11501. /** Destructor. */
  11502. ~MemoryInputStream() throw();
  11503. int64 getPosition();
  11504. bool setPosition (int64 pos);
  11505. int64 getTotalLength();
  11506. bool isExhausted();
  11507. int read (void* destBuffer, int maxBytesToRead);
  11508. juce_UseDebuggingNewOperator
  11509. private:
  11510. const char* data;
  11511. int dataSize, position;
  11512. MemoryBlock internalCopy;
  11513. };
  11514. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  11515. /********* End of inlined file: juce_MemoryInputStream.h *********/
  11516. #endif
  11517. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11518. /********* Start of inlined file: juce_MemoryOutputStream.h *********/
  11519. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11520. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11521. /** Writes data to an internal memory buffer, which grows as required.
  11522. The data that was written into the stream can then be accessed later as
  11523. a contiguous block of memory.
  11524. */
  11525. class JUCE_API MemoryOutputStream : public OutputStream
  11526. {
  11527. public:
  11528. /** Creates a memory stream ready for writing into.
  11529. @param initialSize the intial amount of space to allocate for writing into
  11530. @param granularity the increments by which the internal storage will be increased
  11531. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  11532. place that the data gets stored. If it's zero, the stream
  11533. will allocate its own storage internally, which you can
  11534. access using getData() and getDataSize()
  11535. */
  11536. MemoryOutputStream (const int initialSize = 256,
  11537. const int granularity = 256,
  11538. MemoryBlock* const memoryBlockToWriteTo = 0) throw();
  11539. /** Destructor.
  11540. This will free any data that was written to it.
  11541. */
  11542. ~MemoryOutputStream() throw();
  11543. /** Returns a pointer to the data that has been written to the stream.
  11544. @see getDataSize
  11545. */
  11546. const char* getData() throw();
  11547. /** Returns the number of bytes of data that have been written to the stream.
  11548. @see getData
  11549. */
  11550. int getDataSize() const throw();
  11551. /** Resets the stream, clearing any data that has been written to it so far. */
  11552. void reset() throw();
  11553. void flush();
  11554. bool write (const void* buffer, int howMany);
  11555. int64 getPosition();
  11556. bool setPosition (int64 newPosition);
  11557. juce_UseDebuggingNewOperator
  11558. private:
  11559. MemoryBlock* data;
  11560. int position, size, blockSize;
  11561. bool ownsMemoryBlock;
  11562. };
  11563. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  11564. /********* End of inlined file: juce_MemoryOutputStream.h *********/
  11565. #endif
  11566. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  11567. #endif
  11568. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11569. /********* Start of inlined file: juce_SubregionStream.h *********/
  11570. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11571. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11572. /** Wraps another input stream, and reads from a specific part of it.
  11573. This lets you take a subsection of a stream and present it as an entire
  11574. stream in its own right.
  11575. */
  11576. class JUCE_API SubregionStream : public InputStream
  11577. {
  11578. public:
  11579. /** Creates a SubregionStream from an input source.
  11580. @param sourceStream the source stream to read from
  11581. @param startPositionInSourceStream this is the position in the source stream that
  11582. corresponds to position 0 in this stream
  11583. @param lengthOfSourceStream this specifies the maximum number of bytes
  11584. from the source stream that will be passed through
  11585. by this stream. When the position of this stream
  11586. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  11587. If the length passed in here is greater than the length
  11588. of the source stream (as returned by getTotalLength()),
  11589. then the smaller value will be used.
  11590. Passing a negative value for this parameter means it
  11591. will keep reading until the source's end-of-stream.
  11592. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  11593. deleted by this object when it is itself deleted.
  11594. */
  11595. SubregionStream (InputStream* const sourceStream,
  11596. const int64 startPositionInSourceStream,
  11597. const int64 lengthOfSourceStream,
  11598. const bool deleteSourceWhenDestroyed) throw();
  11599. /** Destructor.
  11600. This may also delete the source stream, if that option was chosen when the
  11601. buffered stream was created.
  11602. */
  11603. ~SubregionStream() throw();
  11604. int64 getTotalLength();
  11605. int64 getPosition();
  11606. bool setPosition (int64 newPosition);
  11607. int read (void* destBuffer, int maxBytesToRead);
  11608. bool isExhausted();
  11609. juce_UseDebuggingNewOperator
  11610. private:
  11611. InputStream* const source;
  11612. const bool deleteSourceWhenDestroyed;
  11613. const int64 startPositionInSourceStream, lengthOfSourceStream;
  11614. SubregionStream (const SubregionStream&);
  11615. const SubregionStream& operator= (const SubregionStream&);
  11616. };
  11617. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  11618. /********* End of inlined file: juce_SubregionStream.h *********/
  11619. #endif
  11620. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  11621. #endif
  11622. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11623. /********* Start of inlined file: juce_LocalisedStrings.h *********/
  11624. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11625. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11626. /** Used in the same way as the T(text) macro, this will attempt to translate a
  11627. string into a localised version using the LocalisedStrings class.
  11628. @see LocalisedStrings
  11629. */
  11630. #define TRANS(stringLiteral) \
  11631. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  11632. /**
  11633. Used to convert strings to localised foreign-language versions.
  11634. This is basically a look-up table of strings and their translated equivalents.
  11635. It can be loaded from a text file, so that you can supply a set of localised
  11636. versions of strings that you use in your app.
  11637. To use it in your code, simply call the translate() method on each string that
  11638. might have foreign versions, and if none is found, the method will just return
  11639. the original string.
  11640. The translation file should start with some lines specifying a description of
  11641. the language it contains, and also a list of ISO country codes where it might
  11642. be appropriate to use the file. After that, each line of the file should contain
  11643. a pair of quoted strings with an '=' sign.
  11644. E.g. for a french translation, the file might be:
  11645. @code
  11646. language: French
  11647. countries: fr be mc ch lu
  11648. "hello" = "bonjour"
  11649. "goodbye" = "au revoir"
  11650. @endcode
  11651. If the strings need to contain a quote character, they can use '\"' instead, and
  11652. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  11653. (you can use this to add comments).
  11654. Note that this is a singleton class, so don't create or destroy the object directly.
  11655. There's also a TRANS(text) macro defined to make it easy to use the this.
  11656. E.g. @code
  11657. printSomething (TRANS("hello"));
  11658. @endcode
  11659. This macro is used in the Juce classes themselves, so your application has a chance to
  11660. intercept and translate any internal Juce text strings that might be shown. (You can easily
  11661. get a list of all the messages by searching for the TRANS() macro in the Juce source
  11662. code).
  11663. */
  11664. class JUCE_API LocalisedStrings
  11665. {
  11666. public:
  11667. /** Creates a set of translations from the text of a translation file.
  11668. When you create one of these, you can call setCurrentMappings() to make it
  11669. the set of mappings that the system's using.
  11670. */
  11671. LocalisedStrings (const String& fileContents) throw();
  11672. /** Creates a set of translations from a file.
  11673. When you create one of these, you can call setCurrentMappings() to make it
  11674. the set of mappings that the system's using.
  11675. */
  11676. LocalisedStrings (const File& fileToLoad) throw();
  11677. /** Destructor. */
  11678. ~LocalisedStrings() throw();
  11679. /** Selects the current set of mappings to be used by the system.
  11680. The object you pass in will be automatically deleted when no longer needed, so
  11681. don't keep a pointer to it. You can also pass in zero to remove the current
  11682. mappings.
  11683. See also the TRANS() macro, which uses the current set to do its translation.
  11684. @see translateWithCurrentMappings
  11685. */
  11686. static void setCurrentMappings (LocalisedStrings* newTranslations) throw();
  11687. /** Returns the currently selected set of mappings.
  11688. This is the object that was last passed to setCurrentMappings(). It may
  11689. be 0 if none has been created.
  11690. */
  11691. static LocalisedStrings* getCurrentMappings() throw();
  11692. /** Tries to translate a string using the currently selected set of mappings.
  11693. If no mapping has been set, or if the mapping doesn't contain a translation
  11694. for the string, this will just return the original string.
  11695. See also the TRANS() macro, which uses this method to do its translation.
  11696. @see setCurrentMappings, getCurrentMappings
  11697. */
  11698. static const String translateWithCurrentMappings (const String& text) throw();
  11699. /** Tries to translate a string using the currently selected set of mappings.
  11700. If no mapping has been set, or if the mapping doesn't contain a translation
  11701. for the string, this will just return the original string.
  11702. See also the TRANS() macro, which uses this method to do its translation.
  11703. @see setCurrentMappings, getCurrentMappings
  11704. */
  11705. static const String translateWithCurrentMappings (const char* text) throw();
  11706. /** Attempts to look up a string and return its localised version.
  11707. If the string isn't found in the list, the original string will be returned.
  11708. */
  11709. const String translate (const String& text) const throw();
  11710. /** Returns the name of the language specified in the translation file.
  11711. This is specified in the file using a line starting with "language:", e.g.
  11712. @code
  11713. language: german
  11714. @endcode
  11715. */
  11716. const String getLanguageName() const throw() { return languageName; }
  11717. /** Returns the list of suitable country codes listed in the translation file.
  11718. These is specified in the file using a line starting with "countries:", e.g.
  11719. @code
  11720. countries: fr be mc ch lu
  11721. @endcode
  11722. The country codes are supposed to be 2-character ISO complient codes.
  11723. */
  11724. const StringArray getCountryCodes() const throw() { return countryCodes; }
  11725. /** Indicates whether to use a case-insensitive search when looking up a string.
  11726. This defaults to true.
  11727. */
  11728. void setIgnoresCase (const bool shouldIgnoreCase) throw();
  11729. juce_UseDebuggingNewOperator
  11730. private:
  11731. String languageName;
  11732. StringArray countryCodes;
  11733. StringPairArray translations;
  11734. void loadFromText (const String& fileContents) throw();
  11735. };
  11736. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  11737. /********* End of inlined file: juce_LocalisedStrings.h *********/
  11738. #endif
  11739. #ifndef __JUCE_STRING_JUCEHEADER__
  11740. #endif
  11741. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  11742. #endif
  11743. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  11744. #endif
  11745. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  11746. /********* Start of inlined file: juce_XmlDocument.h *********/
  11747. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  11748. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  11749. /**
  11750. Parses a text-based XML document and creates an XmlElement object from it.
  11751. The parser will parse DTDs to load external entities but won't
  11752. check the document for validity against the DTD.
  11753. e.g.
  11754. @code
  11755. XmlDocument myDocument (File ("myfile.xml"));
  11756. XmlElement* mainElement = myDocument.getDocumentElement();
  11757. if (mainElement == 0)
  11758. {
  11759. String error = myDocument.getLastParseError();
  11760. }
  11761. else
  11762. {
  11763. ..use the element
  11764. }
  11765. @endcode
  11766. @see XmlElement
  11767. */
  11768. class JUCE_API XmlDocument
  11769. {
  11770. public:
  11771. /** Creates an XmlDocument from the xml text.
  11772. The text doesn't actually get parsed until the getDocumentElement() method is
  11773. called.
  11774. */
  11775. XmlDocument (const String& documentText) throw();
  11776. /** Creates an XmlDocument from a file.
  11777. The text doesn't actually get parsed until the getDocumentElement() method is
  11778. called.
  11779. */
  11780. XmlDocument (const File& file);
  11781. /** Destructor. */
  11782. ~XmlDocument() throw();
  11783. /** Creates an XmlElement object to represent the main document node.
  11784. This method will do the actual parsing of the text, and if there's a
  11785. parse error, it may returns 0 (and you can find out the error using
  11786. the getLastParseError() method).
  11787. @param onlyReadOuterDocumentElement if true, the parser will only read the
  11788. first section of the file, and will only
  11789. return the outer document element - this
  11790. allows quick checking of large files to
  11791. see if they contain the correct type of
  11792. tag, without having to parse the entire file
  11793. @returns a new XmlElement which the caller will need to delete, or null if
  11794. there was an error.
  11795. @see getLastParseError
  11796. */
  11797. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  11798. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  11799. @returns the error, or an empty string if there was no error.
  11800. */
  11801. const String& getLastParseError() const throw();
  11802. /** Sets an input source object to use for parsing documents that reference external entities.
  11803. If the document has been created from a file, this probably won't be needed, but
  11804. if you're parsing some text and there might be a DTD that references external
  11805. files, you may need to create a custom input source that can retrieve the
  11806. other files it needs.
  11807. The object that is passed-in will be deleted automatically when no longer needed.
  11808. @see InputSource
  11809. */
  11810. void setInputSource (InputSource* const newSource) throw();
  11811. /** Sets a flag to change the treatment of empty text elements.
  11812. If this is true (the default state), then any text elements that contain only
  11813. whitespace characters will be ingored during parsing. If you need to catch
  11814. whitespace-only text, then you should set this to false before calling the
  11815. getDocumentElement() method.
  11816. */
  11817. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  11818. juce_UseDebuggingNewOperator
  11819. private:
  11820. String originalText;
  11821. const tchar* input;
  11822. bool outOfData, errorOccurred;
  11823. bool identifierLookupTable [128];
  11824. String lastError, dtdText;
  11825. StringArray tokenisedDTD;
  11826. bool needToLoadDTD, ignoreEmptyTextElements;
  11827. ScopedPointer <InputSource> inputSource;
  11828. void setLastError (const String& desc, const bool carryOn) throw();
  11829. void skipHeader() throw();
  11830. void skipNextWhiteSpace() throw();
  11831. tchar readNextChar() throw();
  11832. XmlElement* readNextElement (const bool alsoParseSubElements) throw();
  11833. void readChildElements (XmlElement* parent) throw();
  11834. int findNextTokenLength() throw();
  11835. void readQuotedString (String& result) throw();
  11836. void readEntity (String& result) throw();
  11837. const String getFileContents (const String& filename) const;
  11838. const String expandEntity (const String& entity);
  11839. const String expandExternalEntity (const String& entity);
  11840. const String getParameterEntity (const String& entity);
  11841. };
  11842. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  11843. /********* End of inlined file: juce_XmlDocument.h *********/
  11844. #endif
  11845. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  11846. #endif
  11847. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  11848. #endif
  11849. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11850. /********* Start of inlined file: juce_InterProcessLock.h *********/
  11851. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11852. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11853. /**
  11854. Acts as a critical section which processes can use to block each other.
  11855. @see CriticalSection
  11856. */
  11857. class JUCE_API InterProcessLock
  11858. {
  11859. public:
  11860. /** Creates a lock object.
  11861. @param name a name that processes will use to identify this lock object
  11862. */
  11863. InterProcessLock (const String& name) throw();
  11864. /** Destructor.
  11865. This will also release the lock if it's currently held by this process.
  11866. */
  11867. ~InterProcessLock() throw();
  11868. /** Attempts to lock the critical section.
  11869. @param timeOutMillisecs how many milliseconds to wait if the lock
  11870. is already held by another process - a value of
  11871. 0 will return immediately, negative values will wait
  11872. forever
  11873. @returns true if the lock could be gained within the timeout period, or
  11874. false if the timeout expired.
  11875. */
  11876. bool enter (int timeOutMillisecs = -1) throw();
  11877. /** Releases the lock if it's currently held by this process.
  11878. */
  11879. void exit() throw();
  11880. juce_UseDebuggingNewOperator
  11881. private:
  11882. void* internal;
  11883. String name;
  11884. int reentrancyLevel;
  11885. InterProcessLock (const InterProcessLock&);
  11886. const InterProcessLock& operator= (const InterProcessLock&);
  11887. };
  11888. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  11889. /********* End of inlined file: juce_InterProcessLock.h *********/
  11890. #endif
  11891. #ifndef __JUCE_PROCESS_JUCEHEADER__
  11892. /********* Start of inlined file: juce_Process.h *********/
  11893. #ifndef __JUCE_PROCESS_JUCEHEADER__
  11894. #define __JUCE_PROCESS_JUCEHEADER__
  11895. /** Represents the current executable's process.
  11896. This contains methods for controlling the current application at the
  11897. process-level.
  11898. @see Thread, JUCEApplication
  11899. */
  11900. class JUCE_API Process
  11901. {
  11902. public:
  11903. enum ProcessPriority
  11904. {
  11905. LowPriority = 0,
  11906. NormalPriority = 1,
  11907. HighPriority = 2,
  11908. RealtimePriority = 3
  11909. };
  11910. /** Changes the current process's priority.
  11911. @param priority the process priority, where
  11912. 0=low, 1=normal, 2=high, 3=realtime
  11913. */
  11914. static void setPriority (const ProcessPriority priority);
  11915. /** Kills the current process immediately.
  11916. This is an emergency process terminator that kills the application
  11917. immediately - it's intended only for use only when something goes
  11918. horribly wrong.
  11919. @see JUCEApplication::quit
  11920. */
  11921. static void terminate();
  11922. /** Returns true if this application process is the one that the user is
  11923. currently using.
  11924. */
  11925. static bool isForegroundProcess() throw();
  11926. /** Raises the current process's privilege level.
  11927. Does nothing if this isn't supported by the current OS, or if process
  11928. privilege level is fixed.
  11929. */
  11930. static void raisePrivilege();
  11931. /** Lowers the current process's privilege level.
  11932. Does nothing if this isn't supported by the current OS, or if process
  11933. privilege level is fixed.
  11934. */
  11935. static void lowerPrivilege();
  11936. /** Returns true if this process is being hosted by a debugger.
  11937. */
  11938. static bool JUCE_CALLTYPE isRunningUnderDebugger() throw();
  11939. };
  11940. #endif // __JUCE_PROCESS_JUCEHEADER__
  11941. /********* End of inlined file: juce_Process.h *********/
  11942. #endif
  11943. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  11944. /********* Start of inlined file: juce_ReadWriteLock.h *********/
  11945. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  11946. #define __JUCE_READWRITELOCK_JUCEHEADER__
  11947. /********* Start of inlined file: juce_WaitableEvent.h *********/
  11948. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  11949. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  11950. /**
  11951. Allows threads to wait for events triggered by other threads.
  11952. A thread can call wait() on a WaitableObject, and this will suspend the
  11953. calling thread until another thread wakes it up by calling the signal()
  11954. method.
  11955. */
  11956. class JUCE_API WaitableEvent
  11957. {
  11958. public:
  11959. /** Creates a WaitableEvent object. */
  11960. WaitableEvent() throw();
  11961. /** Destructor.
  11962. If other threads are waiting on this object when it gets deleted, this
  11963. can cause nasty errors, so be careful!
  11964. */
  11965. ~WaitableEvent() throw();
  11966. /** Suspends the calling thread until the event has been signalled.
  11967. This will wait until the object's signal() method is called by another thread,
  11968. or until the timeout expires.
  11969. After the event has been signalled, this method will return true and reset
  11970. the event.
  11971. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  11972. value will cause it to wait forever.
  11973. @returns true if the object has been signalled, false if the timeout expires first.
  11974. @see signal, reset
  11975. */
  11976. bool wait (const int timeOutMilliseconds = -1) const throw();
  11977. /** Wakes up any threads that are currently waiting on this object.
  11978. If signal() is called when nothing is waiting, the next thread to call wait()
  11979. will return immediately and reset the signal.
  11980. @see wait, reset
  11981. */
  11982. void signal() const throw();
  11983. /** Resets the event to an unsignalled state.
  11984. If it's not already signalled, this does nothing.
  11985. */
  11986. void reset() const throw();
  11987. juce_UseDebuggingNewOperator
  11988. private:
  11989. void* internal;
  11990. WaitableEvent (const WaitableEvent&);
  11991. const WaitableEvent& operator= (const WaitableEvent&);
  11992. };
  11993. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  11994. /********* End of inlined file: juce_WaitableEvent.h *********/
  11995. /********* Start of inlined file: juce_Thread.h *********/
  11996. #ifndef __JUCE_THREAD_JUCEHEADER__
  11997. #define __JUCE_THREAD_JUCEHEADER__
  11998. /**
  11999. Encapsulates a thread.
  12000. Subclasses derive from Thread and implement the run() method, in which they
  12001. do their business. The thread can then be started with the startThread() method
  12002. and controlled with various other methods.
  12003. This class also contains some thread-related static methods, such
  12004. as sleep(), yield(), getCurrentThreadId() etc.
  12005. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  12006. MessageManagerLock
  12007. */
  12008. class JUCE_API Thread
  12009. {
  12010. public:
  12011. /**
  12012. Creates a thread.
  12013. When first created, the thread is not running. Use the startThread()
  12014. method to start it.
  12015. */
  12016. Thread (const String& threadName);
  12017. /** Destructor.
  12018. Deleting a Thread object that is running will only give the thread a
  12019. brief opportunity to stop itself cleanly, so it's recommended that you
  12020. should always call stopThread() with a decent timeout before deleting,
  12021. to avoid the thread being forcibly killed (which is a Bad Thing).
  12022. */
  12023. virtual ~Thread();
  12024. /** Must be implemented to perform the thread's actual code.
  12025. Remember that the thread must regularly check the threadShouldExit()
  12026. method whilst running, and if this returns true it should return from
  12027. the run() method as soon as possible to avoid being forcibly killed.
  12028. @see threadShouldExit, startThread
  12029. */
  12030. virtual void run() = 0;
  12031. // Thread control functions..
  12032. /** Starts the thread running.
  12033. This will start the thread's run() method.
  12034. (if it's already started, startThread() won't do anything).
  12035. @see stopThread
  12036. */
  12037. void startThread() throw();
  12038. /** Starts the thread with a given priority.
  12039. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  12040. If the thread is already running, its priority will be changed.
  12041. @see startThread, setPriority
  12042. */
  12043. void startThread (const int priority) throw();
  12044. /** Attempts to stop the thread running.
  12045. This method will cause the threadShouldExit() method to return true
  12046. and call notify() in case the thread is currently waiting.
  12047. Hopefully the thread will then respond to this by exiting cleanly, and
  12048. the stopThread method will wait for a given time-period for this to
  12049. happen.
  12050. If the thread is stuck and fails to respond after the time-out, it gets
  12051. forcibly killed, which is a very bad thing to happen, as it could still
  12052. be holding locks, etc. which are needed by other parts of your program.
  12053. @param timeOutMilliseconds The number of milliseconds to wait for the
  12054. thread to finish before killing it by force. A negative
  12055. value in here will wait forever.
  12056. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  12057. */
  12058. void stopThread (const int timeOutMilliseconds) throw();
  12059. /** Returns true if the thread is currently active */
  12060. bool isThreadRunning() const throw();
  12061. /** Sets a flag to tell the thread it should stop.
  12062. Calling this means that the threadShouldExit() method will then return true.
  12063. The thread should be regularly checking this to see whether it should exit.
  12064. @see threadShouldExit
  12065. @see waitForThreadToExit
  12066. */
  12067. void signalThreadShouldExit() throw();
  12068. /** Checks whether the thread has been told to stop running.
  12069. Threads need to check this regularly, and if it returns true, they should
  12070. return from their run() method at the first possible opportunity.
  12071. @see signalThreadShouldExit
  12072. */
  12073. inline bool threadShouldExit() const throw() { return threadShouldExit_; }
  12074. /** Waits for the thread to stop.
  12075. This will waits until isThreadRunning() is false or until a timeout expires.
  12076. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  12077. is less than zero, it will wait forever.
  12078. @returns true if the thread exits, or false if the timeout expires first.
  12079. */
  12080. bool waitForThreadToExit (const int timeOutMilliseconds) const throw();
  12081. /** Changes the thread's priority.
  12082. May return false if for some reason the priority can't be changed.
  12083. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  12084. of 5 is normal.
  12085. */
  12086. bool setPriority (const int priority) throw();
  12087. /** Changes the priority of the caller thread.
  12088. Similar to setPriority(), but this static method acts on the caller thread.
  12089. May return false if for some reason the priority can't be changed.
  12090. @see setPriority
  12091. */
  12092. static bool setCurrentThreadPriority (const int priority) throw();
  12093. /** Sets the affinity mask for the thread.
  12094. This will only have an effect next time the thread is started - i.e. if the
  12095. thread is already running when called, it'll have no effect.
  12096. @see setCurrentThreadAffinityMask
  12097. */
  12098. void setAffinityMask (const uint32 affinityMask) throw();
  12099. /** Changes the affinity mask for the caller thread.
  12100. This will change the affinity mask for the thread that calls this static method.
  12101. @see setAffinityMask
  12102. */
  12103. static void setCurrentThreadAffinityMask (const uint32 affinityMask) throw();
  12104. // this can be called from any thread that needs to pause..
  12105. static void JUCE_CALLTYPE sleep (int milliseconds) throw();
  12106. /** Yields the calling thread's current time-slot. */
  12107. static void JUCE_CALLTYPE yield() throw();
  12108. /** Makes the thread wait for a notification.
  12109. This puts the thread to sleep until either the timeout period expires, or
  12110. another thread calls the notify() method to wake it up.
  12111. @returns true if the event has been signalled, false if the timeout expires.
  12112. */
  12113. bool wait (const int timeOutMilliseconds) const throw();
  12114. /** Wakes up the thread.
  12115. If the thread has called the wait() method, this will wake it up.
  12116. @see wait
  12117. */
  12118. void notify() const throw();
  12119. /** A value type used for thread IDs.
  12120. @see getCurrentThreadId(), getThreadId()
  12121. */
  12122. typedef void* ThreadID;
  12123. /** Returns an id that identifies the caller thread.
  12124. To find the ID of a particular thread object, use getThreadId().
  12125. @returns a unique identifier that identifies the calling thread.
  12126. @see getThreadId
  12127. */
  12128. static ThreadID getCurrentThreadId() throw();
  12129. /** Finds the thread object that is currently running.
  12130. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  12131. object associated with them, so this will return 0.
  12132. */
  12133. static Thread* getCurrentThread() throw();
  12134. /** Returns the ID of this thread.
  12135. That means the ID of this thread object - not of the thread that's calling the method.
  12136. This can change when the thread is started and stopped, and will be invalid if the
  12137. thread's not actually running.
  12138. @see getCurrentThreadId
  12139. */
  12140. ThreadID getThreadId() const throw();
  12141. /** Returns the name of the thread.
  12142. This is the name that gets set in the constructor.
  12143. */
  12144. const String getThreadName() const throw() { return threadName_; }
  12145. /** Returns the number of currently-running threads.
  12146. @returns the number of Thread objects known to be currently running.
  12147. @see stopAllThreads
  12148. */
  12149. static int getNumRunningThreads() throw();
  12150. /** Tries to stop all currently-running threads.
  12151. This will attempt to stop all the threads known to be running at the moment.
  12152. */
  12153. static void stopAllThreads (const int timeoutInMillisecs) throw();
  12154. juce_UseDebuggingNewOperator
  12155. private:
  12156. const String threadName_;
  12157. void* volatile threadHandle_;
  12158. CriticalSection startStopLock;
  12159. WaitableEvent startSuspensionEvent_, defaultEvent_;
  12160. int threadPriority_;
  12161. ThreadID threadId_;
  12162. uint32 affinityMask_;
  12163. bool volatile threadShouldExit_;
  12164. friend void JUCE_API juce_threadEntryPoint (void*);
  12165. static void threadEntryPoint (Thread* thread) throw();
  12166. Thread (const Thread&);
  12167. const Thread& operator= (const Thread&);
  12168. };
  12169. #endif // __JUCE_THREAD_JUCEHEADER__
  12170. /********* End of inlined file: juce_Thread.h *********/
  12171. /**
  12172. A critical section that allows multiple simultaneous readers.
  12173. Features of this type of lock are:
  12174. - Multiple readers can hold the lock at the same time, but only one writer
  12175. can hold it at once.
  12176. - Writers trying to gain the lock will be blocked until all readers and writers
  12177. have released it
  12178. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  12179. blocked until the writer has obtained and released it
  12180. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  12181. there are no other readers
  12182. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  12183. - Recursive locking is supported.
  12184. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  12185. */
  12186. class JUCE_API ReadWriteLock
  12187. {
  12188. public:
  12189. /**
  12190. Creates a ReadWriteLock object.
  12191. */
  12192. ReadWriteLock() throw();
  12193. /** Destructor.
  12194. If the object is deleted whilst locked, any subsequent behaviour
  12195. is unpredictable.
  12196. */
  12197. ~ReadWriteLock() throw();
  12198. /** Locks this object for reading.
  12199. Multiple threads can simulaneously lock the object for reading, but if another
  12200. thread has it locked for writing, then this will block until it releases the
  12201. lock.
  12202. @see exitRead, ScopedReadLock
  12203. */
  12204. void enterRead() const throw();
  12205. /** Releases the read-lock.
  12206. If the caller thread hasn't got the lock, this can have unpredictable results.
  12207. If the enterRead() method has been called multiple times by the thread, each
  12208. call must be matched by a call to exitRead() before other threads will be allowed
  12209. to take over the lock.
  12210. @see enterRead, ScopedReadLock
  12211. */
  12212. void exitRead() const throw();
  12213. /** Locks this object for writing.
  12214. This will block until any other threads that have it locked for reading or
  12215. writing have released their lock.
  12216. @see exitWrite, ScopedWriteLock
  12217. */
  12218. void enterWrite() const throw();
  12219. /** Tries to lock this object for writing.
  12220. This is like enterWrite(), but doesn't block - it returns true if it manages
  12221. to obtain the lock.
  12222. @see enterWrite
  12223. */
  12224. bool tryEnterWrite() const throw();
  12225. /** Releases the write-lock.
  12226. If the caller thread hasn't got the lock, this can have unpredictable results.
  12227. If the enterWrite() method has been called multiple times by the thread, each
  12228. call must be matched by a call to exit() before other threads will be allowed
  12229. to take over the lock.
  12230. @see enterWrite, ScopedWriteLock
  12231. */
  12232. void exitWrite() const throw();
  12233. juce_UseDebuggingNewOperator
  12234. private:
  12235. CriticalSection accessLock;
  12236. WaitableEvent waitEvent;
  12237. mutable int numWaitingWriters, numWriters;
  12238. mutable Thread::ThreadID writerThreadId;
  12239. mutable Array <Thread::ThreadID> readerThreads;
  12240. ReadWriteLock (const ReadWriteLock&);
  12241. const ReadWriteLock& operator= (const ReadWriteLock&);
  12242. };
  12243. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  12244. /********* End of inlined file: juce_ReadWriteLock.h *********/
  12245. #endif
  12246. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  12247. #endif
  12248. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  12249. /********* Start of inlined file: juce_ScopedReadLock.h *********/
  12250. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  12251. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  12252. /**
  12253. Automatically locks and unlocks a ReadWriteLock object.
  12254. Use one of these as a local variable to control access to a ReadWriteLock.
  12255. e.g. @code
  12256. ReadWriteLock myLock;
  12257. for (;;)
  12258. {
  12259. const ScopedReadLock myScopedLock (myLock);
  12260. // myLock is now locked
  12261. ...do some stuff...
  12262. // myLock gets unlocked here.
  12263. }
  12264. @endcode
  12265. @see ReadWriteLock, ScopedWriteLock
  12266. */
  12267. class JUCE_API ScopedReadLock
  12268. {
  12269. public:
  12270. /** Creates a ScopedReadLock.
  12271. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  12272. when the ScopedReadLock object is deleted, the ReadWriteLock will
  12273. be unlocked.
  12274. Make sure this object is created and deleted by the same thread,
  12275. otherwise there are no guarantees what will happen! Best just to use it
  12276. as a local stack object, rather than creating one with the new() operator.
  12277. */
  12278. inline ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  12279. /** Destructor.
  12280. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  12281. Make sure this object is created and deleted by the same thread,
  12282. otherwise there are no guarantees what will happen!
  12283. */
  12284. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  12285. private:
  12286. const ReadWriteLock& lock_;
  12287. ScopedReadLock (const ScopedReadLock&);
  12288. const ScopedReadLock& operator= (const ScopedReadLock&);
  12289. };
  12290. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  12291. /********* End of inlined file: juce_ScopedReadLock.h *********/
  12292. #endif
  12293. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12294. /********* Start of inlined file: juce_ScopedTryLock.h *********/
  12295. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12296. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12297. /**
  12298. Automatically tries to lock and unlock a CriticalSection object.
  12299. Use one of these as a local variable to control access to a CriticalSection.
  12300. e.g. @code
  12301. CriticalSection myCriticalSection;
  12302. for (;;)
  12303. {
  12304. const ScopedTryLock myScopedTryLock (myCriticalSection);
  12305. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  12306. // should test this with the isLocked() method before doing your thread-unsafe
  12307. // action..
  12308. if (myScopedTryLock.isLocked())
  12309. {
  12310. ...do some stuff...
  12311. }
  12312. else
  12313. {
  12314. ..our attempt at locking failed because another thread had already locked it..
  12315. }
  12316. // myCriticalSection gets unlocked here (if it was locked)
  12317. }
  12318. @endcode
  12319. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  12320. */
  12321. class JUCE_API ScopedTryLock
  12322. {
  12323. public:
  12324. /** Creates a ScopedTryLock.
  12325. As soon as it is created, this will try to lock the CriticalSection, and
  12326. when the ScopedTryLock object is deleted, the CriticalSection will
  12327. be unlocked if the lock was successful.
  12328. Make sure this object is created and deleted by the same thread,
  12329. otherwise there are no guarantees what will happen! Best just to use it
  12330. as a local stack object, rather than creating one with the new() operator.
  12331. */
  12332. inline ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  12333. /** Destructor.
  12334. The CriticalSection will be unlocked (if locked) when the destructor is called.
  12335. Make sure this object is created and deleted by the same thread,
  12336. otherwise there are no guarantees what will happen!
  12337. */
  12338. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  12339. /** Lock state
  12340. @return True if the CriticalSection is locked.
  12341. */
  12342. bool isLocked() const throw() { return lockWasSuccessful; }
  12343. private:
  12344. const CriticalSection& lock_;
  12345. const bool lockWasSuccessful;
  12346. ScopedTryLock (const ScopedTryLock&);
  12347. const ScopedTryLock& operator= (const ScopedTryLock&);
  12348. };
  12349. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  12350. /********* End of inlined file: juce_ScopedTryLock.h *********/
  12351. #endif
  12352. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12353. /********* Start of inlined file: juce_ScopedWriteLock.h *********/
  12354. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12355. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12356. /**
  12357. Automatically locks and unlocks a ReadWriteLock object.
  12358. Use one of these as a local variable to control access to a ReadWriteLock.
  12359. e.g. @code
  12360. ReadWriteLock myLock;
  12361. for (;;)
  12362. {
  12363. const ScopedWriteLock myScopedLock (myLock);
  12364. // myLock is now locked
  12365. ...do some stuff...
  12366. // myLock gets unlocked here.
  12367. }
  12368. @endcode
  12369. @see ReadWriteLock, ScopedReadLock
  12370. */
  12371. class JUCE_API ScopedWriteLock
  12372. {
  12373. public:
  12374. /** Creates a ScopedWriteLock.
  12375. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  12376. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  12377. be unlocked.
  12378. Make sure this object is created and deleted by the same thread,
  12379. otherwise there are no guarantees what will happen! Best just to use it
  12380. as a local stack object, rather than creating one with the new() operator.
  12381. */
  12382. inline ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  12383. /** Destructor.
  12384. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  12385. Make sure this object is created and deleted by the same thread,
  12386. otherwise there are no guarantees what will happen!
  12387. */
  12388. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  12389. private:
  12390. const ReadWriteLock& lock_;
  12391. ScopedWriteLock (const ScopedWriteLock&);
  12392. const ScopedWriteLock& operator= (const ScopedWriteLock&);
  12393. };
  12394. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  12395. /********* End of inlined file: juce_ScopedWriteLock.h *********/
  12396. #endif
  12397. #ifndef __JUCE_THREAD_JUCEHEADER__
  12398. #endif
  12399. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  12400. /********* Start of inlined file: juce_ThreadPool.h *********/
  12401. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  12402. #define __JUCE_THREADPOOL_JUCEHEADER__
  12403. class ThreadPool;
  12404. class ThreadPoolThread;
  12405. /**
  12406. A task that is executed by a ThreadPool object.
  12407. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  12408. its threads.
  12409. The runJob() method needs to be implemented to do the task, and if the code that
  12410. does the work takes a significant time to run, it must keep checking the shouldExit()
  12411. method to see if something is trying to interrupt the job. If shouldExit() returns
  12412. true, the runJob() method must return immediately.
  12413. @see ThreadPool, Thread
  12414. */
  12415. class JUCE_API ThreadPoolJob
  12416. {
  12417. public:
  12418. /** Creates a thread pool job object.
  12419. After creating your job, add it to a thread pool with ThreadPool::addJob().
  12420. */
  12421. ThreadPoolJob (const String& name);
  12422. /** Destructor. */
  12423. virtual ~ThreadPoolJob();
  12424. /** Returns the name of this job.
  12425. @see setJobName
  12426. */
  12427. const String getJobName() const throw();
  12428. /** Changes the job's name.
  12429. @see getJobName
  12430. */
  12431. void setJobName (const String& newName) throw();
  12432. /** These are the values that can be returned by the runJob() method.
  12433. */
  12434. enum JobStatus
  12435. {
  12436. jobHasFinished = 0, /**< indicates that the job has finished and can be
  12437. removed from the pool. */
  12438. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  12439. should be automatically deleted by the pool. */
  12440. jobNeedsRunningAgain /**< indicates that the job would like to be called
  12441. again when a thread is free. */
  12442. };
  12443. /** Peforms the actual work that this job needs to do.
  12444. Your subclass must implement this method, in which is does its work.
  12445. If the code in this method takes a significant time to run, it must repeatedly check
  12446. the shouldExit() method to see if something is trying to interrupt the job.
  12447. If shouldExit() ever returns true, the runJob() method must return immediately.
  12448. If this method returns jobHasFinished, then the job will be removed from the pool
  12449. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  12450. pool and will get a chance to run again as soon as a thread is free.
  12451. @see shouldExit()
  12452. */
  12453. virtual JobStatus runJob() = 0;
  12454. /** Returns true if this job is currently running its runJob() method. */
  12455. bool isRunning() const throw() { return isActive; }
  12456. /** Returns true if something is trying to interrupt this job and make it stop.
  12457. Your runJob() method must call this whenever it gets a chance, and if it ever
  12458. returns true, the runJob() method must return immediately.
  12459. @see signalJobShouldExit()
  12460. */
  12461. bool shouldExit() const throw() { return shouldStop; }
  12462. /** Calling this will cause the shouldExit() method to return true, and the job
  12463. should (if it's been implemented correctly) stop as soon as possible.
  12464. @see shouldExit()
  12465. */
  12466. void signalJobShouldExit() throw();
  12467. juce_UseDebuggingNewOperator
  12468. private:
  12469. friend class ThreadPool;
  12470. friend class ThreadPoolThread;
  12471. String jobName;
  12472. ThreadPool* pool;
  12473. bool shouldStop, isActive, shouldBeDeleted;
  12474. ThreadPoolJob (const ThreadPoolJob&);
  12475. const ThreadPoolJob& operator= (const ThreadPoolJob&);
  12476. };
  12477. /**
  12478. A set of threads that will run a list of jobs.
  12479. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  12480. will be called by the next pooled thread that becomes free.
  12481. @see ThreadPoolJob, Thread
  12482. */
  12483. class JUCE_API ThreadPool
  12484. {
  12485. public:
  12486. /** Creates a thread pool.
  12487. Once you've created a pool, you can give it some things to do with the addJob()
  12488. method.
  12489. @param numberOfThreads the maximum number of actual threads to run.
  12490. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  12491. until there are some jobs to run. If false, then
  12492. all the threads will be fired-up immediately so that
  12493. they're ready for action
  12494. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  12495. inactive for this length of time, they will automatically
  12496. be stopped until more jobs come along and they're needed
  12497. */
  12498. ThreadPool (const int numberOfThreads,
  12499. const bool startThreadsOnlyWhenNeeded = true,
  12500. const int stopThreadsWhenNotUsedTimeoutMs = 5000);
  12501. /** Destructor.
  12502. This will attempt to remove all the jobs before deleting, but if you want to
  12503. specify a timeout, you should call removeAllJobs() explicitly before deleting
  12504. the pool.
  12505. */
  12506. ~ThreadPool();
  12507. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  12508. for some kind of operation.
  12509. @see ThreadPool::removeAllJobs
  12510. */
  12511. class JUCE_API JobSelector
  12512. {
  12513. public:
  12514. virtual ~JobSelector() {}
  12515. /** Should return true if the specified thread matches your criteria for whatever
  12516. operation that this object is being used for.
  12517. Any implementation of this method must be extremely fast and thread-safe!
  12518. */
  12519. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  12520. };
  12521. /** Adds a job to the queue.
  12522. Once a job has been added, then the next time a thread is free, it will run
  12523. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  12524. runJob() method, the pool will either remove the job from the pool or add it to
  12525. the back of the queue to be run again.
  12526. */
  12527. void addJob (ThreadPoolJob* const job);
  12528. /** Tries to remove a job from the pool.
  12529. If the job isn't yet running, this will simply remove it. If it is running, it
  12530. will wait for it to finish.
  12531. If the timeout period expires before the job finishes running, then the job will be
  12532. left in the pool and this will return false. It returns true if the job is sucessfully
  12533. stopped and removed.
  12534. @param job the job to remove
  12535. @param interruptIfRunning if true, then if the job is currently busy, its
  12536. ThreadPoolJob::signalJobShouldExit() method will be called to try
  12537. to interrupt it. If false, then if the job will be allowed to run
  12538. until it stops normally (or the timeout expires)
  12539. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  12540. before giving up and returning false
  12541. */
  12542. bool removeJob (ThreadPoolJob* const job,
  12543. const bool interruptIfRunning,
  12544. const int timeOutMilliseconds);
  12545. /** Tries to remove all jobs from the pool.
  12546. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  12547. methods called to try to interrupt them
  12548. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  12549. before giving up and returning false
  12550. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  12551. they will simply be removed from the pool. Jobs that are already running when
  12552. this method is called can choose whether they should be deleted by
  12553. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  12554. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  12555. jobs should be removed. If it is zero, all jobs are removed
  12556. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  12557. expires while waiting for one or more jobs to stop
  12558. */
  12559. bool removeAllJobs (const bool interruptRunningJobs,
  12560. const int timeOutMilliseconds,
  12561. const bool deleteInactiveJobs = false,
  12562. JobSelector* selectedJobsToRemove = 0);
  12563. /** Returns the number of jobs currently running or queued.
  12564. */
  12565. int getNumJobs() const throw();
  12566. /** Returns one of the jobs in the queue.
  12567. Note that this can be a very volatile list as jobs might be continuously getting shifted
  12568. around in the list, and this method may return 0 if the index is currently out-of-range.
  12569. */
  12570. ThreadPoolJob* getJob (const int index) const throw();
  12571. /** Returns true if the given job is currently queued or running.
  12572. @see isJobRunning()
  12573. */
  12574. bool contains (const ThreadPoolJob* const job) const throw();
  12575. /** Returns true if the given job is currently being run by a thread.
  12576. */
  12577. bool isJobRunning (const ThreadPoolJob* const job) const;
  12578. /** Waits until a job has finished running and has been removed from the pool.
  12579. This will wait until the job is no longer in the pool - i.e. until its
  12580. runJob() method returns ThreadPoolJob::jobHasFinished.
  12581. If the timeout period expires before the job finishes, this will return false;
  12582. it returns true if the job has finished successfully.
  12583. */
  12584. bool waitForJobToFinish (const ThreadPoolJob* const job,
  12585. const int timeOutMilliseconds) const;
  12586. /** Returns a list of the names of all the jobs currently running or queued.
  12587. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  12588. */
  12589. const StringArray getNamesOfAllJobs (const bool onlyReturnActiveJobs) const throw();
  12590. /** Changes the priority of all the threads.
  12591. This will call Thread::setPriority() for each thread in the pool.
  12592. May return false if for some reason the priority can't be changed.
  12593. */
  12594. bool setThreadPriorities (const int newPriority);
  12595. juce_UseDebuggingNewOperator
  12596. private:
  12597. const int numThreads, threadStopTimeout;
  12598. int priority;
  12599. HeapBlock <Thread*> threads;
  12600. VoidArray jobs;
  12601. CriticalSection lock;
  12602. uint32 lastJobEndTime;
  12603. WaitableEvent jobFinishedSignal;
  12604. friend class ThreadPoolThread;
  12605. bool runNextJob();
  12606. ThreadPool (const ThreadPool&);
  12607. const ThreadPool& operator= (const ThreadPool&);
  12608. };
  12609. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  12610. /********* End of inlined file: juce_ThreadPool.h *********/
  12611. #endif
  12612. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12613. /********* Start of inlined file: juce_TimeSliceThread.h *********/
  12614. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12615. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12616. /**
  12617. Used by the TimeSliceThread class.
  12618. To register your class with a TimeSliceThread, derive from this class and
  12619. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  12620. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  12621. deleting your client!
  12622. @see TimeSliceThread
  12623. */
  12624. class JUCE_API TimeSliceClient
  12625. {
  12626. public:
  12627. /** Destructor. */
  12628. virtual ~TimeSliceClient() {}
  12629. /** Called back by a TimeSliceThread.
  12630. When you register this class with it, a TimeSliceThread will repeatedly call
  12631. this method.
  12632. The implementation of this method should use its time-slice to do something that's
  12633. quick - never block for longer than absolutely necessary.
  12634. @returns Your method should return true if it needs more time, or false if it's
  12635. not too busy and doesn't need calling back urgently. If all the thread's
  12636. clients indicate that they're not busy, then it'll save CPU by sleeping for
  12637. up to half a second in between callbacks. You can force the TimeSliceThread
  12638. to wake up and poll again immediately by calling its notify() method.
  12639. */
  12640. virtual bool useTimeSlice() = 0;
  12641. };
  12642. /**
  12643. A thread that keeps a list of clients, and calls each one in turn, giving them
  12644. all a chance to run some sort of short task.
  12645. @see TimeSliceClient, Thread
  12646. */
  12647. class JUCE_API TimeSliceThread : public Thread
  12648. {
  12649. public:
  12650. /**
  12651. Creates a TimeSliceThread.
  12652. When first created, the thread is not running. Use the startThread()
  12653. method to start it.
  12654. */
  12655. TimeSliceThread (const String& threadName);
  12656. /** Destructor.
  12657. Deleting a Thread object that is running will only give the thread a
  12658. brief opportunity to stop itself cleanly, so it's recommended that you
  12659. should always call stopThread() with a decent timeout before deleting,
  12660. to avoid the thread being forcibly killed (which is a Bad Thing).
  12661. */
  12662. ~TimeSliceThread();
  12663. /** Adds a client to the list.
  12664. The client's callbacks will start immediately (possibly before the method
  12665. has returned).
  12666. */
  12667. void addTimeSliceClient (TimeSliceClient* const client);
  12668. /** Removes a client from the list.
  12669. This method will make sure that all callbacks to the client have completely
  12670. finished before the method returns.
  12671. */
  12672. void removeTimeSliceClient (TimeSliceClient* const client);
  12673. /** Returns the number of registered clients. */
  12674. int getNumClients() const throw();
  12675. /** Returns one of the registered clients. */
  12676. TimeSliceClient* getClient (const int index) const throw();
  12677. /** @internal */
  12678. void run();
  12679. juce_UseDebuggingNewOperator
  12680. private:
  12681. CriticalSection callbackLock, listLock;
  12682. Array <TimeSliceClient*> clients;
  12683. int index;
  12684. TimeSliceClient* clientBeingCalled;
  12685. bool clientsChanged;
  12686. TimeSliceThread (const TimeSliceThread&);
  12687. const TimeSliceThread& operator= (const TimeSliceThread&);
  12688. };
  12689. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  12690. /********* End of inlined file: juce_TimeSliceThread.h *********/
  12691. #endif
  12692. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  12693. #endif
  12694. #endif
  12695. /********* End of inlined file: juce_core_includes.h *********/
  12696. // if you're compiling a command-line app, you might want to just include the core headers,
  12697. // so you can set this macro before including juce.h
  12698. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  12699. /********* Start of inlined file: juce_app_includes.h *********/
  12700. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  12701. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  12702. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  12703. /********* Start of inlined file: juce_Application.h *********/
  12704. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  12705. #define __JUCE_APPLICATION_JUCEHEADER__
  12706. /********* Start of inlined file: juce_ApplicationCommandTarget.h *********/
  12707. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  12708. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  12709. /********* Start of inlined file: juce_Component.h *********/
  12710. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  12711. #define __JUCE_COMPONENT_JUCEHEADER__
  12712. /********* Start of inlined file: juce_MouseCursor.h *********/
  12713. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  12714. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  12715. class Image;
  12716. class RefCountedMouseCursor;
  12717. class ComponentPeer;
  12718. class Component;
  12719. /**
  12720. Represents a mouse cursor image.
  12721. This object can either be used to represent one of the standard mouse
  12722. cursor shapes, or a custom one generated from an image.
  12723. */
  12724. class JUCE_API MouseCursor
  12725. {
  12726. public:
  12727. /** The set of available standard mouse cursors. */
  12728. enum StandardCursorType
  12729. {
  12730. NoCursor = 0, /**< An invisible cursor. */
  12731. NormalCursor, /**< The stardard arrow cursor. */
  12732. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  12733. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  12734. CrosshairCursor, /**< A pair of crosshairs. */
  12735. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  12736. that you're dragging a copy of something. */
  12737. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  12738. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  12739. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  12740. UpDownResizeCursor, /**< an arrow pointing up and down. */
  12741. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  12742. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  12743. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  12744. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  12745. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  12746. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  12747. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  12748. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  12749. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  12750. };
  12751. /** Creates the standard arrow cursor. */
  12752. MouseCursor() throw();
  12753. /** Creates one of the standard mouse cursor */
  12754. MouseCursor (const StandardCursorType type) throw();
  12755. /** Creates a custom cursor from an image.
  12756. @param image the image to use for the cursor - if this is bigger than the
  12757. system can manage, it might get scaled down first, and might
  12758. also have to be turned to black-and-white if it can't do colour
  12759. cursors.
  12760. @param hotSpotX the x position of the cursor's hotspot within the image
  12761. @param hotSpotY the y position of the cursor's hotspot within the image
  12762. */
  12763. MouseCursor (Image& image,
  12764. const int hotSpotX,
  12765. const int hotSpotY) throw();
  12766. /** Creates a copy of another cursor object. */
  12767. MouseCursor (const MouseCursor& other) throw();
  12768. /** Copies this cursor from another object. */
  12769. const MouseCursor& operator= (const MouseCursor& other) throw();
  12770. /** Destructor. */
  12771. ~MouseCursor() throw();
  12772. /** Checks whether two mouse cursors are the same.
  12773. For custom cursors, two cursors created from the same image won't be
  12774. recognised as the same, only MouseCursor objects that have been
  12775. copied from the same object.
  12776. */
  12777. bool operator== (const MouseCursor& other) const throw();
  12778. /** Checks whether two mouse cursors are the same.
  12779. For custom cursors, two cursors created from the same image won't be
  12780. recognised as the same, only MouseCursor objects that have been
  12781. copied from the same object.
  12782. */
  12783. bool operator!= (const MouseCursor& other) const throw();
  12784. /** Makes the system show its default 'busy' cursor.
  12785. This will turn the system cursor to an hourglass or spinning beachball
  12786. until the next time the mouse is moved, or hideWaitCursor() is called.
  12787. This is handy if the message loop is about to block for a couple of
  12788. seconds while busy and you want to give the user feedback about this.
  12789. @see MessageManager::setTimeBeforeShowingWaitCursor
  12790. */
  12791. static void showWaitCursor() throw();
  12792. /** If showWaitCursor has been called, this will return the mouse to its
  12793. normal state.
  12794. This will look at what component is under the mouse, and update the
  12795. cursor to be the correct one for that component.
  12796. @see showWaitCursor
  12797. */
  12798. static void hideWaitCursor() throw();
  12799. juce_UseDebuggingNewOperator
  12800. private:
  12801. RefCountedMouseCursor* cursorHandle;
  12802. friend class Component;
  12803. void showInWindow (ComponentPeer* window) const throw();
  12804. void showInAllWindows() const throw();
  12805. void* getHandle() const throw();
  12806. };
  12807. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  12808. /********* End of inlined file: juce_MouseCursor.h *********/
  12809. /********* Start of inlined file: juce_MouseListener.h *********/
  12810. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  12811. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  12812. /********* Start of inlined file: juce_MouseEvent.h *********/
  12813. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  12814. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  12815. class Component;
  12816. /********* Start of inlined file: juce_ModifierKeys.h *********/
  12817. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  12818. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  12819. /**
  12820. Represents the state of the mouse buttons and modifier keys.
  12821. This is used both by mouse events and by KeyPress objects to describe
  12822. the state of keys such as shift, control, alt, etc.
  12823. @see KeyPress, MouseEvent::mods
  12824. */
  12825. class JUCE_API ModifierKeys
  12826. {
  12827. public:
  12828. /** Creates a ModifierKeys object from a raw set of flags.
  12829. @param flags to represent the keys that are down
  12830. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  12831. rightButtonModifier, commandModifier, popupMenuClickModifier
  12832. */
  12833. ModifierKeys (const int flags = 0) throw();
  12834. /** Creates a copy of another object. */
  12835. ModifierKeys (const ModifierKeys& other) throw();
  12836. /** Copies this object from another one. */
  12837. const ModifierKeys& operator= (const ModifierKeys& other) throw();
  12838. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  12839. This is a platform-agnostic way of checking for the operating system's
  12840. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  12841. Windows/Linux, it's actually checking for the CTRL key.
  12842. */
  12843. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  12844. /** Checks whether the user is trying to launch a pop-up menu.
  12845. This checks for platform-specific modifiers that might indicate that the user
  12846. is following the operating system's normal method of showing a pop-up menu.
  12847. So on Windows/Linux, this method is really testing for a right-click.
  12848. On the Mac, it tests for either the CTRL key being down, or a right-click.
  12849. */
  12850. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  12851. /** Checks whether the flag is set for the left mouse-button. */
  12852. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  12853. /** Checks whether the flag is set for the right mouse-button.
  12854. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  12855. this is platform-independent (and makes your code more explanatory too).
  12856. */
  12857. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  12858. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  12859. /** Tests for any of the mouse-button flags. */
  12860. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  12861. /** Tests for any of the modifier key flags. */
  12862. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  12863. /** Checks whether the shift key's flag is set. */
  12864. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  12865. /** Checks whether the CTRL key's flag is set.
  12866. Remember that it's better to use the platform-agnostic routines to test for command-key and
  12867. popup-menu modifiers.
  12868. @see isCommandDown, isPopupMenu
  12869. */
  12870. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  12871. /** Checks whether the shift key's flag is set. */
  12872. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  12873. /** Flags that represent the different keys. */
  12874. enum Flags
  12875. {
  12876. /** Shift key flag. */
  12877. shiftModifier = 1,
  12878. /** CTRL key flag. */
  12879. ctrlModifier = 2,
  12880. /** ALT key flag. */
  12881. altModifier = 4,
  12882. /** Left mouse button flag. */
  12883. leftButtonModifier = 16,
  12884. /** Right mouse button flag. */
  12885. rightButtonModifier = 32,
  12886. /** Middle mouse button flag. */
  12887. middleButtonModifier = 64,
  12888. #if JUCE_MAC
  12889. /** Command key flag - on windows this is the same as the CTRL key flag. */
  12890. commandModifier = 8,
  12891. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  12892. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  12893. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  12894. #else
  12895. /** Command key flag - on windows this is the same as the CTRL key flag. */
  12896. commandModifier = ctrlModifier,
  12897. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  12898. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  12899. popupMenuClickModifier = rightButtonModifier,
  12900. #endif
  12901. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  12902. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  12903. /** Represents a combination of all the mouse buttons at once. */
  12904. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  12905. };
  12906. /** Returns the raw flags for direct testing. */
  12907. inline int getRawFlags() const throw() { return flags; }
  12908. /** Tests a combination of flags and returns true if any of them are set. */
  12909. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  12910. /** Creates a ModifierKeys object to represent the last-known state of the
  12911. keyboard and mouse buttons.
  12912. @see getCurrentModifiersRealtime
  12913. */
  12914. static const ModifierKeys getCurrentModifiers() throw();
  12915. /** Creates a ModifierKeys object to represent the current state of the
  12916. keyboard and mouse buttons.
  12917. This isn't often needed and isn't recommended, but will actively check all the
  12918. mouse and key states rather than just returning their last-known state like
  12919. getCurrentModifiers() does.
  12920. This is only needed in special circumstances for up-to-date modifier information
  12921. at times when the app's event loop isn't running normally.
  12922. */
  12923. static const ModifierKeys getCurrentModifiersRealtime() throw();
  12924. private:
  12925. int flags;
  12926. static int currentModifierFlags;
  12927. friend class ComponentPeer;
  12928. static void updateCurrentModifiers() throw();
  12929. };
  12930. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  12931. /********* End of inlined file: juce_ModifierKeys.h *********/
  12932. /**
  12933. Contains position and status information about a mouse event.
  12934. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  12935. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  12936. */
  12937. class JUCE_API MouseEvent
  12938. {
  12939. public:
  12940. /** Creates a MouseEvent.
  12941. Normally an application will never need to use this.
  12942. @param x the x position of the mouse, relative to the component that is passed-in
  12943. @param y the y position of the mouse, relative to the component that is passed-in
  12944. @param modifiers the key modifiers at the time of the event
  12945. @param originator the component that the mouse event applies to
  12946. @param eventTime the time the event happened
  12947. @param mouseDownX the x position of the corresponding mouse-down event (relative to the component that is passed-in).
  12948. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  12949. the same as the current mouse-x position.
  12950. @param mouseDownY the y position of the corresponding mouse-down event (relative to the component that is passed-in)
  12951. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  12952. the same as the current mouse-y position.
  12953. @param mouseDownTime the time at which the corresponding mouse-down event happened
  12954. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  12955. the same as the current mouse-event time.
  12956. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  12957. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  12958. */
  12959. MouseEvent (const int x, const int y,
  12960. const ModifierKeys& modifiers,
  12961. Component* const originator,
  12962. const Time& eventTime,
  12963. const int mouseDownX,
  12964. const int mouseDownY,
  12965. const Time& mouseDownTime,
  12966. const int numberOfClicks,
  12967. const bool mouseWasDragged) throw();
  12968. /** Destructor. */
  12969. ~MouseEvent() throw();
  12970. /** The x-position of the mouse when the event occurred.
  12971. This value is relative to the top-left of the component to which the
  12972. event applies (as indicated by the MouseEvent::eventComponent field).
  12973. */
  12974. int x;
  12975. /** The y-position of the mouse when the event occurred.
  12976. This value is relative to the top-left of the component to which the
  12977. event applies (as indicated by the MouseEvent::eventComponent field).
  12978. */
  12979. int y;
  12980. /** The key modifiers associated with the event.
  12981. This will let you find out which mouse buttons were down, as well as which
  12982. modifier keys were held down.
  12983. When used for mouse-up events, this will indicate the state of the mouse buttons
  12984. just before they were released, so that you can tell which button they let go of.
  12985. */
  12986. ModifierKeys mods;
  12987. /** The component that this event applies to.
  12988. This is usually the component that the mouse was over at the time, but for mouse-drag
  12989. events the mouse could actually be over a different component and the events are
  12990. still sent to the component that the button was originally pressed on.
  12991. The x and y member variables are relative to this component's position.
  12992. If you use getEventRelativeTo() to retarget this object to be relative to a different
  12993. component, this pointer will be updated, but originalComponent remains unchanged.
  12994. @see originalComponent
  12995. */
  12996. Component* eventComponent;
  12997. /** The component that the event first occurred on.
  12998. If you use getEventRelativeTo() to retarget this object to be relative to a different
  12999. component, this value remains unchanged to indicate the first component that received it.
  13000. @see eventComponent
  13001. */
  13002. Component* originalComponent;
  13003. /** The time that this mouse-event occurred.
  13004. */
  13005. Time eventTime;
  13006. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  13007. The co-ordinate is relative to the component specified in MouseEvent::component.
  13008. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  13009. */
  13010. int getMouseDownX() const throw();
  13011. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  13012. The co-ordinate is relative to the component specified in MouseEvent::component.
  13013. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  13014. */
  13015. int getMouseDownY() const throw();
  13016. /** Returns the straight-line distance between where the mouse is now and where it
  13017. was the last time the button was pressed.
  13018. This is quite handy for things like deciding whether the user has moved far enough
  13019. for it to be considered a drag operation.
  13020. @see getDistanceFromDragStartX
  13021. */
  13022. int getDistanceFromDragStart() const throw();
  13023. /** Returns the difference between the mouse's current x postion and where it was
  13024. when the button was last pressed.
  13025. @see getDistanceFromDragStart
  13026. */
  13027. int getDistanceFromDragStartX() const throw();
  13028. /** Returns the difference between the mouse's current y postion and where it was
  13029. when the button was last pressed.
  13030. @see getDistanceFromDragStart
  13031. */
  13032. int getDistanceFromDragStartY() const throw();
  13033. /** Returns true if the mouse has just been clicked.
  13034. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  13035. the user has dragged the mouse more than a few pixels from the place where the
  13036. mouse-down occurred.
  13037. Once they have dragged it far enough for this method to return false, it will continue
  13038. to return false until the mouse-up, even if they move the mouse back to the same
  13039. position where they originally pressed it. This means that it's very handy for
  13040. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  13041. callback to ignore any small movements they might make while clicking.
  13042. @returns true if the mouse wasn't dragged by more than a few pixels between
  13043. the last time the button was pressed and released.
  13044. */
  13045. bool mouseWasClicked() const throw();
  13046. /** For a click event, the number of times the mouse was clicked in succession.
  13047. So for example a double-click event will return 2, a triple-click 3, etc.
  13048. */
  13049. int getNumberOfClicks() const throw() { return numberOfClicks; }
  13050. /** Returns the time that the mouse button has been held down for.
  13051. If called from a mouseDrag or mouseUp callback, this will return the
  13052. number of milliseconds since the corresponding mouseDown event occurred.
  13053. If called in other contexts, e.g. a mouseMove, then the returned value
  13054. may be 0 or an undefined value.
  13055. */
  13056. int getLengthOfMousePress() const throw();
  13057. /** Returns the mouse x position of this event, in global screen co-ordinates.
  13058. The co-ordinates are relative to the top-left of the main monitor.
  13059. @see getMouseDownScreenX, Desktop::getMousePosition
  13060. */
  13061. int getScreenX() const throw();
  13062. /** Returns the mouse y position of this event, in global screen co-ordinates.
  13063. The co-ordinates are relative to the top-left of the main monitor.
  13064. @see getMouseDownScreenY, Desktop::getMousePosition
  13065. */
  13066. int getScreenY() const throw();
  13067. /** Returns the x co-ordinate at which the mouse button was last pressed.
  13068. The co-ordinates are relative to the top-left of the main monitor.
  13069. @see getScreenX, Desktop::getMousePosition
  13070. */
  13071. int getMouseDownScreenX() const throw();
  13072. /** Returns the y co-ordinate at which the mouse button was last pressed.
  13073. The co-ordinates are relative to the top-left of the main monitor.
  13074. @see getScreenY, Desktop::getMousePosition
  13075. */
  13076. int getMouseDownScreenY() const throw();
  13077. /** Creates a version of this event that is relative to a different component.
  13078. The x and y positions of the event that is returned will have been
  13079. adjusted to be relative to the new component.
  13080. */
  13081. const MouseEvent getEventRelativeTo (Component* const otherComponent) const throw();
  13082. /** Changes the application-wide setting for the double-click time limit.
  13083. This is the maximum length of time between mouse-clicks for it to be
  13084. considered a double-click. It's used by the Component class.
  13085. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  13086. */
  13087. static void setDoubleClickTimeout (const int timeOutMilliseconds) throw();
  13088. /** Returns the application-wide setting for the double-click time limit.
  13089. This is the maximum length of time between mouse-clicks for it to be
  13090. considered a double-click. It's used by the Component class.
  13091. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  13092. */
  13093. static int getDoubleClickTimeout() throw();
  13094. juce_UseDebuggingNewOperator
  13095. private:
  13096. int mouseDownX, mouseDownY;
  13097. Time mouseDownTime;
  13098. int numberOfClicks;
  13099. bool wasMovedSinceMouseDown;
  13100. };
  13101. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  13102. /********* End of inlined file: juce_MouseEvent.h *********/
  13103. /**
  13104. A MouseListener can be registered with a component to receive callbacks
  13105. about mouse events that happen to that component.
  13106. @see Component::addMouseListener, Component::removeMouseListener
  13107. */
  13108. class JUCE_API MouseListener
  13109. {
  13110. public:
  13111. /** Destructor. */
  13112. virtual ~MouseListener() {}
  13113. /** Called when the mouse moves inside a component.
  13114. If the mouse button isn't pressed and the mouse moves over a component,
  13115. this will be called to let the component react to this.
  13116. A component will always get a mouseEnter callback before a mouseMove.
  13117. @param e details about the position and status of the mouse event, including
  13118. the source component in which it occurred
  13119. @see mouseEnter, mouseExit, mouseDrag, contains
  13120. */
  13121. virtual void mouseMove (const MouseEvent& e);
  13122. /** Called when the mouse first enters a component.
  13123. If the mouse button isn't pressed and the mouse moves into a component,
  13124. this will be called to let the component react to this.
  13125. When the mouse button is pressed and held down while being moved in
  13126. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  13127. mouseDrag messages are sent to the component that the mouse was originally
  13128. clicked on, until the button is released.
  13129. @param e details about the position and status of the mouse event, including
  13130. the source component in which it occurred
  13131. @see mouseExit, mouseDrag, mouseMove, contains
  13132. */
  13133. virtual void mouseEnter (const MouseEvent& e);
  13134. /** Called when the mouse moves out of a component.
  13135. This will be called when the mouse moves off the edge of this
  13136. component.
  13137. If the mouse button was pressed, and it was then dragged off the
  13138. edge of the component and released, then this callback will happen
  13139. when the button is released, after the mouseUp callback.
  13140. @param e details about the position and status of the mouse event, including
  13141. the source component in which it occurred
  13142. @see mouseEnter, mouseDrag, mouseMove, contains
  13143. */
  13144. virtual void mouseExit (const MouseEvent& e);
  13145. /** Called when a mouse button is pressed.
  13146. The MouseEvent object passed in contains lots of methods for finding out
  13147. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  13148. were held down at the time.
  13149. Once a button is held down, the mouseDrag method will be called when the
  13150. mouse moves, until the button is released.
  13151. @param e details about the position and status of the mouse event, including
  13152. the source component in which it occurred
  13153. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  13154. */
  13155. virtual void mouseDown (const MouseEvent& e);
  13156. /** Called when the mouse is moved while a button is held down.
  13157. When a mouse button is pressed inside a component, that component
  13158. receives mouseDrag callbacks each time the mouse moves, even if the
  13159. mouse strays outside the component's bounds.
  13160. @param e details about the position and status of the mouse event, including
  13161. the source component in which it occurred
  13162. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  13163. */
  13164. virtual void mouseDrag (const MouseEvent& e);
  13165. /** Called when a mouse button is released.
  13166. A mouseUp callback is sent to the component in which a button was pressed
  13167. even if the mouse is actually over a different component when the
  13168. button is released.
  13169. The MouseEvent object passed in contains lots of methods for finding out
  13170. which buttons were down just before they were released.
  13171. @param e details about the position and status of the mouse event, including
  13172. the source component in which it occurred
  13173. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  13174. */
  13175. virtual void mouseUp (const MouseEvent& e);
  13176. /** Called when a mouse button has been double-clicked on a component.
  13177. The MouseEvent object passed in contains lots of methods for finding out
  13178. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  13179. were held down at the time.
  13180. @param e details about the position and status of the mouse event, including
  13181. the source component in which it occurred
  13182. @see mouseDown, mouseUp
  13183. */
  13184. virtual void mouseDoubleClick (const MouseEvent& e);
  13185. /** Called when the mouse-wheel is moved.
  13186. This callback is sent to the component that the mouse is over when the
  13187. wheel is moved.
  13188. If not overridden, the component will forward this message to its parent, so
  13189. that parent components can collect mouse-wheel messages that happen to
  13190. child components which aren't interested in them.
  13191. @param e details about the position and status of the mouse event, including
  13192. the source component in which it occurred
  13193. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  13194. value means the wheel has been pushed to the right, negative means it
  13195. was pushed to the left
  13196. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  13197. value means the wheel has been pushed upwards, negative means it
  13198. was pushed downwards
  13199. */
  13200. virtual void mouseWheelMove (const MouseEvent& e,
  13201. float wheelIncrementX,
  13202. float wheelIncrementY);
  13203. };
  13204. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  13205. /********* End of inlined file: juce_MouseListener.h *********/
  13206. /********* Start of inlined file: juce_ComponentListener.h *********/
  13207. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  13208. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  13209. class Component;
  13210. /**
  13211. Gets informed about changes to a component's hierarchy or position.
  13212. To monitor a component for changes, register a subclass of ComponentListener
  13213. with the component using Component::addComponentListener().
  13214. Be sure to deregister listeners before you delete them!
  13215. @see Component::addComponentListener, Component::removeComponentListener
  13216. */
  13217. class JUCE_API ComponentListener
  13218. {
  13219. public:
  13220. /** Destructor. */
  13221. virtual ~ComponentListener() {}
  13222. /** Called when the component's position or size changes.
  13223. @param component the component that was moved or resized
  13224. @param wasMoved true if the component's top-left corner has just moved
  13225. @param wasResized true if the component's width or height has just changed
  13226. @see Component::setBounds, Component::resized, Component::moved
  13227. */
  13228. virtual void componentMovedOrResized (Component& component,
  13229. bool wasMoved,
  13230. bool wasResized);
  13231. /** Called when the component is brought to the top of the z-order.
  13232. @param component the component that was moved
  13233. @see Component::toFront, Component::broughtToFront
  13234. */
  13235. virtual void componentBroughtToFront (Component& component);
  13236. /** Called when the component is made visible or invisible.
  13237. @param component the component that changed
  13238. @see Component::setVisible
  13239. */
  13240. virtual void componentVisibilityChanged (Component& component);
  13241. /** Called when the component has children added or removed.
  13242. @param component the component whose children were changed
  13243. @see Component::childrenChanged, Component::addChildComponent,
  13244. Component::removeChildComponent
  13245. */
  13246. virtual void componentChildrenChanged (Component& component);
  13247. /** Called to indicate that the component's parents have changed.
  13248. When a component is added or removed from its parent, all of its children
  13249. will produce this notification (recursively - so all children of its
  13250. children will also be called as well).
  13251. @param component the component that this listener is registered with
  13252. @see Component::parentHierarchyChanged
  13253. */
  13254. virtual void componentParentHierarchyChanged (Component& component);
  13255. /** Called when the component's name is changed.
  13256. @see Component::setName, Component::getName
  13257. */
  13258. virtual void componentNameChanged (Component& component);
  13259. };
  13260. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  13261. /********* End of inlined file: juce_ComponentListener.h *********/
  13262. /********* Start of inlined file: juce_KeyListener.h *********/
  13263. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  13264. #define __JUCE_KEYLISTENER_JUCEHEADER__
  13265. /********* Start of inlined file: juce_KeyPress.h *********/
  13266. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  13267. #define __JUCE_KEYPRESS_JUCEHEADER__
  13268. /**
  13269. Represents a key press, including any modifier keys that are needed.
  13270. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  13271. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  13272. */
  13273. class JUCE_API KeyPress
  13274. {
  13275. public:
  13276. /** Creates an (invalid) KeyPress.
  13277. @see isValid
  13278. */
  13279. KeyPress() throw();
  13280. /** Creates a KeyPress for a key and some modifiers.
  13281. e.g.
  13282. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  13283. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  13284. @param keyCode a code that represents the key - this value must be
  13285. one of special constants listed in this class, or an
  13286. 8-bit character code such as a letter (case is ignored),
  13287. digit or a simple key like "," or ".". Note that this
  13288. isn't the same as the textCharacter parameter, so for example
  13289. a keyCode of 'a' and a shift-key modifier should have a
  13290. textCharacter value of 'A'.
  13291. @param modifiers the modifiers to associate with the keystroke
  13292. @param textCharacter the character that would be printed if someone typed
  13293. this keypress into a text editor. This value may be
  13294. null if the keypress is a non-printing character
  13295. @see getKeyCode, isKeyCode, getModifiers
  13296. */
  13297. KeyPress (const int keyCode,
  13298. const ModifierKeys& modifiers,
  13299. const juce_wchar textCharacter) throw();
  13300. /** Creates a keypress with a keyCode but no modifiers or text character.
  13301. */
  13302. KeyPress (const int keyCode) throw();
  13303. /** Creates a copy of another KeyPress. */
  13304. KeyPress (const KeyPress& other) throw();
  13305. /** Copies this KeyPress from another one. */
  13306. const KeyPress& operator= (const KeyPress& other) throw();
  13307. /** Compares two KeyPress objects. */
  13308. bool operator== (const KeyPress& other) const throw();
  13309. /** Compares two KeyPress objects. */
  13310. bool operator!= (const KeyPress& other) const throw();
  13311. /** Returns true if this is a valid KeyPress.
  13312. A null keypress can be created by the default constructor, in case it's
  13313. needed.
  13314. */
  13315. bool isValid() const throw() { return keyCode != 0; }
  13316. /** Returns the key code itself.
  13317. This will either be one of the special constants defined in this class,
  13318. or an 8-bit character code.
  13319. */
  13320. int getKeyCode() const throw() { return keyCode; }
  13321. /** Returns the key modifiers.
  13322. @see ModifierKeys
  13323. */
  13324. const ModifierKeys getModifiers() const throw() { return mods; }
  13325. /** Returns the character that is associated with this keypress.
  13326. This is the character that you'd expect to see printed if you press this
  13327. keypress in a text editor or similar component.
  13328. */
  13329. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  13330. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  13331. the modifiers.
  13332. The values for key codes can either be one of the special constants defined in
  13333. this class, or an 8-bit character code.
  13334. @see getKeyCode
  13335. */
  13336. bool isKeyCode (const int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  13337. /** Converts a textual key description to a KeyPress.
  13338. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  13339. This isn't designed to cope with any kind of input, but should be given the
  13340. strings that are created by the getTextDescription() method.
  13341. If the string can't be parsed, the object returned will be invalid.
  13342. @see getTextDescription
  13343. */
  13344. static const KeyPress createFromDescription (const String& textVersion) throw();
  13345. /** Creates a textual description of the key combination.
  13346. e.g. "CTRL + C" or "DELETE".
  13347. To store a keypress in a file, use this method, along with createFromDescription()
  13348. to retrieve it later.
  13349. */
  13350. const String getTextDescription() const throw();
  13351. /** Checks whether the user is currently holding down the keys that make up this
  13352. KeyPress.
  13353. Note that this will return false if any extra modifier keys are
  13354. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  13355. then it will be false.
  13356. */
  13357. bool isCurrentlyDown() const throw();
  13358. /** Checks whether a particular key is held down, irrespective of modifiers.
  13359. The values for key codes can either be one of the special constants defined in
  13360. this class, or an 8-bit character code.
  13361. */
  13362. static bool isKeyCurrentlyDown (int keyCode) throw();
  13363. // Key codes
  13364. //
  13365. // Note that the actual values of these are platform-specific and may change
  13366. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  13367. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  13368. //
  13369. static const int spaceKey; /**< key-code for the space bar */
  13370. static const int escapeKey; /**< key-code for the escape key */
  13371. static const int returnKey; /**< key-code for the return key*/
  13372. static const int tabKey; /**< key-code for the tab key*/
  13373. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  13374. static const int backspaceKey; /**< key-code for the backspace key */
  13375. static const int insertKey; /**< key-code for the insert key */
  13376. static const int upKey; /**< key-code for the cursor-up key */
  13377. static const int downKey; /**< key-code for the cursor-down key */
  13378. static const int leftKey; /**< key-code for the cursor-left key */
  13379. static const int rightKey; /**< key-code for the cursor-right key */
  13380. static const int pageUpKey; /**< key-code for the page-up key */
  13381. static const int pageDownKey; /**< key-code for the page-down key */
  13382. static const int homeKey; /**< key-code for the home key */
  13383. static const int endKey; /**< key-code for the end key */
  13384. static const int F1Key; /**< key-code for the F1 key */
  13385. static const int F2Key; /**< key-code for the F2 key */
  13386. static const int F3Key; /**< key-code for the F3 key */
  13387. static const int F4Key; /**< key-code for the F4 key */
  13388. static const int F5Key; /**< key-code for the F5 key */
  13389. static const int F6Key; /**< key-code for the F6 key */
  13390. static const int F7Key; /**< key-code for the F7 key */
  13391. static const int F8Key; /**< key-code for the F8 key */
  13392. static const int F9Key; /**< key-code for the F9 key */
  13393. static const int F10Key; /**< key-code for the F10 key */
  13394. static const int F11Key; /**< key-code for the F11 key */
  13395. static const int F12Key; /**< key-code for the F12 key */
  13396. static const int F13Key; /**< key-code for the F13 key */
  13397. static const int F14Key; /**< key-code for the F14 key */
  13398. static const int F15Key; /**< key-code for the F15 key */
  13399. static const int F16Key; /**< key-code for the F16 key */
  13400. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  13401. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  13402. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  13403. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  13404. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  13405. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  13406. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  13407. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  13408. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  13409. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  13410. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  13411. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  13412. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  13413. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  13414. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  13415. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  13416. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  13417. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  13418. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  13419. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  13420. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  13421. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  13422. juce_UseDebuggingNewOperator
  13423. private:
  13424. int keyCode;
  13425. ModifierKeys mods;
  13426. juce_wchar textCharacter;
  13427. };
  13428. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  13429. /********* End of inlined file: juce_KeyPress.h *********/
  13430. class Component;
  13431. /**
  13432. Receives callbacks when keys are pressed.
  13433. You can add a key listener to a component to be informed when that component
  13434. gets key events. See the Component::addListener method for more details.
  13435. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  13436. */
  13437. class JUCE_API KeyListener
  13438. {
  13439. public:
  13440. /** Destructor. */
  13441. virtual ~KeyListener() {}
  13442. /** Called to indicate that a key has been pressed.
  13443. If your implementation returns true, then the key event is considered to have
  13444. been consumed, and will not be passed on to any other components. If it returns
  13445. false, then the key will be passed to other components that might want to use it.
  13446. @param key the keystroke, including modifier keys
  13447. @param originatingComponent the component that received the key event
  13448. @see keyStateChanged, Component::keyPressed
  13449. */
  13450. virtual bool keyPressed (const KeyPress& key,
  13451. Component* originatingComponent) = 0;
  13452. /** Called when any key is pressed or released.
  13453. When this is called, classes that might be interested in
  13454. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  13455. check whether their key has changed.
  13456. If your implementation returns true, then the key event is considered to have
  13457. been consumed, and will not be passed on to any other components. If it returns
  13458. false, then the key will be passed to other components that might want to use it.
  13459. @param originatingComponent the component that received the key event
  13460. @param isKeyDown true if a key is being pressed, false if one is being released
  13461. @see KeyPress, Component::keyStateChanged
  13462. */
  13463. virtual bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  13464. };
  13465. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  13466. /********* End of inlined file: juce_KeyListener.h *********/
  13467. /********* Start of inlined file: juce_KeyboardFocusTraverser.h *********/
  13468. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13469. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13470. class Component;
  13471. /**
  13472. Controls the order in which focus moves between components.
  13473. The default algorithm used by this class to work out the order of traversal
  13474. is as follows:
  13475. - if two components both have an explicit focus order specified, then the
  13476. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  13477. method).
  13478. - any component with an explicit focus order greater than 0 comes before ones
  13479. that don't have an order specified.
  13480. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  13481. order.
  13482. If you need traversal in a more customised way, you can create a subclass
  13483. of KeyboardFocusTraverser that uses your own algorithm, and use
  13484. Component::createFocusTraverser() to create it.
  13485. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  13486. */
  13487. class JUCE_API KeyboardFocusTraverser
  13488. {
  13489. public:
  13490. KeyboardFocusTraverser();
  13491. /** Destructor. */
  13492. virtual ~KeyboardFocusTraverser();
  13493. /** Returns the component that should be given focus after the specified one
  13494. when moving "forwards".
  13495. The default implementation will return the next component which is to the
  13496. right of or below this one.
  13497. This may return 0 if there's no suitable candidate.
  13498. */
  13499. virtual Component* getNextComponent (Component* current);
  13500. /** Returns the component that should be given focus after the specified one
  13501. when moving "backwards".
  13502. The default implementation will return the next component which is to the
  13503. left of or above this one.
  13504. This may return 0 if there's no suitable candidate.
  13505. */
  13506. virtual Component* getPreviousComponent (Component* current);
  13507. /** Returns the component that should receive focus be default within the given
  13508. parent component.
  13509. The default implementation will just return the foremost child component that
  13510. wants focus.
  13511. This may return 0 if there's no suitable candidate.
  13512. */
  13513. virtual Component* getDefaultComponent (Component* parentComponent);
  13514. };
  13515. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  13516. /********* End of inlined file: juce_KeyboardFocusTraverser.h *********/
  13517. /********* Start of inlined file: juce_ImageEffectFilter.h *********/
  13518. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  13519. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  13520. /********* Start of inlined file: juce_Graphics.h *********/
  13521. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  13522. #define __JUCE_GRAPHICS_JUCEHEADER__
  13523. /********* Start of inlined file: juce_Font.h *********/
  13524. #ifndef __JUCE_FONT_JUCEHEADER__
  13525. #define __JUCE_FONT_JUCEHEADER__
  13526. /********* Start of inlined file: juce_Typeface.h *********/
  13527. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  13528. #define __JUCE_TYPEFACE_JUCEHEADER__
  13529. /********* Start of inlined file: juce_Path.h *********/
  13530. #ifndef __JUCE_PATH_JUCEHEADER__
  13531. #define __JUCE_PATH_JUCEHEADER__
  13532. /********* Start of inlined file: juce_AffineTransform.h *********/
  13533. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13534. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13535. /**
  13536. Represents a 2D affine-transformation matrix.
  13537. An affine transformation is a transformation such as a rotation, scale, shear,
  13538. resize or translation.
  13539. These are used for various 2D transformation tasks, e.g. with Path objects.
  13540. @see Path, Point, Line
  13541. */
  13542. class JUCE_API AffineTransform
  13543. {
  13544. public:
  13545. /** Creates an identity transform. */
  13546. AffineTransform() throw();
  13547. /** Creates a copy of another transform. */
  13548. AffineTransform (const AffineTransform& other) throw();
  13549. /** Creates a transform from a set of raw matrix values.
  13550. The resulting matrix is:
  13551. (mat00 mat01 mat02)
  13552. (mat10 mat11 mat12)
  13553. ( 0 0 1 )
  13554. */
  13555. AffineTransform (const float mat00, const float mat01, const float mat02,
  13556. const float mat10, const float mat11, const float mat12) throw();
  13557. /** Copies from another AffineTransform object */
  13558. const AffineTransform& operator= (const AffineTransform& other) throw();
  13559. /** Compares two transforms. */
  13560. bool operator== (const AffineTransform& other) const throw();
  13561. /** Compares two transforms. */
  13562. bool operator!= (const AffineTransform& other) const throw();
  13563. /** A ready-to-use identity transform, which you can use to append other
  13564. transformations to.
  13565. e.g. @code
  13566. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  13567. .scaled (2.0f);
  13568. @endcode
  13569. */
  13570. static const AffineTransform identity;
  13571. /** Transforms a 2D co-ordinate using this matrix. */
  13572. void transformPoint (float& x,
  13573. float& y) const throw();
  13574. /** Transforms a 2D co-ordinate using this matrix. */
  13575. void transformPoint (double& x,
  13576. double& y) const throw();
  13577. /** Returns a new transform which is the same as this one followed by a translation. */
  13578. const AffineTransform translated (const float deltaX,
  13579. const float deltaY) const throw();
  13580. /** Returns a new transform which is a translation. */
  13581. static const AffineTransform translation (const float deltaX,
  13582. const float deltaY) throw();
  13583. /** Returns a transform which is the same as this one followed by a rotation.
  13584. The rotation is specified by a number of radians to rotate clockwise, centred around
  13585. the origin (0, 0).
  13586. */
  13587. const AffineTransform rotated (const float angleInRadians) const throw();
  13588. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  13589. The rotation is specified by a number of radians to rotate clockwise, centred around
  13590. the co-ordinates passed in.
  13591. */
  13592. const AffineTransform rotated (const float angleInRadians,
  13593. const float pivotX,
  13594. const float pivotY) const throw();
  13595. /** Returns a new transform which is a rotation about (0, 0). */
  13596. static const AffineTransform rotation (const float angleInRadians) throw();
  13597. /** Returns a new transform which is a rotation about a given point. */
  13598. static const AffineTransform rotation (const float angleInRadians,
  13599. const float pivotX,
  13600. const float pivotY) throw();
  13601. /** Returns a transform which is the same as this one followed by a re-scaling.
  13602. The scaling is centred around the origin (0, 0).
  13603. */
  13604. const AffineTransform scaled (const float factorX,
  13605. const float factorY) const throw();
  13606. /** Returns a new transform which is a re-scale about the origin. */
  13607. static const AffineTransform scale (const float factorX,
  13608. const float factorY) throw();
  13609. /** Returns a transform which is the same as this one followed by a shear.
  13610. The shear is centred around the origin (0, 0).
  13611. */
  13612. const AffineTransform sheared (const float shearX,
  13613. const float shearY) const throw();
  13614. /** Returns a matrix which is the inverse operation of this one.
  13615. Some matrices don't have an inverse - in this case, the method will just return
  13616. an identity transform.
  13617. */
  13618. const AffineTransform inverted() const throw();
  13619. /** Returns the result of concatenating another transformation after this one. */
  13620. const AffineTransform followedBy (const AffineTransform& other) const throw();
  13621. /** Returns true if this transform has no effect on points. */
  13622. bool isIdentity() const throw();
  13623. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  13624. bool isSingularity() const throw();
  13625. /** Returns true if the transform only translates, and doesn't scale or rotate the
  13626. points. */
  13627. bool isOnlyTranslation() const throw();
  13628. /** If this transform is only a translation, this returns the X offset.
  13629. @see isOnlyTranslation
  13630. */
  13631. float getTranslationX() const throw() { return mat02; }
  13632. /** If this transform is only a translation, this returns the X offset.
  13633. @see isOnlyTranslation
  13634. */
  13635. float getTranslationY() const throw() { return mat12; }
  13636. juce_UseDebuggingNewOperator
  13637. /* The transform matrix is:
  13638. (mat00 mat01 mat02)
  13639. (mat10 mat11 mat12)
  13640. ( 0 0 1 )
  13641. */
  13642. float mat00, mat01, mat02;
  13643. float mat10, mat11, mat12;
  13644. private:
  13645. const AffineTransform followedBy (const float mat00, const float mat01, const float mat02,
  13646. const float mat10, const float mat11, const float mat12) const throw();
  13647. };
  13648. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  13649. /********* End of inlined file: juce_AffineTransform.h *********/
  13650. /********* Start of inlined file: juce_Point.h *********/
  13651. #ifndef __JUCE_POINT_JUCEHEADER__
  13652. #define __JUCE_POINT_JUCEHEADER__
  13653. /**
  13654. A pair of (x, y) co-ordinates.
  13655. Uses 32-bit floating point accuracy.
  13656. @see Line, Path, AffineTransform
  13657. */
  13658. class JUCE_API Point
  13659. {
  13660. public:
  13661. /** Creates a point with co-ordinates (0, 0). */
  13662. Point() throw();
  13663. /** Creates a copy of another point. */
  13664. Point (const Point& other) throw();
  13665. /** Creates a point from an (x, y) position. */
  13666. Point (const float x, const float y) throw();
  13667. /** Copies this point from another one.
  13668. @see setXY
  13669. */
  13670. const Point& operator= (const Point& other) throw();
  13671. /** Destructor. */
  13672. ~Point() throw();
  13673. /** Returns the point's x co-ordinate. */
  13674. inline float getX() const throw() { return x; }
  13675. /** Returns the point's y co-ordinate. */
  13676. inline float getY() const throw() { return y; }
  13677. /** Changes the point's x and y co-ordinates. */
  13678. void setXY (const float x,
  13679. const float y) throw();
  13680. /** Uses a transform to change the point's co-ordinates.
  13681. @see AffineTransform::transformPoint
  13682. */
  13683. void applyTransform (const AffineTransform& transform) throw();
  13684. juce_UseDebuggingNewOperator
  13685. private:
  13686. float x, y;
  13687. };
  13688. #endif // __JUCE_POINT_JUCEHEADER__
  13689. /********* End of inlined file: juce_Point.h *********/
  13690. /********* Start of inlined file: juce_Rectangle.h *********/
  13691. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  13692. #define __JUCE_RECTANGLE_JUCEHEADER__
  13693. /**
  13694. A rectangle, specified using integer co-ordinates.
  13695. @see RectangleList, Path, Line, Point
  13696. */
  13697. class JUCE_API Rectangle
  13698. {
  13699. public:
  13700. /** Creates a rectangle of zero size.
  13701. The default co-ordinates will be (0, 0, 0, 0).
  13702. */
  13703. Rectangle() throw();
  13704. /** Creates a copy of another rectangle. */
  13705. Rectangle (const Rectangle& other) throw();
  13706. /** Creates a rectangle with a given position and size. */
  13707. Rectangle (const int x, const int y,
  13708. const int width, const int height) throw();
  13709. /** Creates a rectangle with a given size, and a position of (0, 0). */
  13710. Rectangle (const int width, const int height) throw();
  13711. /** Destructor. */
  13712. ~Rectangle() throw();
  13713. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  13714. inline int getX() const throw() { return x; }
  13715. /** Returns the y co-ordinate of the rectangle's top edge. */
  13716. inline int getY() const throw() { return y; }
  13717. /** Returns the width of the rectangle. */
  13718. inline int getWidth() const throw() { return w; }
  13719. /** Returns the height of the rectangle. */
  13720. inline int getHeight() const throw() { return h; }
  13721. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  13722. inline int getRight() const throw() { return x + w; }
  13723. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  13724. inline int getBottom() const throw() { return y + h; }
  13725. /** Returns the x co-ordinate of the rectangle's centre. */
  13726. inline int getCentreX() const throw() { return x + (w >> 1); }
  13727. /** Returns the y co-ordinate of the rectangle's centre. */
  13728. inline int getCentreY() const throw() { return y + (h >> 1); }
  13729. /** Returns true if the rectangle's width and height are both zero or less */
  13730. bool isEmpty() const throw();
  13731. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  13732. void setPosition (const int x, const int y) throw();
  13733. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  13734. void setSize (const int w, const int h) throw();
  13735. /** Changes all the rectangle's co-ordinates. */
  13736. void setBounds (const int newX, const int newY,
  13737. const int newWidth, const int newHeight) throw();
  13738. /** Changes the rectangle's width */
  13739. void setWidth (const int newWidth) throw();
  13740. /** Changes the rectangle's height */
  13741. void setHeight (const int newHeight) throw();
  13742. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  13743. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  13744. */
  13745. void setLeft (const int newLeft) throw();
  13746. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  13747. If the y is moved to be below the current bottom edge, the height will be set to zero.
  13748. */
  13749. void setTop (const int newTop) throw();
  13750. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  13751. If the new right is below the current X value, the X will be pushed down to match it.
  13752. @see getRight
  13753. */
  13754. void setRight (const int newRight) throw();
  13755. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  13756. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  13757. @see getBottom
  13758. */
  13759. void setBottom (const int newBottom) throw();
  13760. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  13761. void translate (const int deltaX,
  13762. const int deltaY) throw();
  13763. /** Returns a rectangle which is the same as this one moved by a given amount. */
  13764. const Rectangle translated (const int deltaX,
  13765. const int deltaY) const throw();
  13766. /** Expands the rectangle by a given amount.
  13767. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13768. @see expanded, reduce, reduced
  13769. */
  13770. void expand (const int deltaX,
  13771. const int deltaY) throw();
  13772. /** Returns a rectangle that is larger than this one by a given amount.
  13773. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  13774. @see expand, reduce, reduced
  13775. */
  13776. const Rectangle expanded (const int deltaX,
  13777. const int deltaY) const throw();
  13778. /** Shrinks the rectangle by a given amount.
  13779. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13780. @see reduced, expand, expanded
  13781. */
  13782. void reduce (const int deltaX,
  13783. const int deltaY) throw();
  13784. /** Returns a rectangle that is smaller than this one by a given amount.
  13785. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  13786. @see reduce, expand, expanded
  13787. */
  13788. const Rectangle reduced (const int deltaX,
  13789. const int deltaY) const throw();
  13790. /** Returns true if the two rectangles are identical. */
  13791. bool operator== (const Rectangle& other) const throw();
  13792. /** Returns true if the two rectangles are not identical. */
  13793. bool operator!= (const Rectangle& other) const throw();
  13794. /** Returns true if this co-ordinate is inside the rectangle. */
  13795. bool contains (const int x, const int y) const throw();
  13796. /** Returns true if this other rectangle is completely inside this one. */
  13797. bool contains (const Rectangle& other) const throw();
  13798. /** Returns true if any part of another rectangle overlaps this one. */
  13799. bool intersects (const Rectangle& other) const throw();
  13800. /** Returns the region that is the overlap between this and another rectangle.
  13801. If the two rectangles don't overlap, the rectangle returned will be empty.
  13802. */
  13803. const Rectangle getIntersection (const Rectangle& other) const throw();
  13804. /** Clips a rectangle so that it lies only within this one.
  13805. This is a non-static version of intersectRectangles().
  13806. Returns false if the two regions didn't overlap.
  13807. */
  13808. bool intersectRectangle (int& x, int& y, int& w, int& h) const throw();
  13809. /** Returns the smallest rectangle that contains both this one and the one
  13810. passed-in.
  13811. */
  13812. const Rectangle getUnion (const Rectangle& other) const throw();
  13813. /** If this rectangle merged with another one results in a simple rectangle, this
  13814. will set this rectangle to the result, and return true.
  13815. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13816. or if they form a complex region.
  13817. */
  13818. bool enlargeIfAdjacent (const Rectangle& other) throw();
  13819. /** If after removing another rectangle from this one the result is a simple rectangle,
  13820. this will set this object's bounds to be the result, and return true.
  13821. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  13822. or if removing the other one would form a complex region.
  13823. */
  13824. bool reduceIfPartlyContainedIn (const Rectangle& other) throw();
  13825. /** Static utility to intersect two sets of rectangular co-ordinates.
  13826. Returns false if the two regions didn't overlap.
  13827. @see intersectRectangle
  13828. */
  13829. static bool intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  13830. int x2, int y2, int w2, int h2) throw();
  13831. /** Creates a string describing this rectangle.
  13832. The string will be of the form "x y width height", e.g. "100 100 400 200".
  13833. Coupled with the fromString() method, this is very handy for things like
  13834. storing rectangles (particularly component positions) in XML attributes.
  13835. @see fromString
  13836. */
  13837. const String toString() const throw();
  13838. /** Parses a string containing a rectangle's details.
  13839. The string should contain 4 integer tokens, in the form "x y width height". They
  13840. can be comma or whitespace separated.
  13841. This method is intended to go with the toString() method, to form an easy way
  13842. of saving/loading rectangles as strings.
  13843. @see toString
  13844. */
  13845. static const Rectangle fromString (const String& stringVersion);
  13846. juce_UseDebuggingNewOperator
  13847. private:
  13848. friend class RectangleList;
  13849. int x, y, w, h;
  13850. };
  13851. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  13852. /********* End of inlined file: juce_Rectangle.h *********/
  13853. /********* Start of inlined file: juce_Justification.h *********/
  13854. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  13855. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  13856. /**
  13857. Represents a type of justification to be used when positioning graphical items.
  13858. e.g. it indicates whether something should be placed top-left, top-right,
  13859. centred, etc.
  13860. It is used in various places wherever this kind of information is needed.
  13861. */
  13862. class JUCE_API Justification
  13863. {
  13864. public:
  13865. /** Creates a Justification object using a combination of flags. */
  13866. inline Justification (const int flags_) throw() : flags (flags_) {}
  13867. /** Creates a copy of another Justification object. */
  13868. Justification (const Justification& other) throw();
  13869. /** Copies another Justification object. */
  13870. const Justification& operator= (const Justification& other) throw();
  13871. /** Returns the raw flags that are set for this Justification object. */
  13872. inline int getFlags() const throw() { return flags; }
  13873. /** Tests a set of flags for this object.
  13874. @returns true if any of the flags passed in are set on this object.
  13875. */
  13876. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  13877. /** Returns just the flags from this object that deal with vertical layout. */
  13878. int getOnlyVerticalFlags() const throw();
  13879. /** Returns just the flags from this object that deal with horizontal layout. */
  13880. int getOnlyHorizontalFlags() const throw();
  13881. /** Adjusts the position of a rectangle to fit it into a space.
  13882. The (x, y) position of the rectangle will be updated to position it inside the
  13883. given space according to the justification flags.
  13884. */
  13885. void applyToRectangle (int& x, int& y,
  13886. const int w, const int h,
  13887. const int spaceX, const int spaceY,
  13888. const int spaceW, const int spaceH) const throw();
  13889. /** Flag values that can be combined and used in the constructor. */
  13890. enum
  13891. {
  13892. /** Indicates that the item should be aligned against the left edge of the available space. */
  13893. left = 1,
  13894. /** Indicates that the item should be aligned against the right edge of the available space. */
  13895. right = 2,
  13896. /** Indicates that the item should be placed in the centre between the left and right
  13897. sides of the available space. */
  13898. horizontallyCentred = 4,
  13899. /** Indicates that the item should be aligned against the top edge of the available space. */
  13900. top = 8,
  13901. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  13902. bottom = 16,
  13903. /** Indicates that the item should be placed in the centre between the top and bottom
  13904. sides of the available space. */
  13905. verticallyCentred = 32,
  13906. /** Indicates that lines of text should be spread out to fill the maximum width
  13907. available, so that both margins are aligned vertically.
  13908. */
  13909. horizontallyJustified = 64,
  13910. /** Indicates that the item should be centred vertically and horizontally.
  13911. This is equivalent to (horizontallyCentred | verticallyCentred)
  13912. */
  13913. centred = 36,
  13914. /** Indicates that the item should be centred vertically but placed on the left hand side.
  13915. This is equivalent to (left | verticallyCentred)
  13916. */
  13917. centredLeft = 33,
  13918. /** Indicates that the item should be centred vertically but placed on the right hand side.
  13919. This is equivalent to (right | verticallyCentred)
  13920. */
  13921. centredRight = 34,
  13922. /** Indicates that the item should be centred horizontally and placed at the top.
  13923. This is equivalent to (horizontallyCentred | top)
  13924. */
  13925. centredTop = 12,
  13926. /** Indicates that the item should be centred horizontally and placed at the bottom.
  13927. This is equivalent to (horizontallyCentred | bottom)
  13928. */
  13929. centredBottom = 20,
  13930. /** Indicates that the item should be placed in the top-left corner.
  13931. This is equivalent to (left | top)
  13932. */
  13933. topLeft = 9,
  13934. /** Indicates that the item should be placed in the top-right corner.
  13935. This is equivalent to (right | top)
  13936. */
  13937. topRight = 10,
  13938. /** Indicates that the item should be placed in the bottom-left corner.
  13939. This is equivalent to (left | bottom)
  13940. */
  13941. bottomLeft = 17,
  13942. /** Indicates that the item should be placed in the bottom-left corner.
  13943. This is equivalent to (right | bottom)
  13944. */
  13945. bottomRight = 18
  13946. };
  13947. private:
  13948. int flags;
  13949. };
  13950. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  13951. /********* End of inlined file: juce_Justification.h *********/
  13952. /********* Start of inlined file: juce_EdgeTable.h *********/
  13953. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  13954. #define __JUCE_EDGETABLE_JUCEHEADER__
  13955. class Path;
  13956. class RectangleList;
  13957. class Image;
  13958. /**
  13959. A table of horizontal scan-line segments - used for rasterising Paths.
  13960. @see Path, Graphics
  13961. */
  13962. class JUCE_API EdgeTable
  13963. {
  13964. public:
  13965. /** Creates an edge table containing a path.
  13966. A table is created with a fixed vertical range, and only sections of the path
  13967. which lie within this range will be added to the table.
  13968. @param clipLimits only the region of the path that lies within this area will be added
  13969. @param pathToAdd the path to add to the table
  13970. @param transform a transform to apply to the path being added
  13971. */
  13972. EdgeTable (const Rectangle& clipLimits,
  13973. const Path& pathToAdd,
  13974. const AffineTransform& transform) throw();
  13975. /** Creates an edge table containing a rectangle.
  13976. */
  13977. EdgeTable (const Rectangle& rectangleToAdd) throw();
  13978. /** Creates an edge table containing a rectangle list.
  13979. */
  13980. EdgeTable (const RectangleList& rectanglesToAdd) throw();
  13981. /** Creates an edge table containing a rectangle.
  13982. */
  13983. EdgeTable (const float x, const float y,
  13984. const float w, const float h) throw();
  13985. /** Creates a copy of another edge table. */
  13986. EdgeTable (const EdgeTable& other) throw();
  13987. /** Copies from another edge table. */
  13988. const EdgeTable& operator= (const EdgeTable& other) throw();
  13989. /** Destructor. */
  13990. ~EdgeTable() throw();
  13991. void clipToRectangle (const Rectangle& r) throw();
  13992. void excludeRectangle (const Rectangle& r) throw();
  13993. void clipToEdgeTable (const EdgeTable& other);
  13994. void clipLineToMask (int x, int y, uint8* mask, int maskStride, int numPixels) throw();
  13995. bool isEmpty() throw();
  13996. const Rectangle& getMaximumBounds() const throw() { return bounds; }
  13997. void translate (float dx, int dy) throw();
  13998. /** Reduces the amount of space the table has allocated.
  13999. This will shrink the table down to use as little memory as possible - useful for
  14000. read-only tables that get stored and re-used for rendering.
  14001. */
  14002. void optimiseTable() throw();
  14003. /** Iterates the lines in the table, for rendering.
  14004. This function will iterate each line in the table, and call a user-defined class
  14005. to render each pixel or continuous line of pixels that the table contains.
  14006. @param iterationCallback this templated class must contain the following methods:
  14007. @code
  14008. inline void setEdgeTableYPos (int y);
  14009. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  14010. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  14011. @endcode
  14012. (these don't necessarily have to be 'const', but it might help it go faster)
  14013. */
  14014. template <class EdgeTableIterationCallback>
  14015. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  14016. {
  14017. const int* lineStart = table;
  14018. for (int y = 0; y < bounds.getHeight(); ++y)
  14019. {
  14020. const int* line = lineStart;
  14021. lineStart += lineStrideElements;
  14022. int numPoints = line[0];
  14023. if (--numPoints > 0)
  14024. {
  14025. int x = *++line;
  14026. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  14027. int levelAccumulator = 0;
  14028. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  14029. while (--numPoints >= 0)
  14030. {
  14031. const int level = *++line;
  14032. jassert (((unsigned int) level) < (unsigned int) 256);
  14033. const int endX = *++line;
  14034. jassert (endX >= x);
  14035. const int endOfRun = (endX >> 8);
  14036. if (endOfRun == (x >> 8))
  14037. {
  14038. // small segment within the same pixel, so just save it for the next
  14039. // time round..
  14040. levelAccumulator += (endX - x) * level;
  14041. }
  14042. else
  14043. {
  14044. // plot the fist pixel of this segment, including any accumulated
  14045. // levels from smaller segments that haven't been drawn yet
  14046. levelAccumulator += (0xff - (x & 0xff)) * level;
  14047. levelAccumulator >>= 8;
  14048. x >>= 8;
  14049. if (levelAccumulator > 0)
  14050. {
  14051. if (levelAccumulator >> 8)
  14052. levelAccumulator = 0xff;
  14053. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  14054. }
  14055. // if there's a run of similar pixels, do it all in one go..
  14056. if (level > 0)
  14057. {
  14058. jassert (endOfRun <= bounds.getRight());
  14059. const int numPix = endOfRun - ++x;
  14060. if (numPix > 0)
  14061. iterationCallback.handleEdgeTableLine (x, numPix, level);
  14062. }
  14063. // save the bit at the end to be drawn next time round the loop.
  14064. levelAccumulator = (endX & 0xff) * level;
  14065. }
  14066. x = endX;
  14067. }
  14068. if (levelAccumulator > 0)
  14069. {
  14070. levelAccumulator >>= 8;
  14071. if (levelAccumulator >> 8)
  14072. levelAccumulator = 0xff;
  14073. x >>= 8;
  14074. jassert (x >= bounds.getX() && x < bounds.getRight());
  14075. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  14076. }
  14077. }
  14078. }
  14079. }
  14080. juce_UseDebuggingNewOperator
  14081. private:
  14082. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  14083. HeapBlock <int> table;
  14084. Rectangle bounds;
  14085. int maxEdgesPerLine, lineStrideElements;
  14086. bool needToCheckEmptinesss;
  14087. void addEdgePoint (const int x, const int y, const int winding) throw();
  14088. void remapTableForNumEdges (const int newNumEdgesPerLine) throw();
  14089. void intersectWithEdgeTableLine (const int y, const int* otherLine) throw();
  14090. void sanitiseLevels (const bool useNonZeroWinding) throw();
  14091. };
  14092. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  14093. /********* End of inlined file: juce_EdgeTable.h *********/
  14094. class Image;
  14095. /**
  14096. A path is a sequence of lines and curves that may either form a closed shape
  14097. or be open-ended.
  14098. To use a path, you can create an empty one, then add lines and curves to it
  14099. to create shapes, then it can be rendered by a Graphics context or used
  14100. for geometric operations.
  14101. e.g. @code
  14102. Path myPath;
  14103. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  14104. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  14105. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  14106. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  14107. // add an ellipse as well, which will form a second sub-path within the path..
  14108. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  14109. // double the width of the whole thing..
  14110. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  14111. // and draw it to a graphics context with a 5-pixel thick outline.
  14112. g.strokePath (myPath, PathStrokeType (5.0f));
  14113. @endcode
  14114. A path object can actually contain multiple sub-paths, which may themselves
  14115. be open or closed.
  14116. @see PathFlatteningIterator, PathStrokeType, Graphics
  14117. */
  14118. class JUCE_API Path
  14119. {
  14120. public:
  14121. /** Creates an empty path. */
  14122. Path() throw();
  14123. /** Creates a copy of another path. */
  14124. Path (const Path& other) throw();
  14125. /** Destructor. */
  14126. ~Path() throw();
  14127. /** Copies this path from another one. */
  14128. const Path& operator= (const Path& other) throw();
  14129. /** Returns true if the path doesn't contain any lines or curves. */
  14130. bool isEmpty() const throw();
  14131. /** Returns the smallest rectangle that contains all points within the path.
  14132. */
  14133. void getBounds (float& x, float& y,
  14134. float& w, float& h) const throw();
  14135. /** Returns the smallest rectangle that contains all points within the path
  14136. after it's been transformed with the given tranasform matrix.
  14137. */
  14138. void getBoundsTransformed (const AffineTransform& transform,
  14139. float& x, float& y,
  14140. float& w, float& h) const throw();
  14141. /** Checks whether a point lies within the path.
  14142. This is only relevent for closed paths (see closeSubPath()), and
  14143. may produce false results if used on a path which has open sub-paths.
  14144. The path's winding rule is taken into account by this method.
  14145. The tolerence parameter is passed to the PathFlatteningIterator that
  14146. is used to trace the path - for more info about it, see the notes for
  14147. the PathFlatteningIterator constructor.
  14148. @see closeSubPath, setUsingNonZeroWinding
  14149. */
  14150. bool contains (const float x,
  14151. const float y,
  14152. const float tolerence = 10.0f) const throw();
  14153. /** Checks whether a line crosses the path.
  14154. This will return positive if the line crosses any of the paths constituent
  14155. lines or curves. It doesn't take into account whether the line is inside
  14156. or outside the path, or whether the path is open or closed.
  14157. The tolerence parameter is passed to the PathFlatteningIterator that
  14158. is used to trace the path - for more info about it, see the notes for
  14159. the PathFlatteningIterator constructor.
  14160. */
  14161. bool intersectsLine (const float x1, const float y1,
  14162. const float x2, const float y2,
  14163. const float tolerence = 10.0f) throw();
  14164. /** Removes all lines and curves, resetting the path completely. */
  14165. void clear() throw();
  14166. /** Begins a new subpath with a given starting position.
  14167. This will move the path's current position to the co-ordinates passed in and
  14168. make it ready to draw lines or curves starting from this position.
  14169. After adding whatever lines and curves are needed, you can either
  14170. close the current sub-path using closeSubPath() or call startNewSubPath()
  14171. to move to a new sub-path, leaving the old one open-ended.
  14172. @see lineTo, quadraticTo, cubicTo, closeSubPath
  14173. */
  14174. void startNewSubPath (const float startX,
  14175. const float startY) throw();
  14176. /** Closes a the current sub-path with a line back to its start-point.
  14177. When creating a closed shape such as a triangle, don't use 3 lineTo()
  14178. calls - instead use two lineTo() calls, followed by a closeSubPath()
  14179. to join the final point back to the start.
  14180. This ensures that closes shapes are recognised as such, and this is
  14181. important for tasks like drawing strokes, which needs to know whether to
  14182. draw end-caps or not.
  14183. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  14184. */
  14185. void closeSubPath() throw();
  14186. /** Adds a line from the shape's last position to a new end-point.
  14187. This will connect the end-point of the last line or curve that was added
  14188. to a new point, using a straight line.
  14189. See the class description for an example of how to add lines and curves to a path.
  14190. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  14191. */
  14192. void lineTo (const float endX,
  14193. const float endY) throw();
  14194. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  14195. This will connect the end-point of the last line or curve that was added
  14196. to a new point, using a quadratic spline with one control-point.
  14197. See the class description for an example of how to add lines and curves to a path.
  14198. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  14199. */
  14200. void quadraticTo (const float controlPointX,
  14201. const float controlPointY,
  14202. const float endPointX,
  14203. const float endPointY) throw();
  14204. /** Adds a cubic bezier curve from the shape's last position to a new position.
  14205. This will connect the end-point of the last line or curve that was added
  14206. to a new point, using a cubic spline with two control-points.
  14207. See the class description for an example of how to add lines and curves to a path.
  14208. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  14209. */
  14210. void cubicTo (const float controlPoint1X,
  14211. const float controlPoint1Y,
  14212. const float controlPoint2X,
  14213. const float controlPoint2Y,
  14214. const float endPointX,
  14215. const float endPointY) throw();
  14216. /** Returns the last point that was added to the path by one of the drawing methods.
  14217. */
  14218. const Point getCurrentPosition() const;
  14219. /** Adds a rectangle to the path.
  14220. The rectangle is added as a new sub-path. (Any currently open paths will be
  14221. left open).
  14222. @see addRoundedRectangle, addTriangle
  14223. */
  14224. void addRectangle (const float x, const float y,
  14225. const float w, const float h) throw();
  14226. /** Adds a rectangle to the path.
  14227. The rectangle is added as a new sub-path. (Any currently open paths will be
  14228. left open).
  14229. @see addRoundedRectangle, addTriangle
  14230. */
  14231. void addRectangle (const Rectangle& rectangle) throw();
  14232. /** Adds a rectangle with rounded corners to the path.
  14233. The rectangle is added as a new sub-path. (Any currently open paths will be
  14234. left open).
  14235. @see addRectangle, addTriangle
  14236. */
  14237. void addRoundedRectangle (const float x, const float y,
  14238. const float w, const float h,
  14239. float cornerSize) throw();
  14240. /** Adds a rectangle with rounded corners to the path.
  14241. The rectangle is added as a new sub-path. (Any currently open paths will be
  14242. left open).
  14243. @see addRectangle, addTriangle
  14244. */
  14245. void addRoundedRectangle (const float x, const float y,
  14246. const float w, const float h,
  14247. float cornerSizeX,
  14248. float cornerSizeY) throw();
  14249. /** Adds a triangle to the path.
  14250. The triangle is added as a new closed sub-path. (Any currently open paths will be
  14251. left open).
  14252. Note that whether the vertices are specified in clockwise or anticlockwise
  14253. order will affect how the triangle is filled when it overlaps other
  14254. shapes (the winding order setting will affect this of course).
  14255. */
  14256. void addTriangle (const float x1, const float y1,
  14257. const float x2, const float y2,
  14258. const float x3, const float y3) throw();
  14259. /** Adds a quadrilateral to the path.
  14260. The quad is added as a new closed sub-path. (Any currently open paths will be
  14261. left open).
  14262. Note that whether the vertices are specified in clockwise or anticlockwise
  14263. order will affect how the quad is filled when it overlaps other
  14264. shapes (the winding order setting will affect this of course).
  14265. */
  14266. void addQuadrilateral (const float x1, const float y1,
  14267. const float x2, const float y2,
  14268. const float x3, const float y3,
  14269. const float x4, const float y4) throw();
  14270. /** Adds an ellipse to the path.
  14271. The shape is added as a new sub-path. (Any currently open paths will be
  14272. left open).
  14273. @see addArc
  14274. */
  14275. void addEllipse (const float x, const float y,
  14276. const float width, const float height) throw();
  14277. /** Adds an elliptical arc to the current path.
  14278. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  14279. or anti-clockwise according to whether the end angle is greater than the start. This means
  14280. that sometimes you may need to use values greater than 2*Pi for the end angle.
  14281. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  14282. @param y the top edge of the rectangle in which the elliptical outline fits
  14283. @param width the width of the rectangle in which the elliptical outline fits
  14284. @param height the height of the rectangle in which the elliptical outline fits
  14285. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  14286. top-centre of the ellipse)
  14287. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  14288. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  14289. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  14290. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  14291. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  14292. it will be added to the current sub-path, continuing from the current postition
  14293. @see addCentredArc, arcTo, addPieSegment, addEllipse
  14294. */
  14295. void addArc (const float x, const float y,
  14296. const float width, const float height,
  14297. const float fromRadians,
  14298. const float toRadians,
  14299. const bool startAsNewSubPath = false) throw();
  14300. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  14301. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  14302. or anti-clockwise according to whether the end angle is greater than the start. This means
  14303. that sometimes you may need to use values greater than 2*Pi for the end angle.
  14304. @param centreX the centre x of the ellipse
  14305. @param centreY the centre y of the ellipse
  14306. @param radiusX the horizontal radius of the ellipse
  14307. @param radiusY the vertical radius of the ellipse
  14308. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  14309. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  14310. top-centre of the ellipse)
  14311. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  14312. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  14313. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  14314. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  14315. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  14316. it will be added to the current sub-path, continuing from the current postition
  14317. @see addArc, arcTo
  14318. */
  14319. void addCentredArc (const float centreX, const float centreY,
  14320. const float radiusX, const float radiusY,
  14321. const float rotationOfEllipse,
  14322. const float fromRadians,
  14323. const float toRadians,
  14324. const bool startAsNewSubPath = false) throw();
  14325. /** Adds a "pie-chart" shape to the path.
  14326. The shape is added as a new sub-path. (Any currently open paths will be
  14327. left open).
  14328. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  14329. or anti-clockwise according to whether the end angle is greater than the start. This means
  14330. that sometimes you may need to use values greater than 2*Pi for the end angle.
  14331. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  14332. @param y the top edge of the rectangle in which the elliptical outline fits
  14333. @param width the width of the rectangle in which the elliptical outline fits
  14334. @param height the height of the rectangle in which the elliptical outline fits
  14335. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  14336. top-centre of the ellipse)
  14337. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  14338. top-centre of the ellipse)
  14339. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  14340. ellipse at its centre, where this value indicates the inner ellipse's size with
  14341. respect to the outer one.
  14342. @see addArc
  14343. */
  14344. void addPieSegment (const float x, const float y,
  14345. const float width, const float height,
  14346. const float fromRadians,
  14347. const float toRadians,
  14348. const float innerCircleProportionalSize);
  14349. /** Adds a line with a specified thickness.
  14350. The line is added as a new closed sub-path. (Any currently open paths will be
  14351. left open).
  14352. @see addArrow
  14353. */
  14354. void addLineSegment (const float startX, const float startY,
  14355. const float endX, const float endY,
  14356. float lineThickness) throw();
  14357. /** Adds a line with an arrowhead on the end.
  14358. The arrow is added as a new closed sub-path. (Any currently open paths will be
  14359. left open).
  14360. */
  14361. void addArrow (const float startX, const float startY,
  14362. const float endX, const float endY,
  14363. float lineThickness,
  14364. float arrowheadWidth,
  14365. float arrowheadLength) throw();
  14366. /** Adds a star shape to the path.
  14367. */
  14368. void addStar (const float centreX,
  14369. const float centreY,
  14370. const int numberOfPoints,
  14371. const float innerRadius,
  14372. const float outerRadius,
  14373. const float startAngle = 0.0f);
  14374. /** Adds a speech-bubble shape to the path.
  14375. @param bodyX the left of the main body area of the bubble
  14376. @param bodyY the top of the main body area of the bubble
  14377. @param bodyW the width of the main body area of the bubble
  14378. @param bodyH the height of the main body area of the bubble
  14379. @param cornerSize the amount by which to round off the corners of the main body rectangle
  14380. @param arrowTipX the x position that the tip of the arrow should connect to
  14381. @param arrowTipY the y position that the tip of the arrow should connect to
  14382. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  14383. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  14384. arrow's base should be - this is a proportional distance between 0 and 1.0
  14385. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  14386. */
  14387. void addBubble (float bodyX, float bodyY,
  14388. float bodyW, float bodyH,
  14389. float cornerSize,
  14390. float arrowTipX,
  14391. float arrowTipY,
  14392. int whichSide,
  14393. float arrowPositionAlongEdgeProportional,
  14394. float arrowWidth);
  14395. /** Adds another path to this one.
  14396. The new path is added as a new sub-path. (Any currently open paths in this
  14397. path will be left open).
  14398. @param pathToAppend the path to add
  14399. */
  14400. void addPath (const Path& pathToAppend) throw();
  14401. /** Adds another path to this one, transforming it on the way in.
  14402. The new path is added as a new sub-path, its points being transformed by the given
  14403. matrix before being added.
  14404. @param pathToAppend the path to add
  14405. @param transformToApply an optional transform to apply to the incoming vertices
  14406. */
  14407. void addPath (const Path& pathToAppend,
  14408. const AffineTransform& transformToApply) throw();
  14409. /** Swaps the contents of this path with another one.
  14410. The internal data of the two paths is swapped over, so this is much faster than
  14411. copying it to a temp variable and back.
  14412. */
  14413. void swapWithPath (Path& other);
  14414. /** Applies a 2D transform to all the vertices in the path.
  14415. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  14416. */
  14417. void applyTransform (const AffineTransform& transform) throw();
  14418. /** Rescales this path to make it fit neatly into a given space.
  14419. This is effectively a quick way of calling
  14420. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  14421. @param x the x position of the rectangle to fit the path inside
  14422. @param y the y position of the rectangle to fit the path inside
  14423. @param width the width of the rectangle to fit the path inside
  14424. @param height the height of the rectangle to fit the path inside
  14425. @param preserveProportions if true, it will fit the path into the space without altering its
  14426. horizontal/vertical scale ratio; if false, it will distort the
  14427. path to fill the specified ratio both horizontally and vertically
  14428. @see applyTransform, getTransformToScaleToFit
  14429. */
  14430. void scaleToFit (const float x, const float y,
  14431. const float width, const float height,
  14432. const bool preserveProportions) throw();
  14433. /** Returns a transform that can be used to rescale the path to fit into a given space.
  14434. @param x the x position of the rectangle to fit the path inside
  14435. @param y the y position of the rectangle to fit the path inside
  14436. @param width the width of the rectangle to fit the path inside
  14437. @param height the height of the rectangle to fit the path inside
  14438. @param preserveProportions if true, it will fit the path into the space without altering its
  14439. horizontal/vertical scale ratio; if false, it will distort the
  14440. path to fill the specified ratio both horizontally and vertically
  14441. @param justificationType if the proportions are preseved, the resultant path may be smaller
  14442. than the available rectangle, so this describes how it should be
  14443. positioned within the space.
  14444. @returns an appropriate transformation
  14445. @see applyTransform, scaleToFit
  14446. */
  14447. const AffineTransform getTransformToScaleToFit (const float x, const float y,
  14448. const float width, const float height,
  14449. const bool preserveProportions,
  14450. const Justification& justificationType = Justification::centred) const throw();
  14451. /** Creates a version of this path where all sharp corners have been replaced by curves.
  14452. Wherever two lines meet at an angle, this will replace the corner with a curve
  14453. of the given radius.
  14454. */
  14455. const Path createPathWithRoundedCorners (const float cornerRadius) const throw();
  14456. /** Changes the winding-rule to be used when filling the path.
  14457. If set to true (which is the default), then the path uses a non-zero-winding rule
  14458. to determine which points are inside the path. If set to false, it uses an
  14459. alternate-winding rule.
  14460. The winding-rule comes into play when areas of the shape overlap other
  14461. areas, and determines whether the overlapping regions are considered to be
  14462. inside or outside.
  14463. Changing this value just sets a flag - it doesn't affect the contents of the
  14464. path.
  14465. @see isUsingNonZeroWinding
  14466. */
  14467. void setUsingNonZeroWinding (const bool isNonZeroWinding) throw();
  14468. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  14469. The default for a new path is true.
  14470. @see setUsingNonZeroWinding
  14471. */
  14472. bool isUsingNonZeroWinding() const throw() { return useNonZeroWinding; }
  14473. /** Iterates the lines and curves that a path contains.
  14474. @see Path, PathFlatteningIterator
  14475. */
  14476. class JUCE_API Iterator
  14477. {
  14478. public:
  14479. Iterator (const Path& path);
  14480. ~Iterator();
  14481. /** Moves onto the next element in the path.
  14482. If this returns false, there are no more elements. If it returns true,
  14483. the elementType variable will be set to the type of the current element,
  14484. and some of the x and y variables will be filled in with values.
  14485. */
  14486. bool next();
  14487. enum PathElementType
  14488. {
  14489. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  14490. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  14491. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  14492. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  14493. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  14494. };
  14495. PathElementType elementType;
  14496. float x1, y1, x2, y2, x3, y3;
  14497. private:
  14498. const Path& path;
  14499. int index;
  14500. Iterator (const Iterator&);
  14501. const Iterator& operator= (const Iterator&);
  14502. };
  14503. /** Loads a stored path from a data stream.
  14504. The data in the stream must have been written using writePathToStream().
  14505. Note that this will append the stored path to whatever is currently in
  14506. this path, so you might need to call clear() beforehand.
  14507. @see loadPathFromData, writePathToStream
  14508. */
  14509. void loadPathFromStream (InputStream& source);
  14510. /** Loads a stored path from a block of data.
  14511. This is similar to loadPathFromStream(), but just reads from a block
  14512. of data. Useful if you're including stored shapes in your code as a
  14513. block of static data.
  14514. @see loadPathFromStream, writePathToStream
  14515. */
  14516. void loadPathFromData (const unsigned char* const data,
  14517. const int numberOfBytes) throw();
  14518. /** Stores the path by writing it out to a stream.
  14519. After writing out a path, you can reload it using loadPathFromStream().
  14520. @see loadPathFromStream, loadPathFromData
  14521. */
  14522. void writePathToStream (OutputStream& destination) const;
  14523. /** Creates a string containing a textual representation of this path.
  14524. @see restoreFromString
  14525. */
  14526. const String toString() const;
  14527. /** Restores this path from a string that was created with the toString() method.
  14528. @see toString()
  14529. */
  14530. void restoreFromString (const String& stringVersion);
  14531. juce_UseDebuggingNewOperator
  14532. private:
  14533. friend class PathFlatteningIterator;
  14534. friend class Path::Iterator;
  14535. ArrayAllocationBase <float> data;
  14536. int numElements;
  14537. float pathXMin, pathXMax, pathYMin, pathYMax;
  14538. bool useNonZeroWinding;
  14539. static const float lineMarker;
  14540. static const float moveMarker;
  14541. static const float quadMarker;
  14542. static const float cubicMarker;
  14543. static const float closeSubPathMarker;
  14544. };
  14545. #endif // __JUCE_PATH_JUCEHEADER__
  14546. /********* End of inlined file: juce_Path.h *********/
  14547. class Font;
  14548. class CustomTypefaceGlyphInfo;
  14549. /** A typeface represents a size-independent font.
  14550. This base class is abstract, but calling createSystemTypefaceFor() will return
  14551. a platform-specific subclass that can be used.
  14552. The CustomTypeface subclass allow you to build your own typeface, and to
  14553. load and save it in the Juce typeface format.
  14554. Normally you should never need to deal directly with Typeface objects - the Font
  14555. class does everything you typically need for rendering text.
  14556. @see CustomTypeface, Font
  14557. */
  14558. class JUCE_API Typeface : public ReferenceCountedObject
  14559. {
  14560. public:
  14561. /** A handy typedef for a pointer to a typeface. */
  14562. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  14563. /** Returns the name of the typeface.
  14564. @see Font::getTypefaceName
  14565. */
  14566. const String getName() const throw() { return name; }
  14567. /** Creates a new system typeface. */
  14568. static const Ptr createSystemTypefaceFor (const Font& font);
  14569. /** Destructor. */
  14570. virtual ~Typeface();
  14571. /** Returns the ascent of the font, as a proportion of its height.
  14572. The height is considered to always be normalised as 1.0, so this will be a
  14573. value less that 1.0, indicating the proportion of the font that lies above
  14574. its baseline.
  14575. */
  14576. virtual float getAscent() const = 0;
  14577. /** Returns the descent of the font, as a proportion of its height.
  14578. The height is considered to always be normalised as 1.0, so this will be a
  14579. value less that 1.0, indicating the proportion of the font that lies below
  14580. its baseline.
  14581. */
  14582. virtual float getDescent() const = 0;
  14583. /** Measures the width of a line of text.
  14584. The distance returned is based on the font having an normalised height of 1.0.
  14585. You should never need to call this directly! Use Font::getStringWidth() instead!
  14586. */
  14587. virtual float getStringWidth (const String& text) = 0;
  14588. /** Converts a line of text into its glyph numbers and their positions.
  14589. The distances returned are based on the font having an normalised height of 1.0.
  14590. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  14591. */
  14592. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  14593. /** Returns the outline for a glyph.
  14594. The path returned will be normalised to a font height of 1.0.
  14595. */
  14596. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  14597. juce_UseDebuggingNewOperator
  14598. protected:
  14599. String name;
  14600. Typeface (const String& name) throw();
  14601. private:
  14602. Typeface (const Typeface&);
  14603. const Typeface& operator= (const Typeface&);
  14604. };
  14605. /** A typeface that can be populated with custom glyphs.
  14606. You can create a CustomTypeface if you need one that contains your own glyphs,
  14607. or if you need to load a typeface from a Juce-formatted binary stream.
  14608. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  14609. to copy glyphs into this face.
  14610. @see Typeface, Font
  14611. */
  14612. class JUCE_API CustomTypeface : public Typeface
  14613. {
  14614. public:
  14615. /** Creates a new, empty typeface. */
  14616. CustomTypeface();
  14617. /** Loads a typeface from a previously saved stream.
  14618. The stream must have been created by writeToStream().
  14619. @see writeToStream
  14620. */
  14621. CustomTypeface (InputStream& serialisedTypefaceStream);
  14622. /** Destructor. */
  14623. ~CustomTypeface();
  14624. /** Resets this typeface, deleting all its glyphs and settings. */
  14625. void clear();
  14626. /** Sets the vital statistics for the typeface.
  14627. @param name the typeface's name
  14628. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  14629. the value that will be returned by Typeface::getAscent(). The
  14630. descent is assumed to be (1.0 - ascent)
  14631. @param isBold should be true if the typeface is bold
  14632. @param isItalic should be true if the typeface is italic
  14633. @param defaultCharacter the character to be used as a replacement if there's
  14634. no glyph available for the character that's being drawn
  14635. */
  14636. void setCharacteristics (const String& name, const float ascent,
  14637. const bool isBold, const bool isItalic,
  14638. const juce_wchar defaultCharacter) throw();
  14639. /** Adds a glyph to the typeface.
  14640. The path that is passed in is normalised so that the font height is 1.0, and its
  14641. origin is the anchor point of the character on its baseline.
  14642. The width is the nominal width of the character, and any extra kerning values that
  14643. are specified will be added to this width.
  14644. */
  14645. void addGlyph (const juce_wchar character, const Path& path, const float width) throw();
  14646. /** Specifies an extra kerning amount to be used between a pair of characters.
  14647. The amount will be added to the nominal width of the first character when laying out a string.
  14648. */
  14649. void addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw();
  14650. /** Adds a range of glyphs from another typeface.
  14651. This will attempt to pull in the paths and kerning information from another typeface and
  14652. add it to this one.
  14653. */
  14654. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  14655. /** Saves this typeface as a Juce-formatted font file.
  14656. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  14657. constructor.
  14658. */
  14659. bool writeToStream (OutputStream& outputStream);
  14660. // The following methods implement the basic Typeface behaviour.
  14661. float getAscent() const;
  14662. float getDescent() const;
  14663. float getStringWidth (const String& text);
  14664. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  14665. bool getOutlineForGlyph (int glyphNumber, Path& path);
  14666. int getGlyphForCharacter (juce_wchar character);
  14667. juce_UseDebuggingNewOperator
  14668. protected:
  14669. juce_wchar defaultCharacter;
  14670. float ascent;
  14671. bool isBold, isItalic;
  14672. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  14673. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  14674. particular character and there's no corresponding glyph, they'll call this
  14675. method so that a subclass can try to add that glyph, returning true if it
  14676. manages to do so.
  14677. */
  14678. virtual bool loadGlyphIfPossible (const juce_wchar characterNeeded);
  14679. private:
  14680. OwnedArray <CustomTypefaceGlyphInfo> glyphs;
  14681. short lookupTable [128];
  14682. CustomTypeface (const CustomTypeface&);
  14683. const CustomTypeface& operator= (const CustomTypeface&);
  14684. CustomTypefaceGlyphInfo* findGlyph (const juce_wchar character, const bool loadIfNeeded) throw();
  14685. CustomTypefaceGlyphInfo* findGlyphSubstituting (const juce_wchar character) throw();
  14686. };
  14687. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  14688. /********* End of inlined file: juce_Typeface.h *********/
  14689. class LowLevelGraphicsContext;
  14690. /**
  14691. Represents a particular font, including its size, style, etc.
  14692. Apart from the typeface to be used, a Font object also dictates whether
  14693. the font is bold, italic, underlined, how big it is, and its kerning and
  14694. horizontal scale factor.
  14695. @see Typeface
  14696. */
  14697. class JUCE_API Font
  14698. {
  14699. public:
  14700. /** A combination of these values is used by the constructor to specify the
  14701. style of font to use.
  14702. */
  14703. enum FontStyleFlags
  14704. {
  14705. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  14706. bold = 1, /**< boldens the font. @see setStyleFlags */
  14707. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  14708. underlined = 4 /**< underlines the font. @see setStyleFlags */
  14709. };
  14710. /** Creates a sans-serif font in a given size.
  14711. @param fontHeight the height in pixels (can be fractional)
  14712. @param styleFlags the style to use - this can be a combination of the
  14713. Font::bold, Font::italic and Font::underlined, or
  14714. just Font::plain for the normal style.
  14715. @see FontStyleFlags, getDefaultSansSerifFontName
  14716. */
  14717. Font (const float fontHeight,
  14718. const int styleFlags = plain) throw();
  14719. /** Creates a font with a given typeface and parameters.
  14720. @param typefaceName the name of the typeface to use
  14721. @param fontHeight the height in pixels (can be fractional)
  14722. @param styleFlags the style to use - this can be a combination of the
  14723. Font::bold, Font::italic and Font::underlined, or
  14724. just Font::plain for the normal style.
  14725. @see FontStyleFlags, getDefaultSansSerifFontName
  14726. */
  14727. Font (const String& typefaceName,
  14728. const float fontHeight,
  14729. const int styleFlags) throw();
  14730. /** Creates a copy of another Font object. */
  14731. Font (const Font& other) throw();
  14732. /** Creates a font for a typeface. */
  14733. Font (const Typeface::Ptr& typeface) throw();
  14734. /** Creates a basic sans-serif font at a default height.
  14735. You should use one of the other constructors for creating a font that you're planning
  14736. on drawing with - this constructor is here to help initialise objects before changing
  14737. the font's settings later.
  14738. */
  14739. Font() throw();
  14740. /** Copies this font from another one. */
  14741. const Font& operator= (const Font& other) throw();
  14742. bool operator== (const Font& other) const throw();
  14743. bool operator!= (const Font& other) const throw();
  14744. /** Destructor. */
  14745. ~Font() throw();
  14746. /** Changes the name of the typeface family.
  14747. e.g. "Arial", "Courier", etc.
  14748. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  14749. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  14750. but are generic names that are used to represent the various default fonts.
  14751. If you need to know the exact typeface name being used, you can call
  14752. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  14753. If a suitable font isn't found on the machine, it'll just use a default instead.
  14754. */
  14755. void setTypefaceName (const String& faceName) throw();
  14756. /** Returns the name of the typeface family that this font uses.
  14757. e.g. "Arial", "Courier", etc.
  14758. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  14759. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  14760. but are generic names that are used to represent the various default fonts.
  14761. If you need to know the exact typeface name being used, you can call
  14762. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  14763. */
  14764. const String& getTypefaceName() const throw() { return font->typefaceName; }
  14765. /** Returns a typeface name that represents the default sans-serif font.
  14766. This is also the typeface that will be used when a font is created without
  14767. specifying any typeface details.
  14768. Note that this method just returns a generic placeholder string that means "the default
  14769. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  14770. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  14771. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  14772. */
  14773. static const String getDefaultSansSerifFontName() throw();
  14774. /** Returns a typeface name that represents the default sans-serif font.
  14775. Note that this method just returns a generic placeholder string that means "the default
  14776. serif font" - it's not the actual name of this font. To get the actual name, use
  14777. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  14778. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  14779. */
  14780. static const String getDefaultSerifFontName() throw();
  14781. /** Returns a typeface name that represents the default sans-serif font.
  14782. Note that this method just returns a generic placeholder string that means "the default
  14783. monospaced font" - it's not the actual name of this font. To get the actual name, use
  14784. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  14785. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  14786. */
  14787. static const String getDefaultMonospacedFontName() throw();
  14788. /** Returns the typeface names of the default fonts on the current platform. */
  14789. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw();
  14790. /** Returns the total height of this font.
  14791. This is the maximum height, from the top of the ascent to the bottom of the
  14792. descenders.
  14793. @see setHeight, setHeightWithoutChangingWidth, getAscent
  14794. */
  14795. float getHeight() const throw() { return font->height; }
  14796. /** Changes the font's height.
  14797. @see getHeight, setHeightWithoutChangingWidth
  14798. */
  14799. void setHeight (float newHeight) throw();
  14800. /** Changes the font's height without changing its width.
  14801. This alters the horizontal scale to compensate for the change in height.
  14802. */
  14803. void setHeightWithoutChangingWidth (float newHeight) throw();
  14804. /** Returns the height of the font above its baseline.
  14805. This is the maximum height from the baseline to the top.
  14806. @see getHeight, getDescent
  14807. */
  14808. float getAscent() const throw();
  14809. /** Returns the amount that the font descends below its baseline.
  14810. This is calculated as (getHeight() - getAscent()).
  14811. @see getAscent, getHeight
  14812. */
  14813. float getDescent() const throw();
  14814. /** Returns the font's style flags.
  14815. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  14816. enum, to describe whether the font is bold, italic, etc.
  14817. @see FontStyleFlags
  14818. */
  14819. int getStyleFlags() const throw() { return font->styleFlags; }
  14820. /** Changes the font's style.
  14821. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  14822. enum, to set the font's properties
  14823. @see FontStyleFlags
  14824. */
  14825. void setStyleFlags (const int newFlags) throw();
  14826. /** Makes the font bold or non-bold. */
  14827. void setBold (const bool shouldBeBold) throw();
  14828. /** Returns true if the font is bold. */
  14829. bool isBold() const throw();
  14830. /** Makes the font italic or non-italic. */
  14831. void setItalic (const bool shouldBeItalic) throw();
  14832. /** Returns true if the font is italic. */
  14833. bool isItalic() const throw();
  14834. /** Makes the font underlined or non-underlined. */
  14835. void setUnderline (const bool shouldBeUnderlined) throw();
  14836. /** Returns true if the font is underlined. */
  14837. bool isUnderlined() const throw();
  14838. /** Changes the font's horizontal scale factor.
  14839. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  14840. narrower, greater than 1.0 will be stretched out.
  14841. */
  14842. void setHorizontalScale (const float scaleFactor) throw();
  14843. /** Returns the font's horizontal scale.
  14844. A value of 1.0 is the normal scale, less than this will be narrower, greater
  14845. than 1.0 will be stretched out.
  14846. @see setHorizontalScale
  14847. */
  14848. float getHorizontalScale() const throw() { return font->horizontalScale; }
  14849. /** Changes the font's kerning.
  14850. @param extraKerning a multiple of the font's height that will be added
  14851. to space between the characters. So a value of zero is
  14852. normal spacing, positive values spread the letters out,
  14853. negative values make them closer together.
  14854. */
  14855. void setExtraKerningFactor (const float extraKerning) throw();
  14856. /** Returns the font's kerning.
  14857. This is the extra space added between adjacent characters, as a proportion
  14858. of the font's height.
  14859. A value of zero is normal spacing, positive values will spread the letters
  14860. out more, and negative values make them closer together.
  14861. */
  14862. float getExtraKerningFactor() const throw() { return font->kerning; }
  14863. /** Changes all the font's characteristics with one call. */
  14864. void setSizeAndStyle (float newHeight,
  14865. const int newStyleFlags,
  14866. const float newHorizontalScale,
  14867. const float newKerningAmount) throw();
  14868. /** Returns the total width of a string as it would be drawn using this font.
  14869. For a more accurate floating-point result, use getStringWidthFloat().
  14870. */
  14871. int getStringWidth (const String& text) const throw();
  14872. /** Returns the total width of a string as it would be drawn using this font.
  14873. @see getStringWidth
  14874. */
  14875. float getStringWidthFloat (const String& text) const throw();
  14876. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  14877. An extra x offset is added at the end of the run, to indicate where the right hand
  14878. edge of the last character is.
  14879. */
  14880. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  14881. /** Returns the typeface used by this font.
  14882. Note that the object returned may go out of scope if this font is deleted
  14883. or has its style changed.
  14884. */
  14885. Typeface* getTypeface() const throw();
  14886. /** Creates an array of Font objects to represent all the fonts on the system.
  14887. If you just need the names of the typefaces, you can also use
  14888. findAllTypefaceNames() instead.
  14889. @param results the array to which new Font objects will be added.
  14890. */
  14891. static void findFonts (OwnedArray<Font>& results) throw();
  14892. /** Returns a list of all the available typeface names.
  14893. The names returned can be passed into setTypefaceName().
  14894. You can use this instead of findFonts() if you only need their names, and not
  14895. font objects.
  14896. */
  14897. static const StringArray findAllTypefaceNames() throw();
  14898. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  14899. in the requested typeface.
  14900. */
  14901. static const String getFallbackFontName() throw();
  14902. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  14903. available in whatever font you're trying to use.
  14904. */
  14905. static void setFallbackFontName (const String& name) throw();
  14906. juce_UseDebuggingNewOperator
  14907. private:
  14908. friend class FontGlyphAlphaMap;
  14909. friend class TypefaceCache;
  14910. class SharedFontInternal : public ReferenceCountedObject
  14911. {
  14912. public:
  14913. SharedFontInternal (const String& typefaceName, const float height, const float horizontalScale,
  14914. const float kerning, const float ascent, const int styleFlags,
  14915. Typeface* const typeface) throw();
  14916. SharedFontInternal (const SharedFontInternal& other) throw();
  14917. String typefaceName;
  14918. float height, horizontalScale, kerning, ascent;
  14919. int styleFlags;
  14920. Typeface::Ptr typeface;
  14921. };
  14922. ReferenceCountedObjectPtr <SharedFontInternal> font;
  14923. void dupeInternalIfShared() throw();
  14924. };
  14925. #endif // __JUCE_FONT_JUCEHEADER__
  14926. /********* End of inlined file: juce_Font.h *********/
  14927. /********* Start of inlined file: juce_PathStrokeType.h *********/
  14928. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  14929. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  14930. /**
  14931. Describes a type of stroke used to render a solid outline along a path.
  14932. A PathStrokeType object can be used directly to create the shape of an outline
  14933. around a path, and is used by Graphics::strokePath to specify the type of
  14934. stroke to draw.
  14935. @see Path, Graphics::strokePath
  14936. */
  14937. class JUCE_API PathStrokeType
  14938. {
  14939. public:
  14940. /** The type of shape to use for the corners between two adjacent line segments. */
  14941. enum JointStyle
  14942. {
  14943. mitered, /**< Indicates that corners should be drawn with sharp joints.
  14944. Note that for angles that curve back on themselves, drawing a
  14945. mitre could require extending the point too far away from the
  14946. path, so a mitre limit is imposed and any corners that exceed it
  14947. are drawn as bevelled instead. */
  14948. curved, /**< Indicates that corners should be drawn as rounded-off. */
  14949. beveled /**< Indicates that corners should be drawn with a line flattening their
  14950. outside edge. */
  14951. };
  14952. /** The type shape to use for the ends of lines. */
  14953. enum EndCapStyle
  14954. {
  14955. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  14956. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  14957. the thickness of the stroke. */
  14958. rounded /**< Ends of lines are rounded-off with a circular shape. */
  14959. };
  14960. /** Creates a stroke type.
  14961. @param strokeThickness the width of the line to use
  14962. @param jointStyle the type of joints to use for corners
  14963. @param endStyle the type of end-caps to use for the ends of open paths.
  14964. */
  14965. PathStrokeType (const float strokeThickness,
  14966. const JointStyle jointStyle = mitered,
  14967. const EndCapStyle endStyle = butt) throw();
  14968. /** Createes a copy of another stroke type. */
  14969. PathStrokeType (const PathStrokeType& other) throw();
  14970. /** Copies another stroke onto this one. */
  14971. const PathStrokeType& operator= (const PathStrokeType& other) throw();
  14972. /** Destructor. */
  14973. ~PathStrokeType() throw();
  14974. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  14975. @param destPath the resultant stroked outline shape will be copied into this path.
  14976. Note that it's ok for the source and destination Paths to be
  14977. the same object, so you can easily turn a path into a stroked version
  14978. of itself.
  14979. @param sourcePath the path to use as the source
  14980. @param transform an optional transform to apply to the points from the source path
  14981. as they are being used
  14982. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  14983. a higher resolution, which improved the quality if you'll later want
  14984. to enlarge the stroked path
  14985. @see createDashedStroke
  14986. */
  14987. void createStrokedPath (Path& destPath,
  14988. const Path& sourcePath,
  14989. const AffineTransform& transform = AffineTransform::identity,
  14990. const float extraAccuracy = 1.0f) const throw();
  14991. /** Applies this stroke type to a path, creating a dashed line.
  14992. This is similar to createStrokedPath, but uses the array passed in to
  14993. break the stroke up into a series of dashes.
  14994. @param destPath the resultant stroked outline shape will be copied into this path.
  14995. Note that it's ok for the source and destination Paths to be
  14996. the same object, so you can easily turn a path into a stroked version
  14997. of itself.
  14998. @param sourcePath the path to use as the source
  14999. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  15000. a line of length 2, then skip a length of 3, then add a line of length 4,
  15001. skip 5, and keep repeating this pattern.
  15002. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  15003. an even number, otherwise the pattern will get out of step as it
  15004. repeats.
  15005. @param transform an optional transform to apply to the points from the source path
  15006. as they are being used
  15007. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  15008. a higher resolution, which improved the quality if you'll later want
  15009. to enlarge the stroked path
  15010. */
  15011. void createDashedStroke (Path& destPath,
  15012. const Path& sourcePath,
  15013. const float* dashLengths,
  15014. int numDashLengths,
  15015. const AffineTransform& transform = AffineTransform::identity,
  15016. const float extraAccuracy = 1.0f) const throw();
  15017. /** Returns the stroke thickness. */
  15018. float getStrokeThickness() const throw() { return thickness; }
  15019. /** Returns the joint style. */
  15020. JointStyle getJointStyle() const throw() { return jointStyle; }
  15021. /** Returns the end-cap style. */
  15022. EndCapStyle getEndStyle() const throw() { return endStyle; }
  15023. juce_UseDebuggingNewOperator
  15024. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  15025. bool operator== (const PathStrokeType& other) const throw();
  15026. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  15027. bool operator!= (const PathStrokeType& other) const throw();
  15028. private:
  15029. float thickness;
  15030. JointStyle jointStyle;
  15031. EndCapStyle endStyle;
  15032. };
  15033. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  15034. /********* End of inlined file: juce_PathStrokeType.h *********/
  15035. /********* Start of inlined file: juce_Line.h *********/
  15036. #ifndef __JUCE_LINE_JUCEHEADER__
  15037. #define __JUCE_LINE_JUCEHEADER__
  15038. /**
  15039. Represents a line, using 32-bit float co-ordinates.
  15040. This class contains a bunch of useful methods for various geometric
  15041. tasks.
  15042. @see Point, Rectangle, Path, Graphics::drawLine
  15043. */
  15044. class JUCE_API Line
  15045. {
  15046. public:
  15047. /** Creates a line, using (0, 0) as its start and end points. */
  15048. Line() throw();
  15049. /** Creates a copy of another line. */
  15050. Line (const Line& other) throw();
  15051. /** Creates a line based on the co-ordinates of its start and end points. */
  15052. Line (const float startX,
  15053. const float startY,
  15054. const float endX,
  15055. const float endY) throw();
  15056. /** Creates a line from its start and end points. */
  15057. Line (const Point& start,
  15058. const Point& end) throw();
  15059. /** Copies a line from another one. */
  15060. const Line& operator= (const Line& other) throw();
  15061. /** Destructor. */
  15062. ~Line() throw();
  15063. /** Returns the x co-ordinate of the line's start point. */
  15064. inline float getStartX() const throw() { return startX; }
  15065. /** Returns the y co-ordinate of the line's start point. */
  15066. inline float getStartY() const throw() { return startY; }
  15067. /** Returns the x co-ordinate of the line's end point. */
  15068. inline float getEndX() const throw() { return endX; }
  15069. /** Returns the y co-ordinate of the line's end point. */
  15070. inline float getEndY() const throw() { return endY; }
  15071. /** Returns the line's start point. */
  15072. const Point getStart() const throw();
  15073. /** Returns the line's end point. */
  15074. const Point getEnd() const throw();
  15075. /** Changes this line's start point */
  15076. void setStart (const float newStartX,
  15077. const float newStartY) throw();
  15078. /** Changes this line's end point */
  15079. void setEnd (const float newEndX,
  15080. const float newEndY) throw();
  15081. /** Changes this line's start point */
  15082. void setStart (const Point& newStart) throw();
  15083. /** Changes this line's end point */
  15084. void setEnd (const Point& newEnd) throw();
  15085. /** Applies an affine transform to the line's start and end points. */
  15086. void applyTransform (const AffineTransform& transform) throw();
  15087. /** Returns the length of the line. */
  15088. float getLength() const throw();
  15089. /** Returns true if the line's start and end x co-ordinates are the same. */
  15090. bool isVertical() const throw();
  15091. /** Returns true if the line's start and end y co-ordinates are the same. */
  15092. bool isHorizontal() const throw();
  15093. /** Returns the line's angle.
  15094. This value is the number of radians clockwise from the 3 o'clock direction,
  15095. where the line's start point is considered to be at the centre.
  15096. */
  15097. float getAngle() const throw();
  15098. /** Compares two lines. */
  15099. bool operator== (const Line& other) const throw();
  15100. /** Compares two lines. */
  15101. bool operator!= (const Line& other) const throw();
  15102. /** Finds the intersection between two lines.
  15103. @param line the other line
  15104. @param intersectionX the x co-ordinate of the point where the lines meet (or
  15105. where they would meet if they were infinitely long)
  15106. the intersection (if the lines intersect). If the lines
  15107. are parallel, this will just be set to the position
  15108. of one of the line's endpoints.
  15109. @param intersectionY the y co-ordinate of the point where the lines meet
  15110. @returns true if the line segments intersect; false if they dont. Even if they
  15111. don't intersect, the intersection co-ordinates returned will still
  15112. be valid
  15113. */
  15114. bool intersects (const Line& line,
  15115. float& intersectionX,
  15116. float& intersectionY) const throw();
  15117. /** Returns the location of the point which is a given distance along this line.
  15118. @param distanceFromStart the distance to move along the line from its
  15119. start point. This value can be negative or longer
  15120. than the line itself
  15121. @see getPointAlongLineProportionally
  15122. */
  15123. const Point getPointAlongLine (const float distanceFromStart) const throw();
  15124. /** Returns a point which is a certain distance along and to the side of this line.
  15125. This effectively moves a given distance along the line, then another distance
  15126. perpendicularly to this, and returns the resulting position.
  15127. @param distanceFromStart the distance to move along the line from its
  15128. start point. This value can be negative or longer
  15129. than the line itself
  15130. @param perpendicularDistance how far to move sideways from the line. If you're
  15131. looking along the line from its start towards its
  15132. end, then a positive value here will move to the
  15133. right, negative value move to the left.
  15134. */
  15135. const Point getPointAlongLine (const float distanceFromStart,
  15136. const float perpendicularDistance) const throw();
  15137. /** Returns the location of the point which is a given distance along this line
  15138. proportional to the line's length.
  15139. @param proportionOfLength the distance to move along the line from its
  15140. start point, in multiples of the line's length.
  15141. So a value of 0.0 will return the line's start point
  15142. and a value of 1.0 will return its end point. (This value
  15143. can be negative or greater than 1.0).
  15144. @see getPointAlongLine
  15145. */
  15146. const Point getPointAlongLineProportionally (const float proportionOfLength) const throw();
  15147. /** Returns the smallest distance between this line segment and a given point.
  15148. So if the point is close to the line, this will return the perpendicular
  15149. distance from the line; if the point is a long way beyond one of the line's
  15150. end-point's, it'll return the straight-line distance to the nearest end-point.
  15151. @param x x position of the point to test
  15152. @param y y position of the point to test
  15153. @returns the point's distance from the line
  15154. @see getPositionAlongLineOfNearestPoint
  15155. */
  15156. float getDistanceFromLine (const float x,
  15157. const float y) const throw();
  15158. /** Finds the point on this line which is nearest to a given point, and
  15159. returns its position as a proportional position along the line.
  15160. @param x x position of the point to test
  15161. @param y y position of the point to test
  15162. @returns a value 0 to 1.0 which is the distance along this line from the
  15163. line's start to the point which is nearest to the point passed-in. To
  15164. turn this number into a position, use getPointAlongLineProportionally().
  15165. @see getDistanceFromLine, getPointAlongLineProportionally
  15166. */
  15167. float findNearestPointTo (const float x,
  15168. const float y) const throw();
  15169. /** Returns true if the given point lies above this line.
  15170. The return value is true if the point's y coordinate is less than the y
  15171. coordinate of this line at the given x (assuming the line extends infinitely
  15172. in both directions).
  15173. */
  15174. bool isPointAbove (const float x, const float y) const throw();
  15175. /** Returns a shortened copy of this line.
  15176. This will chop off part of the start of this line by a certain amount, (leaving the
  15177. end-point the same), and return the new line.
  15178. */
  15179. const Line withShortenedStart (const float distanceToShortenBy) const throw();
  15180. /** Returns a shortened copy of this line.
  15181. This will chop off part of the end of this line by a certain amount, (leaving the
  15182. start-point the same), and return the new line.
  15183. */
  15184. const Line withShortenedEnd (const float distanceToShortenBy) const throw();
  15185. /** Cuts off parts of this line to keep the parts that are either inside or
  15186. outside a path.
  15187. Note that this isn't smart enough to cope with situations where the
  15188. line would need to be cut into multiple pieces to correctly clip against
  15189. a re-entrant shape.
  15190. @param path the path to clip against
  15191. @param keepSectionOutsidePath if true, it's the section outside the path
  15192. that will be kept; if false its the section inside
  15193. the path
  15194. @returns true if the line was changed.
  15195. */
  15196. bool clipToPath (const Path& path,
  15197. const bool keepSectionOutsidePath) throw();
  15198. juce_UseDebuggingNewOperator
  15199. private:
  15200. float startX, startY, endX, endY;
  15201. };
  15202. #endif // __JUCE_LINE_JUCEHEADER__
  15203. /********* End of inlined file: juce_Line.h *********/
  15204. /********* Start of inlined file: juce_Colours.h *********/
  15205. #ifndef __JUCE_COLOURS_JUCEHEADER__
  15206. #define __JUCE_COLOURS_JUCEHEADER__
  15207. /********* Start of inlined file: juce_Colour.h *********/
  15208. #ifndef __JUCE_COLOUR_JUCEHEADER__
  15209. #define __JUCE_COLOUR_JUCEHEADER__
  15210. /********* Start of inlined file: juce_PixelFormats.h *********/
  15211. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  15212. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  15213. #if JUCE_MSVC
  15214. #pragma pack (push, 1)
  15215. #define PACKED
  15216. #elif JUCE_GCC
  15217. #define PACKED __attribute__((packed))
  15218. #else
  15219. #define PACKED
  15220. #endif
  15221. class PixelRGB;
  15222. class PixelAlpha;
  15223. /**
  15224. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  15225. operations with it.
  15226. This is used internally by the imaging classes.
  15227. @see PixelRGB
  15228. */
  15229. class JUCE_API PixelARGB
  15230. {
  15231. public:
  15232. /** Creates a pixel without defining its colour. */
  15233. PixelARGB() throw() {}
  15234. ~PixelARGB() throw() {}
  15235. /** Creates a pixel from a 32-bit argb value.
  15236. */
  15237. PixelARGB (const uint32 argb_) throw()
  15238. : argb (argb_)
  15239. {
  15240. }
  15241. forcedinline uint32 getARGB() const throw() { return argb; }
  15242. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  15243. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  15244. forcedinline uint8 getAlpha() const throw() { return components.a; }
  15245. forcedinline uint8 getRed() const throw() { return components.r; }
  15246. forcedinline uint8 getGreen() const throw() { return components.g; }
  15247. forcedinline uint8 getBlue() const throw() { return components.b; }
  15248. /** Blends another pixel onto this one.
  15249. This takes into account the opacity of the pixel being overlaid, and blends
  15250. it accordingly.
  15251. */
  15252. forcedinline void blend (const PixelARGB& src) throw()
  15253. {
  15254. uint32 sargb = src.getARGB();
  15255. const uint32 alpha = 0x100 - (sargb >> 24);
  15256. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15257. sargb += 0xff00ff00 & (getAG() * alpha);
  15258. argb = sargb;
  15259. }
  15260. /** Blends another pixel onto this one.
  15261. This takes into account the opacity of the pixel being overlaid, and blends
  15262. it accordingly.
  15263. */
  15264. forcedinline void blend (const PixelAlpha& src) throw();
  15265. /** Blends another pixel onto this one.
  15266. This takes into account the opacity of the pixel being overlaid, and blends
  15267. it accordingly.
  15268. */
  15269. forcedinline void blend (const PixelRGB& src) throw();
  15270. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  15271. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  15272. being used, so this can blend semi-transparently from a PixelRGB argument.
  15273. */
  15274. template <class Pixel>
  15275. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  15276. {
  15277. ++extraAlpha;
  15278. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  15279. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  15280. const uint32 alpha = 0x100 - (sargb >> 24);
  15281. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15282. sargb += 0xff00ff00 & (getAG() * alpha);
  15283. argb = sargb;
  15284. }
  15285. /** Blends another pixel with this one, creating a colour that is somewhere
  15286. between the two, as specified by the amount.
  15287. */
  15288. template <class Pixel>
  15289. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  15290. {
  15291. uint32 drb = getRB();
  15292. drb += (((src.getRB() - drb) * amount) >> 8);
  15293. drb &= 0x00ff00ff;
  15294. uint32 dag = getAG();
  15295. dag += (((src.getAG() - dag) * amount) >> 8);
  15296. dag &= 0x00ff00ff;
  15297. dag <<= 8;
  15298. dag |= drb;
  15299. argb = dag;
  15300. }
  15301. /** Copies another pixel colour over this one.
  15302. This doesn't blend it - this colour is simply replaced by the other one.
  15303. */
  15304. template <class Pixel>
  15305. forcedinline void set (const Pixel& src) throw()
  15306. {
  15307. argb = src.getARGB();
  15308. }
  15309. /** Replaces the colour's alpha value with another one. */
  15310. forcedinline void setAlpha (const uint8 newAlpha) throw()
  15311. {
  15312. components.a = newAlpha;
  15313. }
  15314. /** Multiplies the colour's alpha value with another one. */
  15315. forcedinline void multiplyAlpha (int multiplier) throw()
  15316. {
  15317. ++multiplier;
  15318. argb = ((multiplier * getAG()) & 0xff00ff00)
  15319. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  15320. }
  15321. forcedinline void multiplyAlpha (const float multiplier) throw()
  15322. {
  15323. multiplyAlpha ((int) (multiplier * 256.0f));
  15324. }
  15325. /** Sets the pixel's colour from individual components. */
  15326. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  15327. {
  15328. components.b = b;
  15329. components.g = g;
  15330. components.r = r;
  15331. components.a = a;
  15332. }
  15333. /** Premultiplies the pixel's RGB values by its alpha. */
  15334. forcedinline void premultiply() throw()
  15335. {
  15336. const uint32 alpha = components.a;
  15337. if (alpha < 0xff)
  15338. {
  15339. if (alpha == 0)
  15340. {
  15341. components.b = 0;
  15342. components.g = 0;
  15343. components.r = 0;
  15344. }
  15345. else
  15346. {
  15347. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  15348. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  15349. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  15350. }
  15351. }
  15352. }
  15353. /** Unpremultiplies the pixel's RGB values. */
  15354. forcedinline void unpremultiply() throw()
  15355. {
  15356. const uint32 alpha = components.a;
  15357. if (alpha < 0xff)
  15358. {
  15359. if (alpha == 0)
  15360. {
  15361. components.b = 0;
  15362. components.g = 0;
  15363. components.r = 0;
  15364. }
  15365. else
  15366. {
  15367. components.b = (uint8) jmin (0xff, (components.b * 0xff) / alpha);
  15368. components.g = (uint8) jmin (0xff, (components.g * 0xff) / alpha);
  15369. components.r = (uint8) jmin (0xff, (components.r * 0xff) / alpha);
  15370. }
  15371. }
  15372. }
  15373. forcedinline void desaturate() throw()
  15374. {
  15375. if (components.a < 0xff && components.a > 0)
  15376. {
  15377. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  15378. components.r = components.g = components.b
  15379. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  15380. }
  15381. else
  15382. {
  15383. components.r = components.g = components.b
  15384. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  15385. }
  15386. }
  15387. /** The indexes of the different components in the byte layout of this type of colour. */
  15388. #if JUCE_BIG_ENDIAN
  15389. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  15390. #else
  15391. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  15392. #endif
  15393. private:
  15394. union
  15395. {
  15396. uint32 argb;
  15397. struct
  15398. {
  15399. #if JUCE_BIG_ENDIAN
  15400. uint8 a : 8, r : 8, g : 8, b : 8;
  15401. #else
  15402. uint8 b, g, r, a;
  15403. #endif
  15404. } PACKED components;
  15405. };
  15406. } PACKED;
  15407. /**
  15408. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  15409. This is used internally by the imaging classes.
  15410. @see PixelARGB
  15411. */
  15412. class JUCE_API PixelRGB
  15413. {
  15414. public:
  15415. /** Creates a pixel without defining its colour. */
  15416. PixelRGB() throw() {}
  15417. ~PixelRGB() throw() {}
  15418. /** Creates a pixel from a 32-bit argb value.
  15419. (The argb format is that used by PixelARGB)
  15420. */
  15421. PixelRGB (const uint32 argb) throw()
  15422. {
  15423. r = (uint8) (argb >> 16);
  15424. g = (uint8) (argb >> 8);
  15425. b = (uint8) (argb);
  15426. }
  15427. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  15428. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  15429. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  15430. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  15431. forcedinline uint8 getRed() const throw() { return r; }
  15432. forcedinline uint8 getGreen() const throw() { return g; }
  15433. forcedinline uint8 getBlue() const throw() { return b; }
  15434. /** Blends another pixel onto this one.
  15435. This takes into account the opacity of the pixel being overlaid, and blends
  15436. it accordingly.
  15437. */
  15438. forcedinline void blend (const PixelARGB& src) throw()
  15439. {
  15440. uint32 sargb = src.getARGB();
  15441. const uint32 alpha = 0x100 - (sargb >> 24);
  15442. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15443. sargb += 0x0000ff00 & (g * alpha);
  15444. r = (uint8) (sargb >> 16);
  15445. g = (uint8) (sargb >> 8);
  15446. b = (uint8) sargb;
  15447. }
  15448. forcedinline void blend (const PixelRGB& src) throw()
  15449. {
  15450. set (src);
  15451. }
  15452. forcedinline void blend (const PixelAlpha& src) throw();
  15453. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  15454. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  15455. being used, so this can blend semi-transparently from a PixelRGB argument.
  15456. */
  15457. template <class Pixel>
  15458. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  15459. {
  15460. ++extraAlpha;
  15461. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  15462. const uint32 sag = extraAlpha * src.getAG();
  15463. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  15464. const uint32 alpha = 0x100 - (sargb >> 24);
  15465. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15466. sargb += 0x0000ff00 & (g * alpha);
  15467. b = (uint8) sargb;
  15468. g = (uint8) (sargb >> 8);
  15469. r = (uint8) (sargb >> 16);
  15470. }
  15471. /** Blends another pixel with this one, creating a colour that is somewhere
  15472. between the two, as specified by the amount.
  15473. */
  15474. template <class Pixel>
  15475. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  15476. {
  15477. uint32 drb = getRB();
  15478. drb += (((src.getRB() - drb) * amount) >> 8);
  15479. uint32 dag = getAG();
  15480. dag += (((src.getAG() - dag) * amount) >> 8);
  15481. b = (uint8) drb;
  15482. g = (uint8) dag;
  15483. r = (uint8) (drb >> 16);
  15484. }
  15485. /** Copies another pixel colour over this one.
  15486. This doesn't blend it - this colour is simply replaced by the other one.
  15487. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  15488. is thrown away.
  15489. */
  15490. template <class Pixel>
  15491. forcedinline void set (const Pixel& src) throw()
  15492. {
  15493. b = src.getBlue();
  15494. g = src.getGreen();
  15495. r = src.getRed();
  15496. }
  15497. /** This method is included for compatibility with the PixelARGB class. */
  15498. forcedinline void setAlpha (const uint8) throw() {}
  15499. /** Multiplies the colour's alpha value with another one. */
  15500. forcedinline void multiplyAlpha (int) throw() {}
  15501. /** Sets the pixel's colour from individual components. */
  15502. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  15503. {
  15504. r = r_;
  15505. g = g_;
  15506. b = b_;
  15507. }
  15508. /** Premultiplies the pixel's RGB values by its alpha. */
  15509. forcedinline void premultiply() throw() {}
  15510. /** Unpremultiplies the pixel's RGB values. */
  15511. forcedinline void unpremultiply() throw() {}
  15512. forcedinline void desaturate() throw()
  15513. {
  15514. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  15515. }
  15516. /** The indexes of the different components in the byte layout of this type of colour. */
  15517. #if JUCE_MAC
  15518. enum { indexR = 0, indexG = 1, indexB = 2 };
  15519. #else
  15520. enum { indexR = 2, indexG = 1, indexB = 0 };
  15521. #endif
  15522. private:
  15523. #if JUCE_MAC
  15524. uint8 r, g, b;
  15525. #else
  15526. uint8 b, g, r;
  15527. #endif
  15528. } PACKED;
  15529. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  15530. {
  15531. set (src);
  15532. }
  15533. /**
  15534. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  15535. This is used internally by the imaging classes.
  15536. @see PixelARGB, PixelRGB
  15537. */
  15538. class JUCE_API PixelAlpha
  15539. {
  15540. public:
  15541. /** Creates a pixel without defining its colour. */
  15542. PixelAlpha() throw() {}
  15543. ~PixelAlpha() throw() {}
  15544. /** Creates a pixel from a 32-bit argb value.
  15545. (The argb format is that used by PixelARGB)
  15546. */
  15547. PixelAlpha (const uint32 argb) throw()
  15548. {
  15549. a = (uint8) (argb >> 24);
  15550. }
  15551. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  15552. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  15553. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  15554. forcedinline uint8 getAlpha() const throw() { return a; }
  15555. forcedinline uint8 getRed() const throw() { return 0; }
  15556. forcedinline uint8 getGreen() const throw() { return 0; }
  15557. forcedinline uint8 getBlue() const throw() { return 0; }
  15558. /** Blends another pixel onto this one.
  15559. This takes into account the opacity of the pixel being overlaid, and blends
  15560. it accordingly.
  15561. */
  15562. template <class Pixel>
  15563. forcedinline void blend (const Pixel& src) throw()
  15564. {
  15565. const int srcA = src.getAlpha();
  15566. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  15567. }
  15568. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  15569. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  15570. being used, so this can blend semi-transparently from a PixelRGB argument.
  15571. */
  15572. template <class Pixel>
  15573. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  15574. {
  15575. ++extraAlpha;
  15576. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  15577. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  15578. }
  15579. /** Blends another pixel with this one, creating a colour that is somewhere
  15580. between the two, as specified by the amount.
  15581. */
  15582. template <class Pixel>
  15583. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  15584. {
  15585. a += ((src,getAlpha() - a) * amount) >> 8;
  15586. }
  15587. /** Copies another pixel colour over this one.
  15588. This doesn't blend it - this colour is simply replaced by the other one.
  15589. */
  15590. template <class Pixel>
  15591. forcedinline void set (const Pixel& src) throw()
  15592. {
  15593. a = src.getAlpha();
  15594. }
  15595. /** Replaces the colour's alpha value with another one. */
  15596. forcedinline void setAlpha (const uint8 newAlpha) throw()
  15597. {
  15598. a = newAlpha;
  15599. }
  15600. /** Multiplies the colour's alpha value with another one. */
  15601. forcedinline void multiplyAlpha (int multiplier) throw()
  15602. {
  15603. ++multiplier;
  15604. a = (uint8) ((a * multiplier) >> 8);
  15605. }
  15606. forcedinline void multiplyAlpha (const float multiplier) throw()
  15607. {
  15608. a = (uint8) (a * multiplier);
  15609. }
  15610. /** Sets the pixel's colour from individual components. */
  15611. forcedinline void setARGB (const uint8 a_, const uint8 r, const uint8 g, const uint8 b) throw()
  15612. {
  15613. a = a_;
  15614. }
  15615. /** Premultiplies the pixel's RGB values by its alpha. */
  15616. forcedinline void premultiply() throw()
  15617. {
  15618. }
  15619. /** Unpremultiplies the pixel's RGB values. */
  15620. forcedinline void unpremultiply() throw()
  15621. {
  15622. }
  15623. forcedinline void desaturate() throw()
  15624. {
  15625. }
  15626. private:
  15627. uint8 a : 8;
  15628. } PACKED;
  15629. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  15630. {
  15631. blend (PixelARGB (src.getARGB()));
  15632. }
  15633. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  15634. {
  15635. uint32 sargb = src.getARGB();
  15636. const uint32 alpha = 0x100 - (sargb >> 24);
  15637. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  15638. sargb += 0xff00ff00 & (getAG() * alpha);
  15639. argb = sargb;
  15640. }
  15641. #if JUCE_MSVC
  15642. #pragma pack (pop)
  15643. #endif
  15644. #undef PACKED
  15645. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  15646. /********* End of inlined file: juce_PixelFormats.h *********/
  15647. /**
  15648. Represents a colour, also including a transparency value.
  15649. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  15650. */
  15651. class JUCE_API Colour
  15652. {
  15653. public:
  15654. /** Creates a transparent black colour. */
  15655. Colour() throw();
  15656. /** Creates a copy of another Colour object. */
  15657. Colour (const Colour& other) throw();
  15658. /** Creates a colour from a 32-bit ARGB value.
  15659. The format of this number is:
  15660. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  15661. All components in the range 0x00 to 0xff.
  15662. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15663. @see getPixelARGB
  15664. */
  15665. explicit Colour (const uint32 argb) throw();
  15666. /** Creates an opaque colour using 8-bit red, green and blue values */
  15667. Colour (const uint8 red,
  15668. const uint8 green,
  15669. const uint8 blue) throw();
  15670. /** Creates an opaque colour using 8-bit red, green and blue values */
  15671. static const Colour fromRGB (const uint8 red,
  15672. const uint8 green,
  15673. const uint8 blue) throw();
  15674. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  15675. Colour (const uint8 red,
  15676. const uint8 green,
  15677. const uint8 blue,
  15678. const uint8 alpha) throw();
  15679. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  15680. static const Colour fromRGBA (const uint8 red,
  15681. const uint8 green,
  15682. const uint8 blue,
  15683. const uint8 alpha) throw();
  15684. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  15685. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  15686. Values outside the valid range will be clipped.
  15687. */
  15688. Colour (const uint8 red,
  15689. const uint8 green,
  15690. const uint8 blue,
  15691. const float alpha) throw();
  15692. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  15693. static const Colour fromRGBAFloat (const uint8 red,
  15694. const uint8 green,
  15695. const uint8 blue,
  15696. const float alpha) throw();
  15697. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  15698. The floating point values must be between 0.0 and 1.0.
  15699. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15700. Values outside the valid range will be clipped.
  15701. */
  15702. Colour (const float hue,
  15703. const float saturation,
  15704. const float brightness,
  15705. const uint8 alpha) throw();
  15706. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  15707. All values must be between 0.0 and 1.0.
  15708. Numbers outside the valid range will be clipped.
  15709. */
  15710. Colour (const float hue,
  15711. const float saturation,
  15712. const float brightness,
  15713. const float alpha) throw();
  15714. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  15715. The floating point values must be between 0.0 and 1.0.
  15716. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  15717. Values outside the valid range will be clipped.
  15718. */
  15719. static const Colour fromHSV (const float hue,
  15720. const float saturation,
  15721. const float brightness,
  15722. const float alpha) throw();
  15723. /** Destructor. */
  15724. ~Colour() throw();
  15725. /** Copies another Colour object. */
  15726. const Colour& operator= (const Colour& other) throw();
  15727. /** Compares two colours. */
  15728. bool operator== (const Colour& other) const throw();
  15729. /** Compares two colours. */
  15730. bool operator!= (const Colour& other) const throw();
  15731. /** Returns the red component of this colour.
  15732. @returns a value between 0x00 and 0xff.
  15733. */
  15734. uint8 getRed() const throw() { return argb.getRed(); }
  15735. /** Returns the green component of this colour.
  15736. @returns a value between 0x00 and 0xff.
  15737. */
  15738. uint8 getGreen() const throw() { return argb.getGreen(); }
  15739. /** Returns the blue component of this colour.
  15740. @returns a value between 0x00 and 0xff.
  15741. */
  15742. uint8 getBlue() const throw() { return argb.getBlue(); }
  15743. /** Returns the red component of this colour as a floating point value.
  15744. @returns a value between 0.0 and 1.0
  15745. */
  15746. float getFloatRed() const throw();
  15747. /** Returns the green component of this colour as a floating point value.
  15748. @returns a value between 0.0 and 1.0
  15749. */
  15750. float getFloatGreen() const throw();
  15751. /** Returns the blue component of this colour as a floating point value.
  15752. @returns a value between 0.0 and 1.0
  15753. */
  15754. float getFloatBlue() const throw();
  15755. /** Returns a premultiplied ARGB pixel object that represents this colour.
  15756. */
  15757. const PixelARGB getPixelARGB() const throw();
  15758. /** Returns a 32-bit integer that represents this colour.
  15759. The format of this number is:
  15760. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  15761. */
  15762. uint32 getARGB() const throw();
  15763. /** Returns the colour's alpha (opacity).
  15764. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  15765. */
  15766. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  15767. /** Returns the colour's alpha (opacity) as a floating point value.
  15768. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  15769. */
  15770. float getFloatAlpha() const throw();
  15771. /** Returns true if this colour is completely opaque.
  15772. Equivalent to (getAlpha() == 0xff).
  15773. */
  15774. bool isOpaque() const throw();
  15775. /** Returns true if this colour is completely transparent.
  15776. Equivalent to (getAlpha() == 0x00).
  15777. */
  15778. bool isTransparent() const throw();
  15779. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  15780. const Colour withAlpha (const uint8 newAlpha) const throw();
  15781. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  15782. const Colour withAlpha (const float newAlpha) const throw();
  15783. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  15784. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  15785. */
  15786. const Colour withMultipliedAlpha (const float alphaMultiplier) const throw();
  15787. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  15788. If the foreground colour is semi-transparent, it is blended onto this colour
  15789. accordingly.
  15790. */
  15791. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  15792. /** Returns a colour that lies somewhere between this one and another.
  15793. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  15794. is 1.0, the result is 100% of the other colour.
  15795. */
  15796. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  15797. /** Returns the colour's hue component.
  15798. The value returned is in the range 0.0 to 1.0
  15799. */
  15800. float getHue() const throw();
  15801. /** Returns the colour's saturation component.
  15802. The value returned is in the range 0.0 to 1.0
  15803. */
  15804. float getSaturation() const throw();
  15805. /** Returns the colour's brightness component.
  15806. The value returned is in the range 0.0 to 1.0
  15807. */
  15808. float getBrightness() const throw();
  15809. /** Returns the colour's hue, saturation and brightness components all at once.
  15810. The values returned are in the range 0.0 to 1.0
  15811. */
  15812. void getHSB (float& hue,
  15813. float& saturation,
  15814. float& brightness) const throw();
  15815. /** Returns a copy of this colour with a different hue. */
  15816. const Colour withHue (const float newHue) const throw();
  15817. /** Returns a copy of this colour with a different saturation. */
  15818. const Colour withSaturation (const float newSaturation) const throw();
  15819. /** Returns a copy of this colour with a different brightness.
  15820. @see brighter, darker, withMultipliedBrightness
  15821. */
  15822. const Colour withBrightness (const float newBrightness) const throw();
  15823. /** Returns a copy of this colour with it hue rotated.
  15824. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  15825. @see brighter, darker, withMultipliedBrightness
  15826. */
  15827. const Colour withRotatedHue (const float amountToRotate) const throw();
  15828. /** Returns a copy of this colour with its saturation multiplied by the given value.
  15829. The new colour's saturation is (this->getSaturation() * multiplier)
  15830. (the result is clipped to legal limits).
  15831. */
  15832. const Colour withMultipliedSaturation (const float multiplier) const throw();
  15833. /** Returns a copy of this colour with its brightness multiplied by the given value.
  15834. The new colour's saturation is (this->getBrightness() * multiplier)
  15835. (the result is clipped to legal limits).
  15836. */
  15837. const Colour withMultipliedBrightness (const float amount) const throw();
  15838. /** Returns a brighter version of this colour.
  15839. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  15840. unchanged, and higher values make it brighter
  15841. @see withMultipliedBrightness
  15842. */
  15843. const Colour brighter (float amountBrighter = 0.4f) const throw();
  15844. /** Returns a darker version of this colour.
  15845. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  15846. unchanged, and higher values make it darker
  15847. @see withMultipliedBrightness
  15848. */
  15849. const Colour darker (float amountDarker = 0.4f) const throw();
  15850. /** Returns a colour that will be clearly visible against this colour.
  15851. The amount parameter indicates how contrasting the new colour should
  15852. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  15853. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  15854. return white; Colours::white.contrasting (1.0f) will return black, etc.
  15855. */
  15856. const Colour contrasting (const float amount = 1.0f) const throw();
  15857. /** Returns a colour that contrasts against two colours.
  15858. Looks for a colour that contrasts with both of the colours passed-in.
  15859. Handy for things like choosing a highlight colour in text editors, etc.
  15860. */
  15861. static const Colour contrasting (const Colour& colour1,
  15862. const Colour& colour2) throw();
  15863. /** Returns an opaque shade of grey.
  15864. @param brightness the level of grey to return - 0 is black, 1.0 is white
  15865. */
  15866. static const Colour greyLevel (const float brightness) throw();
  15867. /** Returns a stringified version of this colour.
  15868. The string can be turned back into a colour using the fromString() method.
  15869. */
  15870. const String toString() const throw();
  15871. /** Reads the colour from a string that was created with toString().
  15872. */
  15873. static const Colour fromString (const String& encodedColourString);
  15874. juce_UseDebuggingNewOperator
  15875. private:
  15876. PixelARGB argb;
  15877. };
  15878. #endif // __JUCE_COLOUR_JUCEHEADER__
  15879. /********* End of inlined file: juce_Colour.h *********/
  15880. /**
  15881. Contains a set of predefined named colours (mostly standard HTML colours)
  15882. @see Colour, Colours::greyLevel
  15883. */
  15884. class Colours
  15885. {
  15886. public:
  15887. static JUCE_API const Colour
  15888. transparentBlack, /**< ARGB = 0x00000000 */
  15889. transparentWhite, /**< ARGB = 0x00ffffff */
  15890. black, /**< ARGB = 0xff000000 */
  15891. white, /**< ARGB = 0xffffffff */
  15892. blue, /**< ARGB = 0xff0000ff */
  15893. grey, /**< ARGB = 0xff808080 */
  15894. green, /**< ARGB = 0xff008000 */
  15895. red, /**< ARGB = 0xffff0000 */
  15896. yellow, /**< ARGB = 0xffffff00 */
  15897. aliceblue, antiquewhite, aqua, aquamarine,
  15898. azure, beige, bisque, blanchedalmond,
  15899. blueviolet, brown, burlywood, cadetblue,
  15900. chartreuse, chocolate, coral, cornflowerblue,
  15901. cornsilk, crimson, cyan, darkblue,
  15902. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  15903. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  15904. darkorchid, darkred, darksalmon, darkseagreen,
  15905. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  15906. deeppink, deepskyblue, dimgrey, dodgerblue,
  15907. firebrick, floralwhite, forestgreen, fuchsia,
  15908. gainsboro, gold, goldenrod, greenyellow,
  15909. honeydew, hotpink, indianred, indigo,
  15910. ivory, khaki, lavender, lavenderblush,
  15911. lemonchiffon, lightblue, lightcoral, lightcyan,
  15912. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  15913. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  15914. lightsteelblue, lightyellow, lime, limegreen,
  15915. linen, magenta, maroon, mediumaquamarine,
  15916. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  15917. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  15918. midnightblue, mintcream, mistyrose, navajowhite,
  15919. navy, oldlace, olive, olivedrab,
  15920. orange, orangered, orchid, palegoldenrod,
  15921. palegreen, paleturquoise, palevioletred, papayawhip,
  15922. peachpuff, peru, pink, plum,
  15923. powderblue, purple, rosybrown, royalblue,
  15924. saddlebrown, salmon, sandybrown, seagreen,
  15925. seashell, sienna, silver, skyblue,
  15926. slateblue, slategrey, snow, springgreen,
  15927. steelblue, tan, teal, thistle,
  15928. tomato, turquoise, violet, wheat,
  15929. whitesmoke, yellowgreen;
  15930. /** Attempts to look up a string in the list of known colour names, and return
  15931. the appropriate colour.
  15932. A non-case-sensitive search is made of the list of predefined colours, and
  15933. if a match is found, that colour is returned. If no match is found, the
  15934. colour passed in as the defaultColour parameter is returned.
  15935. */
  15936. static JUCE_API const Colour findColourForName (const String& colourName,
  15937. const Colour& defaultColour);
  15938. private:
  15939. // this isn't a class you should ever instantiate - it's just here for the
  15940. // static values in it.
  15941. Colours();
  15942. };
  15943. #endif // __JUCE_COLOURS_JUCEHEADER__
  15944. /********* End of inlined file: juce_Colours.h *********/
  15945. /********* Start of inlined file: juce_FillType.h *********/
  15946. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  15947. #define __JUCE_FILLTYPE_JUCEHEADER__
  15948. /********* Start of inlined file: juce_ColourGradient.h *********/
  15949. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  15950. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  15951. /**
  15952. Describes the layout and colours that should be used to paint a colour gradient.
  15953. @see Graphics::setGradientFill
  15954. */
  15955. class JUCE_API ColourGradient
  15956. {
  15957. public:
  15958. /** Creates a gradient object.
  15959. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  15960. colour2 should be. In between them there's a gradient.
  15961. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  15962. its centre.
  15963. The alpha transparencies of the colours are used, so note that
  15964. if you blend from transparent to a solid colour, the RGB of the transparent
  15965. colour will become visible in parts of the gradient. e.g. blending
  15966. from Colour::transparentBlack to Colours::white will produce a
  15967. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  15968. will be white all the way across.
  15969. @see ColourGradient
  15970. */
  15971. ColourGradient (const Colour& colour1,
  15972. const float x1,
  15973. const float y1,
  15974. const Colour& colour2,
  15975. const float x2,
  15976. const float y2,
  15977. const bool isRadial) throw();
  15978. /** Creates an uninitialised gradient.
  15979. If you use this constructor instead of the other one, be sure to set all the
  15980. object's public member variables before using it!
  15981. */
  15982. ColourGradient() throw();
  15983. /** Destructor */
  15984. ~ColourGradient() throw();
  15985. /** Removes any colours that have been added.
  15986. This will also remove any start and end colours, so the gradient won't work. You'll
  15987. need to add more colours with addColour().
  15988. */
  15989. void clearColours() throw();
  15990. /** Adds a colour at a point along the length of the gradient.
  15991. This allows the gradient to go through a spectrum of colours, instead of just a
  15992. start and end colour.
  15993. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  15994. of the distance along the line between the two points
  15995. at which the colour should occur.
  15996. @param colour the colour that should be used at this point
  15997. */
  15998. void addColour (const double proportionAlongGradient,
  15999. const Colour& colour) throw();
  16000. /** Multiplies the alpha value of all the colours by the given scale factor */
  16001. void multiplyOpacity (const float multiplier) throw();
  16002. /** Returns the number of colour-stops that have been added. */
  16003. int getNumColours() const throw();
  16004. /** Returns the position along the length of the gradient of the colour with this index.
  16005. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  16006. */
  16007. double getColourPosition (const int index) const throw();
  16008. /** Returns the colour that was added with a given index.
  16009. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  16010. */
  16011. const Colour getColour (const int index) const throw();
  16012. /** Returns the an interpolated colour at any position along the gradient.
  16013. @param position the position along the gradient, between 0 and 1
  16014. */
  16015. const Colour getColourAtPosition (const float position) const throw();
  16016. /** Creates a set of interpolated premultiplied ARGB values.
  16017. This will resize the HeapBlock, fill it with the colours, and will return the number of
  16018. colours that it added.
  16019. */
  16020. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const throw();
  16021. /** Returns true if all colours are opaque. */
  16022. bool isOpaque() const throw();
  16023. /** Returns true if all colours are completely transparent. */
  16024. bool isInvisible() const throw();
  16025. float x1;
  16026. float y1;
  16027. float x2;
  16028. float y2;
  16029. /** If true, the gradient should be filled circularly, centred around
  16030. (x1, y1), with (x2, y2) defining a point on the circumference.
  16031. If false, the gradient is linear between the two points.
  16032. */
  16033. bool isRadial;
  16034. juce_UseDebuggingNewOperator
  16035. private:
  16036. Array <uint32> colours;
  16037. };
  16038. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  16039. /********* End of inlined file: juce_ColourGradient.h *********/
  16040. class Image;
  16041. /**
  16042. Represents a colour or fill pattern to use for rendering paths.
  16043. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  16044. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  16045. @see Graphics::setFillType, DrawablePath::setFill
  16046. */
  16047. class JUCE_API FillType
  16048. {
  16049. public:
  16050. /** Creates a default fill type, of solid black. */
  16051. FillType() throw();
  16052. /** Creates a fill type of a solid colour.
  16053. @see setColour
  16054. */
  16055. FillType (const Colour& colour) throw();
  16056. /** Creates a gradient fill type.
  16057. @see setGradient
  16058. */
  16059. FillType (const ColourGradient& gradient) throw();
  16060. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  16061. and rotation of the pattern.
  16062. @see setTiledImage
  16063. */
  16064. FillType (const Image& image, const AffineTransform& transform) throw();
  16065. /** Creates a copy of another FillType. */
  16066. FillType (const FillType& other) throw();
  16067. /** Makes a copy of another FillType. */
  16068. const FillType& operator= (const FillType& other) throw();
  16069. /** Destructor. */
  16070. ~FillType() throw();
  16071. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  16072. bool isColour() const throw() { return gradient == 0 && image == 0; }
  16073. /** Returns true if this is a gradient fill. */
  16074. bool isGradient() const throw() { return gradient != 0; }
  16075. /** Returns true if this is a tiled image pattern fill. */
  16076. bool isTiledImage() const throw() { return image != 0; }
  16077. /** Turns this object into a solid colour fill.
  16078. If the object was an image or gradient, those fields will no longer be valid. */
  16079. void setColour (const Colour& newColour) throw();
  16080. /** Turns this object into a gradient fill. */
  16081. void setGradient (const ColourGradient& newGradient) throw();
  16082. /** Turns this object into a tiled image fill type. The transform allows you to set
  16083. the scaling, offset and rotation of the pattern.
  16084. */
  16085. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  16086. /** Changes the opacity that should be used.
  16087. If the fill is a solid colour, this just changes the opacity of that colour. For
  16088. gradients and image tiles, it changes the opacity that will be used for them.
  16089. */
  16090. void setOpacity (const float newOpacity) throw();
  16091. /** Returns the current opacity to be applied to the colour, gradient, or image.
  16092. @see setOpacity
  16093. */
  16094. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  16095. /** The solid colour being used.
  16096. If the fill type is not a solid colour, the alpha channel of this colour indicates
  16097. the opacity that should be used for the fill, and the RGB channels are ignored.
  16098. */
  16099. Colour colour;
  16100. /** Returns the gradient that should be used for filling.
  16101. This will be zero if the object is some other type of fill.
  16102. If a gradient is active, the overall opacity with which it should be applied
  16103. is indicated by the alpha channel of the colour variable.
  16104. */
  16105. ScopedPointer <ColourGradient> gradient;
  16106. /** Returns the image that should be used for tiling.
  16107. The FillType object just keeps a pointer to this image, it doesn't own it, so you have to
  16108. be careful to make sure the image doesn't get deleted while it's being used.
  16109. If an image fill is active, the overall opacity with which it should be applied
  16110. is indicated by the alpha channel of the colour variable.
  16111. */
  16112. const Image* image;
  16113. /** The transform that should be applied to the image or gradient that's being drawn.
  16114. */
  16115. AffineTransform transform;
  16116. juce_UseDebuggingNewOperator
  16117. };
  16118. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  16119. /********* End of inlined file: juce_FillType.h *********/
  16120. /********* Start of inlined file: juce_RectanglePlacement.h *********/
  16121. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  16122. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  16123. /**
  16124. Defines the method used to postion some kind of rectangular object within
  16125. a rectangular viewport.
  16126. Although similar to Justification, this is more specific, and has some extra
  16127. options.
  16128. */
  16129. class JUCE_API RectanglePlacement
  16130. {
  16131. public:
  16132. /** Creates a RectanglePlacement object using a combination of flags. */
  16133. inline RectanglePlacement (const int flags_) throw() : flags (flags_) {}
  16134. /** Creates a copy of another Justification object. */
  16135. RectanglePlacement (const RectanglePlacement& other) throw();
  16136. /** Copies another Justification object. */
  16137. const RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  16138. /** Flag values that can be combined and used in the constructor. */
  16139. enum
  16140. {
  16141. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  16142. xLeft = 1,
  16143. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  16144. xRight = 2,
  16145. /** Indicates that the source should be placed in the centre between the left and right
  16146. sides of the available space. */
  16147. xMid = 4,
  16148. /** Indicates that the source's top edge should be aligned with the top edge of the
  16149. destination rectangle. */
  16150. yTop = 8,
  16151. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  16152. destination rectangle. */
  16153. yBottom = 16,
  16154. /** Indicates that the source should be placed in the centre between the top and bottom
  16155. sides of the available space. */
  16156. yMid = 32,
  16157. /** If this flag is set, then the source rectangle will be resized to completely fill
  16158. the destination rectangle, and all other flags are ignored.
  16159. */
  16160. stretchToFit = 64,
  16161. /** If this flag is set, then the source rectangle will be resized so that it is the
  16162. minimum size to completely fill the destination rectangle, without changing its
  16163. aspect ratio. This means that some of the source rectangle may fall outside
  16164. the destination.
  16165. If this flag is not set, the source will be given the maximum size at which none
  16166. of it falls outside the destination rectangle.
  16167. */
  16168. fillDestination = 128,
  16169. /** Indicates that the source rectangle can be reduced in size if required, but should
  16170. never be made larger than its original size.
  16171. */
  16172. onlyReduceInSize = 256,
  16173. /** Indicates that the source rectangle can be enlarged if required, but should
  16174. never be made smaller than its original size.
  16175. */
  16176. onlyIncreaseInSize = 512,
  16177. /** Indicates that the source rectangle's size should be left unchanged.
  16178. */
  16179. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  16180. /** A shorthand value that is equivalent to (xMid | yMid). */
  16181. centred = 4 + 32
  16182. };
  16183. /** Returns the raw flags that are set for this object. */
  16184. inline int getFlags() const throw() { return flags; }
  16185. /** Tests a set of flags for this object.
  16186. @returns true if any of the flags passed in are set on this object.
  16187. */
  16188. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  16189. /** Adjusts the position and size of a rectangle to fit it into a space.
  16190. The source rectangle co-ordinates will be adjusted so that they fit into
  16191. the destination rectangle based on this object's flags.
  16192. */
  16193. void applyTo (double& sourceX,
  16194. double& sourceY,
  16195. double& sourceW,
  16196. double& sourceH,
  16197. const double destinationX,
  16198. const double destinationY,
  16199. const double destinationW,
  16200. const double destinationH) const throw();
  16201. /** Returns the transform that should be applied to these source co-ordinates to fit them
  16202. into the destination rectangle using the current flags.
  16203. */
  16204. const AffineTransform getTransformToFit (float sourceX,
  16205. float sourceY,
  16206. float sourceW,
  16207. float sourceH,
  16208. const float destinationX,
  16209. const float destinationY,
  16210. const float destinationW,
  16211. const float destinationH) const throw();
  16212. private:
  16213. int flags;
  16214. };
  16215. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  16216. /********* End of inlined file: juce_RectanglePlacement.h *********/
  16217. class LowLevelGraphicsContext;
  16218. class Image;
  16219. class RectangleList;
  16220. /**
  16221. A graphics context, used for drawing a component or image.
  16222. When a Component needs painting, a Graphics context is passed to its
  16223. Component::paint() method, and this you then call methods within this
  16224. object to actually draw the component's content.
  16225. A Graphics can also be created from an image, to allow drawing directly onto
  16226. that image.
  16227. @see Component::paint
  16228. */
  16229. class JUCE_API Graphics
  16230. {
  16231. public:
  16232. /** Creates a Graphics object to draw directly onto the given image.
  16233. The graphics object that is created will be set up to draw onto the image,
  16234. with the context's clipping area being the entire size of the image, and its
  16235. origin being the image's origin. To draw into a subsection of an image, use the
  16236. reduceClipRegion() and setOrigin() methods.
  16237. Obviously you shouldn't delete the image before this context is deleted.
  16238. */
  16239. Graphics (Image& imageToDrawOnto) throw();
  16240. /** Destructor. */
  16241. ~Graphics() throw();
  16242. /** Changes the current drawing colour.
  16243. This sets the colour that will now be used for drawing operations - it also
  16244. sets the opacity to that of the colour passed-in.
  16245. If a brush is being used when this method is called, the brush will be deselected,
  16246. and any subsequent drawing will be done with a solid colour brush instead.
  16247. @see setOpacity
  16248. */
  16249. void setColour (const Colour& newColour) throw();
  16250. /** Changes the opacity to use with the current colour.
  16251. If a solid colour is being used for drawing, this changes its opacity
  16252. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  16253. If a gradient is being used, this will have no effect on it.
  16254. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  16255. */
  16256. void setOpacity (const float newOpacity) throw();
  16257. /** Sets the context to use a gradient for its fill pattern.
  16258. */
  16259. void setGradientFill (const ColourGradient& gradient) throw();
  16260. /** Sets the context to use a tiled image pattern for filling.
  16261. Make sure that you don't delete this image while it's still being used by
  16262. this context!
  16263. */
  16264. void setTiledImageFill (const Image& imageToUse,
  16265. const int anchorX,
  16266. const int anchorY,
  16267. const float opacity) throw();
  16268. /** Changes the current fill settings.
  16269. @see setColour, setGradientFill, setTiledImageFill
  16270. */
  16271. void setFillType (const FillType& newFill) throw();
  16272. /** Changes the font to use for subsequent text-drawing functions.
  16273. Note there's also a setFont (float, int) method to quickly change the size and
  16274. style of the current font.
  16275. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  16276. */
  16277. void setFont (const Font& newFont) throw();
  16278. /** Changes the size and style of the currently-selected font.
  16279. This is a convenient shortcut that changes the context's current font to a
  16280. different size or style. The typeface won't be changed.
  16281. @see Font
  16282. */
  16283. void setFont (const float newFontHeight,
  16284. const int fontStyleFlags = Font::plain) throw();
  16285. /** Draws a one-line text string.
  16286. This will use the current colour (or brush) to fill the text. The font is the last
  16287. one specified by setFont().
  16288. @param text the string to draw
  16289. @param startX the position to draw the left-hand edge of the text
  16290. @param baselineY the position of the text's baseline
  16291. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  16292. */
  16293. void drawSingleLineText (const String& text,
  16294. const int startX,
  16295. const int baselineY) const throw();
  16296. /** Draws text across multiple lines.
  16297. This will break the text onto a new line where there's a new-line or
  16298. carriage-return character, or at a word-boundary when the text becomes wider
  16299. than the size specified by the maximumLineWidth parameter.
  16300. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  16301. */
  16302. void drawMultiLineText (const String& text,
  16303. const int startX,
  16304. const int baselineY,
  16305. const int maximumLineWidth) const throw();
  16306. /** Renders a string of text as a vector path.
  16307. This allows a string to be transformed with an arbitrary AffineTransform and
  16308. rendered using the current colour/brush. It's much slower than the normal text methods
  16309. but more accurate.
  16310. @see setFont
  16311. */
  16312. void drawTextAsPath (const String& text,
  16313. const AffineTransform& transform) const throw();
  16314. /** Draws a line of text within a specified rectangle.
  16315. The text will be positioned within the rectangle based on the justification
  16316. flags passed-in. If the string is too long to fit inside the rectangle, it will
  16317. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  16318. flag is true).
  16319. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  16320. */
  16321. void drawText (const String& text,
  16322. const int x,
  16323. const int y,
  16324. const int width,
  16325. const int height,
  16326. const Justification& justificationType,
  16327. const bool useEllipsesIfTooBig) const throw();
  16328. /** Tries to draw a text string inside a given space.
  16329. This does its best to make the given text readable within the specified rectangle,
  16330. so it useful for labelling things.
  16331. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  16332. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  16333. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  16334. it's been truncated.
  16335. A Justification parameter lets you specify how the text is laid out within the rectangle,
  16336. both horizontally and vertically.
  16337. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  16338. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  16339. can set this value to 1.0f.
  16340. @see GlyphArrangement::addFittedText
  16341. */
  16342. void drawFittedText (const String& text,
  16343. const int x,
  16344. const int y,
  16345. const int width,
  16346. const int height,
  16347. const Justification& justificationFlags,
  16348. const int maximumNumberOfLines,
  16349. const float minimumHorizontalScale = 0.7f) const throw();
  16350. /** Fills the context's entire clip region with the current colour or brush.
  16351. (See also the fillAll (const Colour&) method which is a quick way of filling
  16352. it with a given colour).
  16353. */
  16354. void fillAll() const throw();
  16355. /** Fills the context's entire clip region with a given colour.
  16356. This leaves the context's current colour and brush unchanged, it just
  16357. uses the specified colour temporarily.
  16358. */
  16359. void fillAll (const Colour& colourToUse) const throw();
  16360. /** Fills a rectangle with the current colour or brush.
  16361. @see drawRect, fillRoundedRectangle
  16362. */
  16363. void fillRect (int x,
  16364. int y,
  16365. int width,
  16366. int height) const throw();
  16367. /** Fills a rectangle with the current colour or brush. */
  16368. void fillRect (const Rectangle& rectangle) const throw();
  16369. /** Fills a rectangle with the current colour or brush.
  16370. This uses sub-pixel positioning so is slower than the fillRect method which
  16371. takes integer co-ordinates.
  16372. */
  16373. void fillRect (const float x,
  16374. const float y,
  16375. const float width,
  16376. const float height) const throw();
  16377. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  16378. @see drawRoundedRectangle, Path::addRoundedRectangle
  16379. */
  16380. void fillRoundedRectangle (const float x,
  16381. const float y,
  16382. const float width,
  16383. const float height,
  16384. const float cornerSize) const throw();
  16385. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  16386. @see drawRoundedRectangle, Path::addRoundedRectangle
  16387. */
  16388. void fillRoundedRectangle (const Rectangle& rectangle,
  16389. const float cornerSize) const throw();
  16390. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  16391. */
  16392. void fillCheckerBoard (int x, int y,
  16393. int width, int height,
  16394. const int checkWidth,
  16395. const int checkHeight,
  16396. const Colour& colour1,
  16397. const Colour& colour2) const throw();
  16398. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16399. The lines are drawn inside the given rectangle, and greater line thicknesses
  16400. extend inwards.
  16401. @see fillRect
  16402. */
  16403. void drawRect (const int x,
  16404. const int y,
  16405. const int width,
  16406. const int height,
  16407. const int lineThickness = 1) const throw();
  16408. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16409. The lines are drawn inside the given rectangle, and greater line thicknesses
  16410. extend inwards.
  16411. @see fillRect
  16412. */
  16413. void drawRect (const float x,
  16414. const float y,
  16415. const float width,
  16416. const float height,
  16417. const float lineThickness = 1.0f) const throw();
  16418. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  16419. The lines are drawn inside the given rectangle, and greater line thicknesses
  16420. extend inwards.
  16421. @see fillRect
  16422. */
  16423. void drawRect (const Rectangle& rectangle,
  16424. const int lineThickness = 1) const throw();
  16425. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  16426. @see fillRoundedRectangle, Path::addRoundedRectangle
  16427. */
  16428. void drawRoundedRectangle (const float x,
  16429. const float y,
  16430. const float width,
  16431. const float height,
  16432. const float cornerSize,
  16433. const float lineThickness) const throw();
  16434. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  16435. @see fillRoundedRectangle, Path::addRoundedRectangle
  16436. */
  16437. void drawRoundedRectangle (const Rectangle& rectangle,
  16438. const float cornerSize,
  16439. const float lineThickness) const throw();
  16440. /** Draws a 3D raised (or indented) bevel using two colours.
  16441. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  16442. extend inwards.
  16443. The top-left colour is used for the top- and left-hand edges of the
  16444. bevel; the bottom-right colour is used for the bottom- and right-hand
  16445. edges.
  16446. If useGradient is true, then the bevel fades out to make it look more curved
  16447. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  16448. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  16449. the centre edges are sharp and it fades towards the outside.
  16450. */
  16451. void drawBevel (const int x,
  16452. const int y,
  16453. const int width,
  16454. const int height,
  16455. const int bevelThickness,
  16456. const Colour& topLeftColour = Colours::white,
  16457. const Colour& bottomRightColour = Colours::black,
  16458. const bool useGradient = true,
  16459. const bool sharpEdgeOnOutside = true) const throw();
  16460. /** Draws a pixel using the current colour or brush.
  16461. */
  16462. void setPixel (int x, int y) const throw();
  16463. /** Fills an ellipse with the current colour or brush.
  16464. The ellipse is drawn to fit inside the given rectangle.
  16465. @see drawEllipse, Path::addEllipse
  16466. */
  16467. void fillEllipse (const float x,
  16468. const float y,
  16469. const float width,
  16470. const float height) const throw();
  16471. /** Draws an elliptical stroke using the current colour or brush.
  16472. @see fillEllipse, Path::addEllipse
  16473. */
  16474. void drawEllipse (const float x,
  16475. const float y,
  16476. const float width,
  16477. const float height,
  16478. const float lineThickness) const throw();
  16479. /** Draws a line between two points.
  16480. The line is 1 pixel wide and drawn with the current colour or brush.
  16481. */
  16482. void drawLine (float startX,
  16483. float startY,
  16484. float endX,
  16485. float endY) const throw();
  16486. /** Draws a line between two points with a given thickness.
  16487. @see Path::addLineSegment
  16488. */
  16489. void drawLine (const float startX,
  16490. const float startY,
  16491. const float endX,
  16492. const float endY,
  16493. const float lineThickness) const throw();
  16494. /** Draws a line between two points.
  16495. The line is 1 pixel wide and drawn with the current colour or brush.
  16496. */
  16497. void drawLine (const Line& line) const throw();
  16498. /** Draws a line between two points with a given thickness.
  16499. @see Path::addLineSegment
  16500. */
  16501. void drawLine (const Line& line,
  16502. const float lineThickness) const throw();
  16503. /** Draws a dashed line using a custom set of dash-lengths.
  16504. @param startX the line's start x co-ordinate
  16505. @param startY the line's start y co-ordinate
  16506. @param endX the line's end x co-ordinate
  16507. @param endY the line's end y co-ordinate
  16508. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  16509. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  16510. draw 6 pixels, skip 7 pixels, and then repeat.
  16511. @param numDashLengths the number of elements in the array (this must be an even number).
  16512. @param lineThickness the thickness of the line to draw
  16513. @see PathStrokeType::createDashedStroke
  16514. */
  16515. void drawDashedLine (const float startX,
  16516. const float startY,
  16517. const float endX,
  16518. const float endY,
  16519. const float* const dashLengths,
  16520. const int numDashLengths,
  16521. const float lineThickness = 1.0f) const throw();
  16522. /** Draws a vertical line of pixels at a given x position.
  16523. The x position is an integer, but the top and bottom of the line can be sub-pixel
  16524. positions, and these will be anti-aliased if necessary.
  16525. */
  16526. void drawVerticalLine (const int x, float top, float bottom) const throw();
  16527. /** Draws a horizontal line of pixels at a given y position.
  16528. The y position is an integer, but the left and right ends of the line can be sub-pixel
  16529. positions, and these will be anti-aliased if necessary.
  16530. */
  16531. void drawHorizontalLine (const int y, float left, float right) const throw();
  16532. /** Fills a path using the currently selected colour or brush.
  16533. */
  16534. void fillPath (const Path& path,
  16535. const AffineTransform& transform = AffineTransform::identity) const throw();
  16536. /** Draws a path's outline using the currently selected colour or brush.
  16537. */
  16538. void strokePath (const Path& path,
  16539. const PathStrokeType& strokeType,
  16540. const AffineTransform& transform = AffineTransform::identity) const throw();
  16541. /** Draws a line with an arrowhead.
  16542. @param startX the line's start x co-ordinate
  16543. @param startY the line's start y co-ordinate
  16544. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  16545. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  16546. @param lineThickness the thickness of the line
  16547. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  16548. @param arrowheadLength the length of the arrow head (along the length of the line)
  16549. */
  16550. void drawArrow (const float startX,
  16551. const float startY,
  16552. const float endX,
  16553. const float endY,
  16554. const float lineThickness,
  16555. const float arrowheadWidth,
  16556. const float arrowheadLength) const throw();
  16557. /** Types of rendering quality that can be specified when drawing images.
  16558. @see blendImage, Graphics::setImageResamplingQuality
  16559. */
  16560. enum ResamplingQuality
  16561. {
  16562. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  16563. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  16564. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  16565. };
  16566. /** Changes the quality that will be used when resampling images.
  16567. By default a Graphics object will be set to mediumRenderingQuality.
  16568. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  16569. */
  16570. void setImageResamplingQuality (const ResamplingQuality newQuality) throw();
  16571. /** Draws an image.
  16572. This will draw the whole of an image, positioning its top-left corner at the
  16573. given co-ordinates, and keeping its size the same. This is the simplest image
  16574. drawing method - the others give more control over the scaling and clipping
  16575. of the images.
  16576. Images are composited using the context's current opacity, so if you
  16577. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16578. (or setColour() with an opaque colour) before drawing images.
  16579. */
  16580. void drawImageAt (const Image* const imageToDraw,
  16581. const int topLeftX,
  16582. const int topLeftY,
  16583. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16584. /** Draws part of an image, rescaling it to fit in a given target region.
  16585. The specified area of the source image is rescaled and drawn to fill the
  16586. specifed destination rectangle.
  16587. Images are composited using the context's current opacity, so if you
  16588. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16589. (or setColour() with an opaque colour) before drawing images.
  16590. @param imageToDraw the image to overlay
  16591. @param destX the left of the destination rectangle
  16592. @param destY the top of the destination rectangle
  16593. @param destWidth the width of the destination rectangle
  16594. @param destHeight the height of the destination rectangle
  16595. @param sourceX the left of the rectangle to copy from the source image
  16596. @param sourceY the top of the rectangle to copy from the source image
  16597. @param sourceWidth the width of the rectangle to copy from the source image
  16598. @param sourceHeight the height of the rectangle to copy from the source image
  16599. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  16600. the source image's alpha channel is used as a mask with
  16601. which to fill the destination using the current colour
  16602. or brush. (If the source is has no alpha channel, then
  16603. it will just fill the target with a solid rectangle)
  16604. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  16605. */
  16606. void drawImage (const Image* const imageToDraw,
  16607. int destX,
  16608. int destY,
  16609. int destWidth,
  16610. int destHeight,
  16611. int sourceX,
  16612. int sourceY,
  16613. int sourceWidth,
  16614. int sourceHeight,
  16615. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16616. /** Draws part of an image, having applied an affine transform to it.
  16617. This lets you throw the image around in some wacky ways, rotate it, shear,
  16618. scale it, etc.
  16619. A subregion is specified within the source image, and all transformations
  16620. will be treated as relative to the origin of this sub-region. So, for example if
  16621. your subregion is (50, 50, 100, 100), and your transform is a translation of (20, 20),
  16622. the resulting pixel drawn at (20, 20) in the destination context is from (50, 50) in
  16623. your image. If you want to use the whole image, then Image::getBounds() returns a
  16624. suitable rectangle to use as the imageSubRegion parameter.
  16625. Images are composited using the context's current opacity, so if you
  16626. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  16627. (or setColour() with an opaque colour) before drawing images.
  16628. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  16629. are ignored and it is filled with the current brush, masked by its alpha channel.
  16630. @see setImageResamplingQuality, drawImage
  16631. */
  16632. void drawImageTransformed (const Image* const imageToDraw,
  16633. const Rectangle& imageSubRegion,
  16634. const AffineTransform& transform,
  16635. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16636. /** Draws an image to fit within a designated rectangle.
  16637. If the image is too big or too small for the space, it will be rescaled
  16638. to fit as nicely as it can do without affecting its aspect ratio. It will
  16639. then be placed within the target rectangle according to the justification flags
  16640. specified.
  16641. @param imageToDraw the source image to draw
  16642. @param destX top-left of the target rectangle to fit it into
  16643. @param destY top-left of the target rectangle to fit it into
  16644. @param destWidth size of the target rectangle to fit the image into
  16645. @param destHeight size of the target rectangle to fit the image into
  16646. @param placementWithinTarget this specifies how the image should be positioned
  16647. within the target rectangle - see the RectanglePlacement
  16648. class for more details about this.
  16649. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  16650. alpha channel will be used as a mask with which to
  16651. draw with the current brush or colour. This is
  16652. similar to fillAlphaMap(), and see also drawImage()
  16653. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  16654. */
  16655. void drawImageWithin (const Image* const imageToDraw,
  16656. const int destX,
  16657. const int destY,
  16658. const int destWidth,
  16659. const int destHeight,
  16660. const RectanglePlacement& placementWithinTarget,
  16661. const bool fillAlphaChannelWithCurrentBrush = false) const throw();
  16662. /** Returns the position of the bounding box for the current clipping region.
  16663. @see getClipRegion, clipRegionIntersects
  16664. */
  16665. const Rectangle getClipBounds() const throw();
  16666. /** Checks whether a rectangle overlaps the context's clipping region.
  16667. If this returns false, no part of the given area can be drawn onto, so this
  16668. method can be used to optimise a component's paint() method, by letting it
  16669. avoid drawing complex objects that aren't within the region being repainted.
  16670. */
  16671. bool clipRegionIntersects (const int x, const int y, const int width, const int height) const throw();
  16672. /** Intersects the current clipping region with another region.
  16673. @returns true if the resulting clipping region is non-zero in size
  16674. @see setOrigin, clipRegionIntersects
  16675. */
  16676. bool reduceClipRegion (const int x, const int y,
  16677. const int width, const int height) throw();
  16678. /** Intersects the current clipping region with a rectangle list region.
  16679. @returns true if the resulting clipping region is non-zero in size
  16680. @see setOrigin, clipRegionIntersects
  16681. */
  16682. bool reduceClipRegion (const RectangleList& clipRegion) throw();
  16683. /** Intersects the current clipping region with a path.
  16684. @returns true if the resulting clipping region is non-zero in size
  16685. @see reduceClipRegion
  16686. */
  16687. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity) throw();
  16688. /** Intersects the current clipping region with an image's alpha-channel.
  16689. The current clipping path is intersected with the area covered by this image's
  16690. alpha-channel, after the image has been transformed by the specified matrix.
  16691. @param image the image whose alpha-channel should be used. If the image doesn't
  16692. have an alpha-channel, it is treated as entirely opaque.
  16693. @param sourceClipRegion a subsection of the image that should be used. To use the
  16694. entire image, just pass a rectangle of bounds
  16695. (0, 0, image.getWidth(), image.getHeight()).
  16696. @param transform a matrix to apply to the image
  16697. @returns true if the resulting clipping region is non-zero in size
  16698. @see reduceClipRegion
  16699. */
  16700. bool reduceClipRegion (const Image& image, const Rectangle& sourceClipRegion,
  16701. const AffineTransform& transform) throw();
  16702. /** Excludes a rectangle to stop it being drawn into. */
  16703. void excludeClipRegion (const int x, const int y,
  16704. const int width, const int height) throw();
  16705. /** Returns true if no drawing can be done because the clip region is zero. */
  16706. bool isClipEmpty() const throw();
  16707. /** Saves the current graphics state on an internal stack.
  16708. To restore the state, use restoreState().
  16709. */
  16710. void saveState() throw();
  16711. /** Restores a graphics state that was previously saved with saveState().
  16712. */
  16713. void restoreState() throw();
  16714. /** Moves the position of the context's origin.
  16715. This changes the position that the context considers to be (0, 0) to
  16716. the specified position.
  16717. So if you call setOrigin (100, 100), then the position that was previously
  16718. referred to as (100, 100) will subsequently be considered to be (0, 0).
  16719. @see reduceClipRegion
  16720. */
  16721. void setOrigin (const int newOriginX,
  16722. const int newOriginY) throw();
  16723. /** Resets the current colour, brush, and font to default settings. */
  16724. void resetToDefaultState() throw();
  16725. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  16726. bool isVectorDevice() const throw();
  16727. juce_UseDebuggingNewOperator
  16728. /** Create a graphics that uses a given low-level renderer.
  16729. For internal use only.
  16730. NB. The context will NOT be deleted by this object when it is deleted.
  16731. */
  16732. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  16733. /** @internal */
  16734. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  16735. private:
  16736. LowLevelGraphicsContext* const context;
  16737. const bool ownsContext;
  16738. bool saveStatePending;
  16739. void saveStateIfPending() throw();
  16740. const Graphics& operator= (const Graphics& other);
  16741. Graphics (const Graphics&);
  16742. };
  16743. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  16744. /********* End of inlined file: juce_Graphics.h *********/
  16745. /**
  16746. A graphical effect filter that can be applied to components.
  16747. An ImageEffectFilter can be applied to the image that a component
  16748. paints before it hits the screen.
  16749. This is used for adding effects like shadows, blurs, etc.
  16750. @see Component::setComponentEffect
  16751. */
  16752. class JUCE_API ImageEffectFilter
  16753. {
  16754. public:
  16755. /** Overridden to render the effect.
  16756. The implementation of this method must use the image that is passed in
  16757. as its source, and should render its output to the graphics context passed in.
  16758. @param sourceImage the image that the source component has just rendered with
  16759. its paint() method. The image may or may not have an alpha
  16760. channel, depending on whether the component is opaque.
  16761. @param destContext the graphics context to use to draw the resultant image.
  16762. */
  16763. virtual void applyEffect (Image& sourceImage,
  16764. Graphics& destContext) = 0;
  16765. /** Destructor. */
  16766. virtual ~ImageEffectFilter() {}
  16767. };
  16768. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  16769. /********* End of inlined file: juce_ImageEffectFilter.h *********/
  16770. /********* Start of inlined file: juce_RectangleList.h *********/
  16771. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  16772. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  16773. /**
  16774. Maintains a set of rectangles as a complex region.
  16775. This class allows a set of rectangles to be treated as a solid shape, and can
  16776. add and remove rectangular sections of it, and simplify overlapping or
  16777. adjacent rectangles.
  16778. @see Rectangle
  16779. */
  16780. class JUCE_API RectangleList
  16781. {
  16782. public:
  16783. /** Creates an empty RectangleList */
  16784. RectangleList() throw();
  16785. /** Creates a copy of another list */
  16786. RectangleList (const RectangleList& other) throw();
  16787. /** Creates a list containing just one rectangle. */
  16788. RectangleList (const Rectangle& rect) throw();
  16789. /** Copies this list from another one. */
  16790. const RectangleList& operator= (const RectangleList& other) throw();
  16791. /** Destructor. */
  16792. ~RectangleList() throw();
  16793. /** Returns true if the region is empty. */
  16794. bool isEmpty() const throw();
  16795. /** Returns the number of rectangles in the list. */
  16796. int getNumRectangles() const throw() { return rects.size(); }
  16797. /** Returns one of the rectangles at a particular index.
  16798. @returns the rectangle at the index, or an empty rectangle if the
  16799. index is out-of-range.
  16800. */
  16801. const Rectangle getRectangle (const int index) const throw();
  16802. /** Removes all rectangles to leave an empty region. */
  16803. void clear() throw();
  16804. /** Merges a new rectangle into the list.
  16805. The rectangle being added will first be clipped to remove any parts of it
  16806. that overlap existing rectangles in the list.
  16807. */
  16808. void add (const int x, const int y,
  16809. const int w, const int h) throw();
  16810. /** Merges a new rectangle into the list.
  16811. The rectangle being added will first be clipped to remove any parts of it
  16812. that overlap existing rectangles in the list, and adjacent rectangles will be
  16813. merged into it.
  16814. */
  16815. void add (const Rectangle& rect) throw();
  16816. /** Dumbly adds a rectangle to the list without checking for overlaps.
  16817. This simply adds the rectangle to the end, it doesn't merge it or remove
  16818. any overlapping bits.
  16819. */
  16820. void addWithoutMerging (const Rectangle& rect) throw();
  16821. /** Merges another rectangle list into this one.
  16822. Any overlaps between the two lists will be clipped, so that the result is
  16823. the union of both lists.
  16824. */
  16825. void add (const RectangleList& other) throw();
  16826. /** Removes a rectangular region from the list.
  16827. Any rectangles in the list which overlap this will be clipped and subdivided
  16828. if necessary.
  16829. */
  16830. void subtract (const Rectangle& rect) throw();
  16831. /** Removes all areas in another RectangleList from this one.
  16832. Any rectangles in the list which overlap this will be clipped and subdivided
  16833. if necessary.
  16834. */
  16835. void subtract (const RectangleList& otherList) throw();
  16836. /** Removes any areas of the region that lie outside a given rectangle.
  16837. Any rectangles in the list which overlap this will be clipped and subdivided
  16838. if necessary.
  16839. Returns true if the resulting region is not empty, false if it is empty.
  16840. @see getIntersectionWith
  16841. */
  16842. bool clipTo (const Rectangle& rect) throw();
  16843. /** Removes any areas of the region that lie outside a given rectangle list.
  16844. Any rectangles in this object which overlap the specified list will be clipped
  16845. and subdivided if necessary.
  16846. Returns true if the resulting region is not empty, false if it is empty.
  16847. @see getIntersectionWith
  16848. */
  16849. bool clipTo (const RectangleList& other) throw();
  16850. /** Creates a region which is the result of clipping this one to a given rectangle.
  16851. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  16852. resulting region into the list whose reference is passed-in.
  16853. Returns true if the resulting region is not empty, false if it is empty.
  16854. @see clipTo
  16855. */
  16856. bool getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw();
  16857. /** Swaps the contents of this and another list.
  16858. This swaps their internal pointers, so is hugely faster than using copy-by-value
  16859. to swap them.
  16860. */
  16861. void swapWith (RectangleList& otherList) throw();
  16862. /** Checks whether the region contains a given point.
  16863. @returns true if the point lies within one of the rectangles in the list
  16864. */
  16865. bool containsPoint (const int x, const int y) const throw();
  16866. /** Checks whether the region contains the whole of a given rectangle.
  16867. @returns true all parts of the rectangle passed in lie within the region
  16868. defined by this object
  16869. @see intersectsRectangle, containsPoint
  16870. */
  16871. bool containsRectangle (const Rectangle& rectangleToCheck) const throw();
  16872. /** Checks whether the region contains any part of a given rectangle.
  16873. @returns true if any part of the rectangle passed in lies within the region
  16874. defined by this object
  16875. @see containsRectangle
  16876. */
  16877. bool intersectsRectangle (const Rectangle& rectangleToCheck) const throw();
  16878. /** Checks whether this region intersects any part of another one.
  16879. @see intersectsRectangle
  16880. */
  16881. bool intersects (const RectangleList& other) const throw();
  16882. /** Returns the smallest rectangle that can enclose the whole of this region. */
  16883. const Rectangle getBounds() const throw();
  16884. /** Optimises the list into a minimum number of constituent rectangles.
  16885. This will try to combine any adjacent rectangles into larger ones where
  16886. possible, to simplify lists that might have been fragmented by repeated
  16887. add/subtract calls.
  16888. */
  16889. void consolidate() throw();
  16890. /** Adds an x and y value to all the co-ordinates. */
  16891. void offsetAll (const int dx, const int dy) throw();
  16892. /** Creates a Path object to represent this region. */
  16893. const Path toPath() const throw();
  16894. /** An iterator for accessing all the rectangles in a RectangleList. */
  16895. class Iterator
  16896. {
  16897. public:
  16898. Iterator (const RectangleList& list) throw();
  16899. ~Iterator() throw();
  16900. /** Advances to the next rectangle, and returns true if it's not finished.
  16901. Call this before using getRectangle() to find the rectangle that was returned.
  16902. */
  16903. bool next() throw();
  16904. /** Returns the current rectangle. */
  16905. const Rectangle* getRectangle() const throw() { return current; }
  16906. juce_UseDebuggingNewOperator
  16907. private:
  16908. const Rectangle* current;
  16909. const RectangleList& owner;
  16910. int index;
  16911. Iterator (const Iterator&);
  16912. const Iterator& operator= (const Iterator&);
  16913. };
  16914. juce_UseDebuggingNewOperator
  16915. private:
  16916. friend class Iterator;
  16917. Array <Rectangle> rects;
  16918. };
  16919. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  16920. /********* End of inlined file: juce_RectangleList.h *********/
  16921. /********* Start of inlined file: juce_BorderSize.h *********/
  16922. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  16923. #define __JUCE_BORDERSIZE_JUCEHEADER__
  16924. /**
  16925. Specifies a set of gaps to be left around the sides of a rectangle.
  16926. This is basically the size of the spaces at the top, bottom, left and right of
  16927. a rectangle. It's used by various component classes to specify borders.
  16928. @see Rectangle
  16929. */
  16930. class JUCE_API BorderSize
  16931. {
  16932. public:
  16933. /** Creates a null border.
  16934. All sizes are left as 0.
  16935. */
  16936. BorderSize() throw();
  16937. /** Creates a copy of another border. */
  16938. BorderSize (const BorderSize& other) throw();
  16939. /** Creates a border with the given gaps. */
  16940. BorderSize (const int topGap,
  16941. const int leftGap,
  16942. const int bottomGap,
  16943. const int rightGap) throw();
  16944. /** Creates a border with the given gap on all sides. */
  16945. BorderSize (const int allGaps) throw();
  16946. /** Destructor. */
  16947. ~BorderSize() throw();
  16948. /** Returns the gap that should be left at the top of the region. */
  16949. int getTop() const throw() { return top; }
  16950. /** Returns the gap that should be left at the top of the region. */
  16951. int getLeft() const throw() { return left; }
  16952. /** Returns the gap that should be left at the top of the region. */
  16953. int getBottom() const throw() { return bottom; }
  16954. /** Returns the gap that should be left at the top of the region. */
  16955. int getRight() const throw() { return right; }
  16956. /** Returns the sum of the top and bottom gaps. */
  16957. int getTopAndBottom() const throw() { return top + bottom; }
  16958. /** Returns the sum of the left and right gaps. */
  16959. int getLeftAndRight() const throw() { return left + right; }
  16960. /** Changes the top gap. */
  16961. void setTop (const int newTopGap) throw();
  16962. /** Changes the left gap. */
  16963. void setLeft (const int newLeftGap) throw();
  16964. /** Changes the bottom gap. */
  16965. void setBottom (const int newBottomGap) throw();
  16966. /** Changes the right gap. */
  16967. void setRight (const int newRightGap) throw();
  16968. /** Returns a rectangle with these borders removed from it. */
  16969. const Rectangle subtractedFrom (const Rectangle& original) const throw();
  16970. /** Removes this border from a given rectangle. */
  16971. void subtractFrom (Rectangle& rectangle) const throw();
  16972. /** Returns a rectangle with these borders added around it. */
  16973. const Rectangle addedTo (const Rectangle& original) const throw();
  16974. /** Adds this border around a given rectangle. */
  16975. void addTo (Rectangle& original) const throw();
  16976. bool operator== (const BorderSize& other) const throw();
  16977. bool operator!= (const BorderSize& other) const throw();
  16978. juce_UseDebuggingNewOperator
  16979. private:
  16980. int top, left, bottom, right;
  16981. };
  16982. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  16983. /********* End of inlined file: juce_BorderSize.h *********/
  16984. /********* Start of inlined file: juce_ComponentPeer.h *********/
  16985. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  16986. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  16987. class Component;
  16988. class Graphics;
  16989. class ComponentBoundsConstrainer;
  16990. class ComponentDeletionWatcher;
  16991. /**
  16992. The base class for window objects that wrap a component as a real operating
  16993. system object.
  16994. This is an abstract base class - the platform specific code contains default
  16995. implementations of it that create and manage windows.
  16996. @see Component::createNewPeer
  16997. */
  16998. class JUCE_API ComponentPeer : public MessageListener
  16999. {
  17000. public:
  17001. /** A combination of these flags is passed to the ComponentPeer constructor. */
  17002. enum StyleFlags
  17003. {
  17004. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  17005. entry on the taskbar (ignored on MacOSX) */
  17006. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  17007. tooltip, etc. */
  17008. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  17009. through it (may not be possible on some platforms). */
  17010. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  17011. title bar and frame\. if not specified, the window will be
  17012. borderless. */
  17013. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  17014. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  17015. minimise button on it. */
  17016. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  17017. maximise button on it. */
  17018. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  17019. close button on it. */
  17020. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  17021. not be possible on all platforms). */
  17022. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  17023. do its own repainting, but only to repaint when the
  17024. performAnyPendingRepaintsNow() method is called. */
  17025. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  17026. be used for things like plugin windows, to stop them interfering
  17027. with the host's shortcut keys */
  17028. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  17029. };
  17030. /** Creates a peer.
  17031. The component is the one that we intend to represent, and the style flags are
  17032. a combination of the values in the StyleFlags enum
  17033. */
  17034. ComponentPeer (Component* const component,
  17035. const int styleFlags) throw();
  17036. /** Destructor. */
  17037. virtual ~ComponentPeer();
  17038. /** Returns the component being represented by this peer. */
  17039. Component* getComponent() const throw() { return component; }
  17040. /** Returns the set of style flags that were set when the window was created.
  17041. @see Component::addToDesktop
  17042. */
  17043. int getStyleFlags() const throw() { return styleFlags; }
  17044. /** Returns the raw handle to whatever kind of window is being used.
  17045. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  17046. but rememeber there's no guarantees what you'll get back.
  17047. */
  17048. virtual void* getNativeHandle() const = 0;
  17049. /** Shows or hides the window. */
  17050. virtual void setVisible (bool shouldBeVisible) = 0;
  17051. /** Changes the title of the window. */
  17052. virtual void setTitle (const String& title) = 0;
  17053. /** Moves the window without changing its size.
  17054. If the native window is contained in another window, then the co-ordinates are
  17055. relative to the parent window's origin, not the screen origin.
  17056. This should result in a callback to handleMovedOrResized().
  17057. */
  17058. virtual void setPosition (int x, int y) = 0;
  17059. /** Resizes the window without changing its position.
  17060. This should result in a callback to handleMovedOrResized().
  17061. */
  17062. virtual void setSize (int w, int h) = 0;
  17063. /** Moves and resizes the window.
  17064. If the native window is contained in another window, then the co-ordinates are
  17065. relative to the parent window's origin, not the screen origin.
  17066. This should result in a callback to handleMovedOrResized().
  17067. */
  17068. virtual void setBounds (int x, int y, int w, int h, const bool isNowFullScreen) = 0;
  17069. /** Returns the current position and size of the window.
  17070. If the native window is contained in another window, then the co-ordinates are
  17071. relative to the parent window's origin, not the screen origin.
  17072. */
  17073. virtual void getBounds (int& x, int& y, int& w, int& h) const = 0;
  17074. /** Returns the x-position of this window, relative to the screen's origin. */
  17075. virtual int getScreenX() const = 0;
  17076. /** Returns the y-position of this window, relative to the screen's origin. */
  17077. virtual int getScreenY() const = 0;
  17078. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  17079. virtual void relativePositionToGlobal (int& x, int& y) = 0;
  17080. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  17081. virtual void globalPositionToRelative (int& x, int& y) = 0;
  17082. /** Minimises the window. */
  17083. virtual void setMinimised (bool shouldBeMinimised) = 0;
  17084. /** True if the window is currently minimised. */
  17085. virtual bool isMinimised() const = 0;
  17086. /** Enable/disable fullscreen mode for the window. */
  17087. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  17088. /** True if the window is currently full-screen. */
  17089. virtual bool isFullScreen() const = 0;
  17090. /** Sets the size to restore to if fullscreen mode is turned off. */
  17091. void setNonFullScreenBounds (const Rectangle& newBounds) throw();
  17092. /** Returns the size to restore to if fullscreen mode is turned off. */
  17093. const Rectangle& getNonFullScreenBounds() const throw();
  17094. /** Attempts to change the icon associated with this window.
  17095. */
  17096. virtual void setIcon (const Image& newIcon) = 0;
  17097. /** Sets a constrainer to use if the peer can resize itself.
  17098. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  17099. */
  17100. void setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw();
  17101. /** Returns the current constrainer, if one has been set. */
  17102. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  17103. /** Checks if a point is in the window.
  17104. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  17105. is false, then this returns false if the point is actually inside a child of this
  17106. window.
  17107. */
  17108. virtual bool contains (int x, int y, bool trueIfInAChildWindow) const = 0;
  17109. /** Returns the size of the window frame that's around this window.
  17110. Whether or not the window has a normal window frame depends on the flags
  17111. that were set when the window was created by Component::addToDesktop()
  17112. */
  17113. virtual const BorderSize getFrameSize() const = 0;
  17114. /** This is called when the window's bounds change.
  17115. A peer implementation must call this when the window is moved and resized, so that
  17116. this method can pass the message on to the component.
  17117. */
  17118. void handleMovedOrResized();
  17119. /** This is called if the screen resolution changes.
  17120. A peer implementation must call this if the monitor arrangement changes or the available
  17121. screen size changes.
  17122. */
  17123. void handleScreenSizeChange();
  17124. /** This is called to repaint the component into the given context. */
  17125. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  17126. /** Sets this window to either be always-on-top or normal.
  17127. Some kinds of window might not be able to do this, so should return false.
  17128. */
  17129. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  17130. /** Brings the window to the top, optionally also giving it focus. */
  17131. virtual void toFront (bool makeActive) = 0;
  17132. /** Moves the window to be just behind another one. */
  17133. virtual void toBehind (ComponentPeer* other) = 0;
  17134. /** Called when the window is brought to the front, either by the OS or by a call
  17135. to toFront().
  17136. */
  17137. void handleBroughtToFront();
  17138. /** True if the window has the keyboard focus. */
  17139. virtual bool isFocused() const = 0;
  17140. /** Tries to give the window keyboard focus. */
  17141. virtual void grabFocus() = 0;
  17142. /** Tells the window that text input may be required at the given position.
  17143. This may cause things like a virtual on-screen keyboard to appear, depending
  17144. on the OS.
  17145. */
  17146. virtual void textInputRequired (int x, int y) = 0;
  17147. /** Called when the window gains keyboard focus. */
  17148. void handleFocusGain();
  17149. /** Called when the window loses keyboard focus. */
  17150. void handleFocusLoss();
  17151. Component* getLastFocusedSubcomponent() const throw();
  17152. /** Called when a key is pressed.
  17153. For keycode info, see the KeyPress class.
  17154. Returns true if the keystroke was used.
  17155. */
  17156. bool handleKeyPress (const int keyCode,
  17157. const juce_wchar textCharacter);
  17158. /** Called whenever a key is pressed or released.
  17159. Returns true if the keystroke was used.
  17160. */
  17161. bool handleKeyUpOrDown (const bool isKeyDown);
  17162. /** Called whenever a modifier key is pressed or released. */
  17163. void handleModifierKeysChange();
  17164. /** Invalidates a region of the window to be repainted asynchronously. */
  17165. virtual void repaint (int x, int y, int w, int h) = 0;
  17166. /** This can be called (from the message thread) to cause the immediate redrawing
  17167. of any areas of this window that need repainting.
  17168. You shouldn't ever really need to use this, it's mainly for special purposes
  17169. like supporting audio plugins where the host's event loop is out of our control.
  17170. */
  17171. virtual void performAnyPendingRepaintsNow() = 0;
  17172. void handleMouseEnter (int x, int y, const int64 time);
  17173. void handleMouseMove (int x, int y, const int64 time);
  17174. void handleMouseDown (int x, int y, const int64 time);
  17175. void handleMouseDrag (int x, int y, const int64 time);
  17176. void handleMouseUp (const int oldModifiers, int x, int y, const int64 time);
  17177. void handleMouseExit (int x, int y, const int64 time);
  17178. void handleMouseWheel (const int amountX, const int amountY, const int64 time);
  17179. /** Causes a mouse-move callback to be made asynchronously. */
  17180. void sendFakeMouseMove() throw();
  17181. void handleUserClosingWindow();
  17182. void handleFileDragMove (const StringArray& files, int x, int y);
  17183. void handleFileDragExit (const StringArray& files);
  17184. void handleFileDragDrop (const StringArray& files, int x, int y);
  17185. /** Resets the masking region.
  17186. The subclass should call this every time it's about to call the handlePaint
  17187. method.
  17188. @see addMaskedRegion
  17189. */
  17190. void clearMaskedRegion() throw();
  17191. /** Adds a rectangle to the set of areas not to paint over.
  17192. A component can call this on its peer during its paint() method, to signal
  17193. that the painting code should ignore a given region. The reason
  17194. for this is to stop embedded windows (such as OpenGL) getting painted over.
  17195. The masked region is cleared each time before a paint happens, so a component
  17196. will have to make sure it calls this every time it's painted.
  17197. */
  17198. void addMaskedRegion (int x, int y, int w, int h) throw();
  17199. /** Returns the number of currently-active peers.
  17200. @see getPeer
  17201. */
  17202. static int getNumPeers() throw();
  17203. /** Returns one of the currently-active peers.
  17204. @see getNumPeers
  17205. */
  17206. static ComponentPeer* getPeer (const int index) throw();
  17207. /** Checks if this peer object is valid.
  17208. @see getNumPeers
  17209. */
  17210. static bool isValidPeer (const ComponentPeer* const peer) throw();
  17211. static void bringModalComponentToFront();
  17212. virtual const StringArray getAvailableRenderingEngines() throw();
  17213. virtual int getCurrentRenderingEngine() throw();
  17214. virtual void setCurrentRenderingEngine (int index) throw();
  17215. juce_UseDebuggingNewOperator
  17216. protected:
  17217. Component* const component;
  17218. const int styleFlags;
  17219. RectangleList maskedRegion;
  17220. Rectangle lastNonFullscreenBounds;
  17221. uint32 lastPaintTime;
  17222. ComponentBoundsConstrainer* constrainer;
  17223. static void updateCurrentModifiers() throw();
  17224. /** @internal */
  17225. void handleMessage (const Message& message);
  17226. private:
  17227. Component* lastFocusedComponent;
  17228. ScopedPointer <ComponentDeletionWatcher> dragAndDropTargetComponent;
  17229. Component* lastDragAndDropCompUnderMouse;
  17230. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  17231. friend class Component;
  17232. static ComponentPeer* getPeerFor (const Component* const component) throw();
  17233. void setLastDragDropTarget (Component* comp);
  17234. ComponentPeer (const ComponentPeer&);
  17235. const ComponentPeer& operator= (const ComponentPeer&);
  17236. };
  17237. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  17238. /********* End of inlined file: juce_ComponentPeer.h *********/
  17239. class LookAndFeel;
  17240. /**
  17241. The base class for all JUCE user-interface objects.
  17242. */
  17243. class JUCE_API Component : public MouseListener,
  17244. protected MessageListener
  17245. {
  17246. public:
  17247. /** Creates a component.
  17248. To get it to actually appear, you'll also need to:
  17249. - Either add it to a parent component or use the addToDesktop() method to
  17250. make it a desktop window
  17251. - Set its size and position to something sensible
  17252. - Use setVisible() to make it visible
  17253. And for it to serve any useful purpose, you'll need to write a
  17254. subclass of Component or use one of the other types of component from
  17255. the library.
  17256. */
  17257. Component() throw();
  17258. /** Destructor.
  17259. Note that when a component is deleted, any child components it might
  17260. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  17261. */
  17262. virtual ~Component();
  17263. /** Creates a component, setting its name at the same time.
  17264. @see getName, setName
  17265. */
  17266. Component (const String& componentName) throw();
  17267. /** Returns the name of this component.
  17268. @see setName
  17269. */
  17270. const String& getName() const throw() { return componentName_; }
  17271. /** Sets the name of this component.
  17272. When the name changes, all registered ComponentListeners will receive a
  17273. ComponentListener::componentNameChanged() callback.
  17274. @see getName
  17275. */
  17276. virtual void setName (const String& newName);
  17277. /** Checks whether this Component object has been deleted.
  17278. This will check whether this object is still a valid component, or whether
  17279. it's been deleted.
  17280. It's safe to call this on null or dangling pointers, but note that there is a
  17281. small risk if another new (but different) component has been created at the
  17282. same memory address which this one occupied, this methods can return a
  17283. false positive.
  17284. */
  17285. bool isValidComponent() const throw();
  17286. /** Makes the component visible or invisible.
  17287. This method will show or hide the component.
  17288. Note that components default to being non-visible when first created.
  17289. Also note that visible components won't be seen unless all their parent components
  17290. are also visible.
  17291. This method will call visibilityChanged() and also componentVisibilityChanged()
  17292. for any component listeners that are interested in this component.
  17293. @param shouldBeVisible whether to show or hide the component
  17294. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  17295. */
  17296. virtual void setVisible (bool shouldBeVisible);
  17297. /** Tests whether the component is visible or not.
  17298. this doesn't necessarily tell you whether this comp is actually on the screen
  17299. because this depends on whether all the parent components are also visible - use
  17300. isShowing() to find this out.
  17301. @see isShowing, setVisible
  17302. */
  17303. bool isVisible() const throw() { return flags.visibleFlag; }
  17304. /** Called when this component's visiblility changes.
  17305. @see setVisible, isVisible
  17306. */
  17307. virtual void visibilityChanged();
  17308. /** Tests whether this component and all its parents are visible.
  17309. @returns true only if this component and all its parents are visible.
  17310. @see isVisible
  17311. */
  17312. bool isShowing() const throw();
  17313. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  17314. To do this, this function will cunningly:
  17315. - take a snapshot of the component as it currently looks
  17316. - call setVisible(false) on the component
  17317. - replace it with a special component that will continue drawing the
  17318. snapshot, animating it and gradually making it more transparent
  17319. - when it's gone, the special component will also be deleted
  17320. As soon as this method returns, the component can be safely removed and deleted
  17321. leaving the proxy to do the fade-out, so it's even ok to call this in a
  17322. component's destructor.
  17323. Passing non-zero x and y values will cause the ghostly component image to
  17324. also whizz off by this distance while fading out. If the scale factor is
  17325. not 1.0, it will also zoom from the component's current size to this new size.
  17326. One thing to be careful about is that the parent component must be able to cope
  17327. with this unknown component type being added to it.
  17328. */
  17329. void fadeOutComponent (const int lengthOfFadeOutInMilliseconds,
  17330. const int deltaXToMove = 0,
  17331. const int deltaYToMove = 0,
  17332. const float scaleFactorAtEnd = 1.0f);
  17333. /** Makes this component appear as a window on the desktop.
  17334. Note that before calling this, you should make sure that the component's opacity is
  17335. set correctly using setOpaque(). If the component is non-opaque, the windowing
  17336. system will try to create a special transparent window for it, which will generally take
  17337. a lot more CPU to operate (and might not even be possible on some platforms).
  17338. If the component is inside a parent component at the time this method is called, it
  17339. will be first be removed from that parent. Likewise if a component on the desktop
  17340. is subsequently added to another component, it'll be removed from the desktop.
  17341. @param windowStyleFlags a combination of the flags specified in the
  17342. ComponentPeer::StyleFlags enum, which define the
  17343. window's characteristics.
  17344. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  17345. in which the juce component should place itself. On Windows,
  17346. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  17347. supported on all platforms, and best left as 0 unless you know
  17348. what you're doing
  17349. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  17350. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  17351. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  17352. */
  17353. virtual void addToDesktop (int windowStyleFlags,
  17354. void* nativeWindowToAttachTo = 0);
  17355. /** If the component is currently showing on the desktop, this will hide it.
  17356. You can also use setVisible() to hide a desktop window temporarily, but
  17357. removeFromDesktop() will free any system resources that are being used up.
  17358. @see addToDesktop, isOnDesktop
  17359. */
  17360. void removeFromDesktop();
  17361. /** Returns true if this component is currently showing on the desktop.
  17362. @see addToDesktop, removeFromDesktop
  17363. */
  17364. bool isOnDesktop() const throw();
  17365. /** Returns the heavyweight window that contains this component.
  17366. If this component is itself on the desktop, this will return the window
  17367. object that it is using. Otherwise, it will return the window of
  17368. its top-level parent component.
  17369. This may return 0 if there isn't a desktop component.
  17370. @see addToDesktop, isOnDesktop
  17371. */
  17372. ComponentPeer* getPeer() const throw();
  17373. /** For components on the desktop, this is called if the system wants to close the window.
  17374. This is a signal that either the user or the system wants the window to close. The
  17375. default implementation of this method will trigger an assertion to warn you that your
  17376. component should do something about it, but you can override this to ignore the event
  17377. if you want.
  17378. */
  17379. virtual void userTriedToCloseWindow();
  17380. /** Called for a desktop component which has just been minimised or un-minimised.
  17381. This will only be called for components on the desktop.
  17382. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  17383. */
  17384. virtual void minimisationStateChanged (bool isNowMinimised);
  17385. /** Brings the component to the front of its siblings.
  17386. If some of the component's siblings have had their 'always-on-top' flag set,
  17387. then they will still be kept in front of this one (unless of course this
  17388. one is also 'always-on-top').
  17389. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  17390. to the component (see grabKeyboardFocus() for more details)
  17391. @see toBack, toBehind, setAlwaysOnTop
  17392. */
  17393. void toFront (const bool shouldAlsoGainFocus);
  17394. /** Changes this component's z-order to be at the back of all its siblings.
  17395. If the component is set to be 'always-on-top', it will only be moved to the
  17396. back of the other other 'always-on-top' components.
  17397. @see toFront, toBehind, setAlwaysOnTop
  17398. */
  17399. void toBack();
  17400. /** Changes this component's z-order so that it's just behind another component.
  17401. @see toFront, toBack
  17402. */
  17403. void toBehind (Component* const other);
  17404. /** Sets whether the component should always be kept at the front of its siblings.
  17405. @see isAlwaysOnTop
  17406. */
  17407. void setAlwaysOnTop (const bool shouldStayOnTop);
  17408. /** Returns true if this component is set to always stay in front of its siblings.
  17409. @see setAlwaysOnTop
  17410. */
  17411. bool isAlwaysOnTop() const throw();
  17412. /** Returns the x co-ordinate of the component's left edge.
  17413. This is a distance in pixels from the left edge of the component's parent.
  17414. @see getScreenX
  17415. */
  17416. inline int getX() const throw() { return bounds_.getX(); }
  17417. /** Returns the y co-ordinate of the top of this component.
  17418. This is a distance in pixels from the top edge of the component's parent.
  17419. @see getScreenY
  17420. */
  17421. inline int getY() const throw() { return bounds_.getY(); }
  17422. /** Returns the component's width in pixels. */
  17423. inline int getWidth() const throw() { return bounds_.getWidth(); }
  17424. /** Returns the component's height in pixels. */
  17425. inline int getHeight() const throw() { return bounds_.getHeight(); }
  17426. /** Returns the x co-ordinate of the component's right-hand edge.
  17427. This is a distance in pixels from the left edge of the component's parent.
  17428. */
  17429. int getRight() const throw() { return bounds_.getRight(); }
  17430. /** Returns the y co-ordinate of the bottom edge of this component.
  17431. This is a distance in pixels from the top edge of the component's parent.
  17432. */
  17433. int getBottom() const throw() { return bounds_.getBottom(); }
  17434. /** Returns this component's bounding box.
  17435. The rectangle returned is relative to the top-left of the component's parent.
  17436. */
  17437. const Rectangle& getBounds() const throw() { return bounds_; }
  17438. /** Returns the region of this component that's not obscured by other, opaque components.
  17439. The RectangleList that is returned represents the area of this component
  17440. which isn't covered by opaque child components.
  17441. If includeSiblings is true, it will also take into account any siblings
  17442. that may be overlapping the component.
  17443. */
  17444. void getVisibleArea (RectangleList& result,
  17445. const bool includeSiblings) const;
  17446. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  17447. @see getX, relativePositionToGlobal
  17448. */
  17449. int getScreenX() const throw();
  17450. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  17451. @see getY, relativePositionToGlobal
  17452. */
  17453. int getScreenY() const throw();
  17454. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  17455. @see globalPositionToRelative, relativePositionToOtherComponent
  17456. */
  17457. void relativePositionToGlobal (int& x, int& y) const throw();
  17458. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  17459. @see relativePositionToGlobal, relativePositionToOtherComponent
  17460. */
  17461. void globalPositionToRelative (int& x, int& y) const throw();
  17462. /** Converts a position relative to this component's top-left into a position
  17463. relative to another component's top-left.
  17464. @see relativePositionToGlobal, globalPositionToRelative
  17465. */
  17466. void relativePositionToOtherComponent (const Component* const targetComponent,
  17467. int& x, int& y) const throw();
  17468. /** Moves the component to a new position.
  17469. Changes the component's top-left position (without changing its size).
  17470. The position is relative to the top-left of the component's parent.
  17471. If the component actually moves, this method will make a synchronous call to moved().
  17472. @see setBounds, ComponentListener::componentMovedOrResized
  17473. */
  17474. void setTopLeftPosition (const int x, const int y);
  17475. /** Moves the component to a new position.
  17476. Changes the position of the component's top-right corner (keeping it the same size).
  17477. The position is relative to the top-left of the component's parent.
  17478. If the component actually moves, this method will make a synchronous call to moved().
  17479. */
  17480. void setTopRightPosition (const int x, const int y);
  17481. /** Changes the size of the component.
  17482. A synchronous call to resized() will be occur if the size actually changes.
  17483. */
  17484. void setSize (const int newWidth, const int newHeight);
  17485. /** Changes the component's position and size.
  17486. The co-ordinates are relative to the top-left of the component's parent, or relative
  17487. to the origin of the screen is the component is on the desktop.
  17488. If this method changes the component's top-left position, it will make a synchronous
  17489. call to moved(). If it changes the size, it will also make a call to resized().
  17490. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  17491. */
  17492. void setBounds (int x, int y, int width, int height);
  17493. /** Changes the component's position and size.
  17494. @see setBounds
  17495. */
  17496. void setBounds (const Rectangle& newBounds);
  17497. /** Changes the component's position and size in terms of fractions of its parent's size.
  17498. The values are factors of the parent's size, so for example
  17499. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  17500. width and height of the parent, with its top-left position 20% of
  17501. the way across and down the parent.
  17502. */
  17503. void setBoundsRelative (const float proportionalX, const float proportionalY,
  17504. const float proportionalWidth, const float proportionalHeight);
  17505. /** Changes the component's position and size based on the amount of space to leave around it.
  17506. This will position the component within its parent, leaving the specified number of
  17507. pixels around each edge.
  17508. */
  17509. void setBoundsInset (const BorderSize& borders);
  17510. /** Positions the component within a given rectangle, keeping its proportions
  17511. unchanged.
  17512. If onlyReduceInSize is false, the component will be resized to fill as much of the
  17513. rectangle as possible without changing its aspect ratio (the component's
  17514. current size is used to determine its aspect ratio, so a zero-size component
  17515. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  17516. too big to fit inside the rectangle.
  17517. It will then be positioned within the rectangle according to the justification flags
  17518. specified.
  17519. */
  17520. void setBoundsToFit (int x, int y, int width, int height,
  17521. const Justification& justification,
  17522. const bool onlyReduceInSize);
  17523. /** Changes the position of the component's centre.
  17524. Leaves the component's size unchanged, but sets the position of its centre
  17525. relative to its parent's top-left.
  17526. */
  17527. void setCentrePosition (const int x, const int y);
  17528. /** Changes the position of the component's centre.
  17529. Leaves the position unchanged, but positions its centre relative to its
  17530. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  17531. its parent.
  17532. */
  17533. void setCentreRelative (const float x, const float y);
  17534. /** Changes the component's size and centres it within its parent.
  17535. After changing the size, the component will be moved so that it's
  17536. centred within its parent.
  17537. */
  17538. void centreWithSize (const int width, const int height);
  17539. /** Returns a proportion of the component's width.
  17540. This is a handy equivalent of (getWidth() * proportion).
  17541. */
  17542. int proportionOfWidth (const float proportion) const throw();
  17543. /** Returns a proportion of the component's height.
  17544. This is a handy equivalent of (getHeight() * proportion).
  17545. */
  17546. int proportionOfHeight (const float proportion) const throw();
  17547. /** Returns the width of the component's parent.
  17548. If the component has no parent (i.e. if it's on the desktop), this will return
  17549. the width of the screen.
  17550. */
  17551. int getParentWidth() const throw();
  17552. /** Returns the height of the component's parent.
  17553. If the component has no parent (i.e. if it's on the desktop), this will return
  17554. the height of the screen.
  17555. */
  17556. int getParentHeight() const throw();
  17557. /** Returns the screen co-ordinates of the monitor that contains this component.
  17558. If there's only one monitor, this will return its size - if there are multiple
  17559. monitors, it will return the area of the monitor that contains the component's
  17560. centre.
  17561. */
  17562. const Rectangle getParentMonitorArea() const throw();
  17563. /** Returns the number of child components that this component contains.
  17564. @see getChildComponent, getIndexOfChildComponent
  17565. */
  17566. int getNumChildComponents() const throw();
  17567. /** Returns one of this component's child components, by it index.
  17568. The component with index 0 is at the back of the z-order, the one at the
  17569. front will have index (getNumChildComponents() - 1).
  17570. If the index is out-of-range, this will return a null pointer.
  17571. @see getNumChildComponents, getIndexOfChildComponent
  17572. */
  17573. Component* getChildComponent (const int index) const throw();
  17574. /** Returns the index of this component in the list of child components.
  17575. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  17576. values are further towards the front.
  17577. Returns -1 if the component passed-in is not a child of this component.
  17578. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  17579. */
  17580. int getIndexOfChildComponent (const Component* const child) const throw();
  17581. /** Adds a child component to this one.
  17582. @param child the new component to add. If the component passed-in is already
  17583. the child of another component, it'll first be removed from that.
  17584. @param zOrder The index in the child-list at which this component should be inserted.
  17585. A value of -1 will insert it in front of the others, 0 is the back.
  17586. @see removeChildComponent, addAndMakeVisible, getChild,
  17587. ComponentListener::componentChildrenChanged
  17588. */
  17589. void addChildComponent (Component* const child,
  17590. int zOrder = -1);
  17591. /** Adds a child component to this one, and also makes the child visible if it isn't.
  17592. Quite a useful function, this is just the same as calling addChildComponent()
  17593. followed by setVisible (true) on the child.
  17594. */
  17595. void addAndMakeVisible (Component* const child,
  17596. int zOrder = -1);
  17597. /** Removes one of this component's child-components.
  17598. If the child passed-in isn't actually a child of this component (either because
  17599. it's invalid or is the child of a different parent), then nothing is done.
  17600. Note that removing a child will not delete it!
  17601. @see addChildComponent, ComponentListener::componentChildrenChanged
  17602. */
  17603. void removeChildComponent (Component* const childToRemove);
  17604. /** Removes one of this component's child-components by index.
  17605. This will return a pointer to the component that was removed, or null if
  17606. the index was out-of-range.
  17607. Note that removing a child will not delete it!
  17608. @see addChildComponent, ComponentListener::componentChildrenChanged
  17609. */
  17610. Component* removeChildComponent (const int childIndexToRemove);
  17611. /** Removes all this component's children.
  17612. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  17613. */
  17614. void removeAllChildren();
  17615. /** Removes all this component's children, and deletes them.
  17616. @see removeAllChildren
  17617. */
  17618. void deleteAllChildren();
  17619. /** Returns the component which this component is inside.
  17620. If this is the highest-level component or hasn't yet been added to
  17621. a parent, this will return null.
  17622. */
  17623. Component* getParentComponent() const throw() { return parentComponent_; }
  17624. /** Searches the parent components for a component of a specified class.
  17625. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  17626. component that can be dynamically cast to a MyComp, or will return 0 if none
  17627. of the parents are suitable.
  17628. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  17629. */
  17630. template <class TargetClass>
  17631. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  17632. {
  17633. (void) dummyParameter;
  17634. Component* p = parentComponent_;
  17635. while (p != 0)
  17636. {
  17637. TargetClass* target = dynamic_cast <TargetClass*> (p);
  17638. if (target != 0)
  17639. return target;
  17640. p = p->parentComponent_;
  17641. }
  17642. return 0;
  17643. }
  17644. /** Returns the highest-level component which contains this one or its parents.
  17645. This will search upwards in the parent-hierarchy from this component, until it
  17646. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  17647. not yet added to a parent), and will return that.
  17648. */
  17649. Component* getTopLevelComponent() const throw();
  17650. /** Checks whether a component is anywhere inside this component or its children.
  17651. This will recursively check through this components children to see if the
  17652. given component is anywhere inside.
  17653. */
  17654. bool isParentOf (const Component* possibleChild) const throw();
  17655. /** Called to indicate that the component's parents have changed.
  17656. When a component is added or removed from its parent, this method will
  17657. be called on all of its children (recursively - so all children of its
  17658. children will also be called as well).
  17659. Subclasses can override this if they need to react to this in some way.
  17660. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  17661. */
  17662. virtual void parentHierarchyChanged();
  17663. /** Subclasses can use this callback to be told when children are added or removed.
  17664. @see parentHierarchyChanged
  17665. */
  17666. virtual void childrenChanged();
  17667. /** Tests whether a given point inside the component.
  17668. Overriding this method allows you to create components which only intercept
  17669. mouse-clicks within a user-defined area.
  17670. This is called to find out whether a particular x, y co-ordinate is
  17671. considered to be inside the component or not, and is used by methods such
  17672. as contains() and getComponentAt() to work out which component
  17673. the mouse is clicked on.
  17674. Components with custom shapes will probably want to override it to perform
  17675. some more complex hit-testing.
  17676. The default implementation of this method returns either true or false,
  17677. depending on the value that was set by calling setInterceptsMouseClicks() (true
  17678. is the default return value).
  17679. Note that the hit-test region is not related to the opacity with which
  17680. areas of a component are painted.
  17681. Applications should never call hitTest() directly - instead use the
  17682. contains() method, because this will also test for occlusion by the
  17683. component's parent.
  17684. Note that for components on the desktop, this method will be ignored, because it's
  17685. not always possible to implement this behaviour on all platforms.
  17686. @param x the x co-ordinate to test, relative to the left hand edge of this
  17687. component. This value is guaranteed to be greater than or equal to
  17688. zero, and less than the component's width
  17689. @param y the y co-ordinate to test, relative to the top edge of this
  17690. component. This value is guaranteed to be greater than or equal to
  17691. zero, and less than the component's height
  17692. @returns true if the click is considered to be inside the component
  17693. @see setInterceptsMouseClicks, contains
  17694. */
  17695. virtual bool hitTest (int x, int y);
  17696. /** Changes the default return value for the hitTest() method.
  17697. Setting this to false is an easy way to make a component pass its mouse-clicks
  17698. through to the components behind it.
  17699. When a component is created, the default setting for this is true.
  17700. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  17701. return false (or true for child components if allowClicksOnChildComponents
  17702. is true)
  17703. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  17704. components can be clicked on as normal but clicks on this component pass
  17705. straight through; if this is false and allowClicksOnThisComponent
  17706. is false, then neither this component nor any child components can
  17707. be clicked on
  17708. @see hitTest, getInterceptsMouseClicks
  17709. */
  17710. void setInterceptsMouseClicks (const bool allowClicksOnThisComponent,
  17711. const bool allowClicksOnChildComponents) throw();
  17712. /** Retrieves the current state of the mouse-click interception flags.
  17713. On return, the two parameters are set to the state used in the last call to
  17714. setInterceptsMouseClicks().
  17715. @see setInterceptsMouseClicks
  17716. */
  17717. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  17718. bool& allowsClicksOnChildComponents) const throw();
  17719. /** Returns true if a given point lies within this component or one of its children.
  17720. Never override this method! Use hitTest to create custom hit regions.
  17721. @param x the x co-ordinate to test, relative to this component's left hand edge.
  17722. @param y the y co-ordinate to test, relative to this component's top edge.
  17723. @returns true if the point is within the component's hit-test area, but only if
  17724. that part of the component isn't clipped by its parent component. Note
  17725. that this won't take into account any overlapping sibling components
  17726. which might be in the way - for that, see reallyContains()
  17727. @see hitTest, reallyContains, getComponentAt
  17728. */
  17729. virtual bool contains (int x, int y);
  17730. /** Returns true if a given point lies in this component, taking any overlapping
  17731. siblings into account.
  17732. @param x the x co-ordinate to test, relative to this component's left hand edge.
  17733. @param y the y co-ordinate to test, relative to this component's top edge.
  17734. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  17735. component, this determines the value that will
  17736. be returned.
  17737. @see contains, getComponentAt
  17738. */
  17739. bool reallyContains (int x, int y,
  17740. const bool returnTrueIfWithinAChild);
  17741. /** Returns the component at a certain point within this one.
  17742. @param x the x co-ordinate to test, relative to this component's left hand edge.
  17743. @param y the y co-ordinate to test, relative to this component's top edge.
  17744. @returns the component that is at this position - which may be 0, this component,
  17745. or one of its children. Note that overlapping siblings that might actually
  17746. be in the way are not taken into account by this method - to account for these,
  17747. instead call getComponentAt on the top-level parent of this component.
  17748. @see hitTest, contains, reallyContains
  17749. */
  17750. Component* getComponentAt (const int x, const int y);
  17751. /** Marks the whole component as needing to be redrawn.
  17752. Calling this will not do any repainting immediately, but will mark the component
  17753. as 'dirty'. At some point in the near future the operating system will send a paint
  17754. message, which will redraw all the dirty regions of all components.
  17755. There's no guarantee about how soon after calling repaint() the redraw will actually
  17756. happen, and other queued events may be delivered before a redraw is done.
  17757. If the setBufferedToImage() method has been used to cause this component
  17758. to use a buffer, the repaint() call will invalidate the component's buffer.
  17759. To redraw just a subsection of the component rather than the whole thing,
  17760. use the repaint (int, int, int, int) method.
  17761. @see paint
  17762. */
  17763. void repaint() throw();
  17764. /** Marks a subsection of this component as needing to be redrawn.
  17765. Calling this will not do any repainting immediately, but will mark the given region
  17766. of the component as 'dirty'. At some point in the near future the operating system
  17767. will send a paint message, which will redraw all the dirty regions of all components.
  17768. There's no guarantee about how soon after calling repaint() the redraw will actually
  17769. happen, and other queued events may be delivered before a redraw is done.
  17770. The region that is passed in will be clipped to keep it within the bounds of this
  17771. component.
  17772. @see repaint()
  17773. */
  17774. void repaint (const int x, const int y,
  17775. const int width, const int height) throw();
  17776. /** Makes the component use an internal buffer to optimise its redrawing.
  17777. Setting this flag to true will cause the component to allocate an
  17778. internal buffer into which it paints itself, so that when asked to
  17779. redraw itself, it can use this buffer rather than actually calling the
  17780. paint() method.
  17781. The buffer is kept until the repaint() method is called directly on
  17782. this component (or until it is resized), when the image is invalidated
  17783. and then redrawn the next time the component is painted.
  17784. Note that only the drawing that happens within the component's paint()
  17785. method is drawn into the buffer, it's child components are not buffered, and
  17786. nor is the paintOverChildren() method.
  17787. @see repaint, paint, createComponentSnapshot
  17788. */
  17789. void setBufferedToImage (const bool shouldBeBuffered) throw();
  17790. /** Generates a snapshot of part of this component.
  17791. This will return a new Image, the size of the rectangle specified,
  17792. containing a snapshot of the specified area of the component and all
  17793. its children.
  17794. The image may or may not have an alpha-channel, depending on whether the
  17795. image is opaque or not.
  17796. If the clipImageToComponentBounds parameter is true and the area is greater than
  17797. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  17798. then parts of the component beyond its bounds can be drawn.
  17799. The caller is responsible for deleting the image that is returned.
  17800. @see paintEntireComponent
  17801. */
  17802. Image* createComponentSnapshot (const Rectangle& areaToGrab,
  17803. const bool clipImageToComponentBounds = true);
  17804. /** Draws this component and all its subcomponents onto the specified graphics
  17805. context.
  17806. You should very rarely have to use this method, it's simply there in case you need
  17807. to draw a component with a custom graphics context for some reason, e.g. for
  17808. creating a snapshot of the component.
  17809. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  17810. on its children in order to render the entire tree.
  17811. The graphics context may be left in an undefined state after this method returns,
  17812. so you may need to reset it if you're going to use it again.
  17813. */
  17814. void paintEntireComponent (Graphics& context);
  17815. /** Adds an effect filter to alter the component's appearance.
  17816. When a component has an effect filter set, then this is applied to the
  17817. results of its paint() method. There are a few preset effects, such as
  17818. a drop-shadow or glow, but they can be user-defined as well.
  17819. The effect that is passed in will not be deleted by the component - the
  17820. caller must take care of deleting it.
  17821. To remove an effect from a component, pass a null pointer in as the parameter.
  17822. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  17823. */
  17824. void setComponentEffect (ImageEffectFilter* const newEffect);
  17825. /** Returns the current component effect.
  17826. @see setComponentEffect
  17827. */
  17828. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  17829. /** Finds the appropriate look-and-feel to use for this component.
  17830. If the component hasn't had a look-and-feel explicitly set, this will
  17831. return the parent's look-and-feel, or just the default one if there's no
  17832. parent.
  17833. @see setLookAndFeel, lookAndFeelChanged
  17834. */
  17835. LookAndFeel& getLookAndFeel() const throw();
  17836. /** Sets the look and feel to use for this component.
  17837. This will also change the look and feel for any child components that haven't
  17838. had their look set explicitly.
  17839. The object passed in will not be deleted by the component, so it's the caller's
  17840. responsibility to manage it. It may be used at any time until this component
  17841. has been deleted.
  17842. Calling this method will also invoke the sendLookAndFeelChange() method.
  17843. @see getLookAndFeel, lookAndFeelChanged
  17844. */
  17845. void setLookAndFeel (LookAndFeel* const newLookAndFeel);
  17846. /** Called to let the component react to a change in the look-and-feel setting.
  17847. When the look-and-feel is changed for a component, this will be called in
  17848. all its child components, recursively.
  17849. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  17850. an application uses a LookAndFeel class that might have changed internally.
  17851. @see sendLookAndFeelChange, getLookAndFeel
  17852. */
  17853. virtual void lookAndFeelChanged();
  17854. /** Calls the lookAndFeelChanged() method in this component and all its children.
  17855. This will recurse through the children and their children, calling lookAndFeelChanged()
  17856. on them all.
  17857. @see lookAndFeelChanged
  17858. */
  17859. void sendLookAndFeelChange();
  17860. /** Indicates whether any parts of the component might be transparent.
  17861. Components that always paint all of their contents with solid colour and
  17862. thus completely cover any components behind them should use this method
  17863. to tell the repaint system that they are opaque.
  17864. This information is used to optimise drawing, because it means that
  17865. objects underneath opaque windows don't need to be painted.
  17866. By default, components are considered transparent, unless this is used to
  17867. make it otherwise.
  17868. @see isOpaque, getVisibleArea
  17869. */
  17870. void setOpaque (const bool shouldBeOpaque) throw();
  17871. /** Returns true if no parts of this component are transparent.
  17872. @returns the value that was set by setOpaque, (the default being false)
  17873. @see setOpaque
  17874. */
  17875. bool isOpaque() const throw();
  17876. /** Indicates whether the component should be brought to the front when clicked.
  17877. Setting this flag to true will cause the component to be brought to the front
  17878. when the mouse is clicked somewhere inside it or its child components.
  17879. Note that a top-level desktop window might still be brought to the front by the
  17880. operating system when it's clicked, depending on how the OS works.
  17881. By default this is set to false.
  17882. @see setMouseClickGrabsKeyboardFocus
  17883. */
  17884. void setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw();
  17885. /** Indicates whether the component should be brought to the front when clicked-on.
  17886. @see setBroughtToFrontOnMouseClick
  17887. */
  17888. bool isBroughtToFrontOnMouseClick() const throw();
  17889. // Keyboard focus methods
  17890. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  17891. By default components aren't actually interested in gaining the
  17892. focus, but this method can be used to turn this on.
  17893. See the grabKeyboardFocus() method for details about the way a component
  17894. is chosen to receive the focus.
  17895. @see grabKeyboardFocus, getWantsKeyboardFocus
  17896. */
  17897. void setWantsKeyboardFocus (const bool wantsFocus) throw();
  17898. /** Returns true if the component is interested in getting keyboard focus.
  17899. This returns the flag set by setWantsKeyboardFocus(). The default
  17900. setting is false.
  17901. @see setWantsKeyboardFocus
  17902. */
  17903. bool getWantsKeyboardFocus() const throw();
  17904. /** Chooses whether a click on this component automatically grabs the focus.
  17905. By default this is set to true, but you might want a component which can
  17906. be focused, but where you don't want the user to be able to affect it directly
  17907. by clicking.
  17908. */
  17909. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  17910. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  17911. See setMouseClickGrabsKeyboardFocus() for more info.
  17912. */
  17913. bool getMouseClickGrabsKeyboardFocus() const throw();
  17914. /** Tries to give keyboard focus to this component.
  17915. When the user clicks on a component or its grabKeyboardFocus()
  17916. method is called, the following procedure is used to work out which
  17917. component should get it:
  17918. - if the component that was clicked on actually wants focus (as indicated
  17919. by calling getWantsKeyboardFocus), it gets it.
  17920. - if the component itself doesn't want focus, it will try to pass it
  17921. on to whichever of its children is the default component, as determined by
  17922. KeyboardFocusTraverser::getDefaultComponent()
  17923. - if none of its children want focus at all, it will pass it up to its
  17924. parent instead, unless it's a top-level component without a parent,
  17925. in which case it just takes the focus itself.
  17926. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  17927. getCurrentlyFocusedComponent, focusGained, focusLost,
  17928. keyPressed, keyStateChanged
  17929. */
  17930. void grabKeyboardFocus();
  17931. /** Returns true if this component currently has the keyboard focus.
  17932. @param trueIfChildIsFocused if this is true, then the method returns true if
  17933. either this component or any of its children (recursively)
  17934. have the focus. If false, the method only returns true if
  17935. this component has the focus.
  17936. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  17937. focusGained, focusLost
  17938. */
  17939. bool hasKeyboardFocus (const bool trueIfChildIsFocused) const throw();
  17940. /** Returns the component that currently has the keyboard focus.
  17941. @returns the focused component, or null if nothing is focused.
  17942. */
  17943. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  17944. /** Tries to move the keyboard focus to one of this component's siblings.
  17945. This will try to move focus to either the next or previous component. (This
  17946. is the method that is used when shifting focus by pressing the tab key).
  17947. Components for which getWantsKeyboardFocus() returns false are not looked at.
  17948. @param moveToNext if true, the focus will move forwards; if false, it will
  17949. move backwards
  17950. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  17951. */
  17952. void moveKeyboardFocusToSibling (const bool moveToNext);
  17953. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  17954. which focus should be passed from this component.
  17955. The default implementation of this method will return a default
  17956. KeyboardFocusTraverser if this component is a focus container (as determined
  17957. by the setFocusContainer() method). If the component isn't a focus
  17958. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  17959. If you overrride this to return a custom KeyboardFocusTraverser, then
  17960. this component and all its sub-components will use the new object to
  17961. make their focusing decisions.
  17962. The method should return a new object, which the caller is required to
  17963. delete when no longer needed.
  17964. */
  17965. virtual KeyboardFocusTraverser* createFocusTraverser();
  17966. /** Returns the focus order of this component, if one has been specified.
  17967. By default components don't have a focus order - in that case, this
  17968. will return 0. Lower numbers indicate that the component will be
  17969. earlier in the focus traversal order.
  17970. To change the order, call setExplicitFocusOrder().
  17971. The focus order may be used by the KeyboardFocusTraverser class as part of
  17972. its algorithm for deciding the order in which components should be traversed.
  17973. See the KeyboardFocusTraverser class for more details on this.
  17974. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  17975. */
  17976. int getExplicitFocusOrder() const throw();
  17977. /** Sets the index used in determining the order in which focusable components
  17978. should be traversed.
  17979. A value of 0 or less is taken to mean that no explicit order is wanted, and
  17980. that traversal should use other factors, like the component's position.
  17981. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  17982. */
  17983. void setExplicitFocusOrder (const int newFocusOrderIndex) throw();
  17984. /** Indicates whether this component is a parent for components that can have
  17985. their focus traversed.
  17986. This flag is used by the default implementation of the createFocusTraverser()
  17987. method, which uses the flag to find the first parent component (of the currently
  17988. focused one) which wants to be a focus container.
  17989. So using this method to set the flag to 'true' causes this component to
  17990. act as the top level within which focus is passed around.
  17991. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  17992. */
  17993. void setFocusContainer (const bool shouldBeFocusContainer) throw();
  17994. /** Returns true if this component has been marked as a focus container.
  17995. See setFocusContainer() for more details.
  17996. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  17997. */
  17998. bool isFocusContainer() const throw();
  17999. /** Returns true if the component (and all its parents) are enabled.
  18000. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  18001. what difference this makes to the component depends on the type. E.g. buttons
  18002. and sliders will choose to draw themselves differently, etc.
  18003. Note that if one of this component's parents is disabled, this will always
  18004. return false, even if this component itself is enabled.
  18005. @see setEnabled, enablementChanged
  18006. */
  18007. bool isEnabled() const throw();
  18008. /** Enables or disables this component.
  18009. Disabling a component will also cause all of its child components to become
  18010. disabled.
  18011. Similarly, enabling a component which is inside a disabled parent
  18012. component won't make any difference until the parent is re-enabled.
  18013. @see isEnabled, enablementChanged
  18014. */
  18015. void setEnabled (const bool shouldBeEnabled);
  18016. /** Callback to indicate that this component has been enabled or disabled.
  18017. This can be triggered by one of the component's parent components
  18018. being enabled or disabled, as well as changes to the component itself.
  18019. The default implementation of this method does nothing; your class may
  18020. wish to repaint itself or something when this happens.
  18021. @see setEnabled, isEnabled
  18022. */
  18023. virtual void enablementChanged();
  18024. /** Changes the mouse cursor shape to use when the mouse is over this component.
  18025. Note that the cursor set by this method can be overridden by the getMouseCursor
  18026. method.
  18027. @see MouseCursor
  18028. */
  18029. void setMouseCursor (const MouseCursor& cursorType) throw();
  18030. /** Returns the mouse cursor shape to use when the mouse is over this component.
  18031. The default implementation will return the cursor that was set by setCursor()
  18032. but can be overridden for more specialised purposes, e.g. returning different
  18033. cursors depending on the mouse position.
  18034. @see MouseCursor
  18035. */
  18036. virtual const MouseCursor getMouseCursor();
  18037. /** Forces the current mouse cursor to be updated.
  18038. If you're overriding the getMouseCursor() method to control which cursor is
  18039. displayed, then this will only be checked each time the user moves the mouse. So
  18040. if you want to force the system to check that the cursor being displayed is
  18041. up-to-date (even if the mouse is just sitting there), call this method.
  18042. This isn't needed if you're only using setMouseCursor().
  18043. */
  18044. void updateMouseCursor() const throw();
  18045. /** Components can override this method to draw their content.
  18046. The paint() method gets called when a region of a component needs redrawing,
  18047. either because the component's repaint() method has been called, or because
  18048. something has happened on the screen that means a section of a window needs
  18049. to be redrawn.
  18050. Any child components will draw themselves over whatever this method draws. If
  18051. you need to paint over the top of your child components, you can also implement
  18052. the paintOverChildren() method to do this.
  18053. If you want to cause a component to redraw itself, this is done asynchronously -
  18054. calling the repaint() method marks a region of the component as "dirty", and the
  18055. paint() method will automatically be called sometime later, by the message thread,
  18056. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  18057. you never redraw something synchronously.
  18058. You should never need to call this method directly - to take a snapshot of the
  18059. component you could use createComponentSnapshot() or paintEntireComponent().
  18060. @param g the graphics context that must be used to do the drawing operations.
  18061. @see repaint, paintOverChildren, Graphics
  18062. */
  18063. virtual void paint (Graphics& g);
  18064. /** Components can override this method to draw over the top of their children.
  18065. For most drawing operations, it's better to use the normal paint() method,
  18066. but if you need to overlay something on top of the children, this can be
  18067. used.
  18068. @see paint, Graphics
  18069. */
  18070. virtual void paintOverChildren (Graphics& g);
  18071. /** Called when the mouse moves inside this component.
  18072. If the mouse button isn't pressed and the mouse moves over a component,
  18073. this will be called to let the component react to this.
  18074. A component will always get a mouseEnter callback before a mouseMove.
  18075. @param e details about the position and status of the mouse event
  18076. @see mouseEnter, mouseExit, mouseDrag, contains
  18077. */
  18078. virtual void mouseMove (const MouseEvent& e);
  18079. /** Called when the mouse first enters this component.
  18080. If the mouse button isn't pressed and the mouse moves into a component,
  18081. this will be called to let the component react to this.
  18082. When the mouse button is pressed and held down while being moved in
  18083. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  18084. mouseDrag messages are sent to the component that the mouse was originally
  18085. clicked on, until the button is released.
  18086. If you're writing a component that needs to repaint itself when the mouse
  18087. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  18088. method.
  18089. @param e details about the position and status of the mouse event
  18090. @see mouseExit, mouseDrag, mouseMove, contains
  18091. */
  18092. virtual void mouseEnter (const MouseEvent& e);
  18093. /** Called when the mouse moves out of this component.
  18094. This will be called when the mouse moves off the edge of this
  18095. component.
  18096. If the mouse button was pressed, and it was then dragged off the
  18097. edge of the component and released, then this callback will happen
  18098. when the button is released, after the mouseUp callback.
  18099. If you're writing a component that needs to repaint itself when the mouse
  18100. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  18101. method.
  18102. @param e details about the position and status of the mouse event
  18103. @see mouseEnter, mouseDrag, mouseMove, contains
  18104. */
  18105. virtual void mouseExit (const MouseEvent& e);
  18106. /** Called when a mouse button is pressed while it's over this component.
  18107. The MouseEvent object passed in contains lots of methods for finding out
  18108. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18109. were held down at the time.
  18110. Once a button is held down, the mouseDrag method will be called when the
  18111. mouse moves, until the button is released.
  18112. @param e details about the position and status of the mouse event
  18113. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  18114. */
  18115. virtual void mouseDown (const MouseEvent& e);
  18116. /** Called when the mouse is moved while a button is held down.
  18117. When a mouse button is pressed inside a component, that component
  18118. receives mouseDrag callbacks each time the mouse moves, even if the
  18119. mouse strays outside the component's bounds.
  18120. If you want to be able to drag things off the edge of a component
  18121. and have the component scroll when you get to the edges, the
  18122. beginDragAutoRepeat() method might be useful.
  18123. @param e details about the position and status of the mouse event
  18124. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  18125. */
  18126. virtual void mouseDrag (const MouseEvent& e);
  18127. /** Called when a mouse button is released.
  18128. A mouseUp callback is sent to the component in which a button was pressed
  18129. even if the mouse is actually over a different component when the
  18130. button is released.
  18131. The MouseEvent object passed in contains lots of methods for finding out
  18132. which buttons were down just before they were released.
  18133. @param e details about the position and status of the mouse event
  18134. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  18135. */
  18136. virtual void mouseUp (const MouseEvent& e);
  18137. /** Called when a mouse button has been double-clicked in this component.
  18138. The MouseEvent object passed in contains lots of methods for finding out
  18139. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  18140. were held down at the time.
  18141. For altering the time limit used to detect double-clicks,
  18142. see MouseEvent::setDoubleClickTimeout.
  18143. @param e details about the position and status of the mouse event
  18144. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  18145. MouseEvent::getDoubleClickTimeout
  18146. */
  18147. virtual void mouseDoubleClick (const MouseEvent& e);
  18148. /** Called when the mouse-wheel is moved.
  18149. This callback is sent to the component that the mouse is over when the
  18150. wheel is moved.
  18151. If not overridden, the component will forward this message to its parent, so
  18152. that parent components can collect mouse-wheel messages that happen to
  18153. child components which aren't interested in them.
  18154. @param e details about the position and status of the mouse event
  18155. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  18156. value means the wheel has been pushed to the right, negative means it
  18157. was pushed to the left
  18158. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  18159. value means the wheel has been pushed upwards, negative means it
  18160. was pushed downwards
  18161. */
  18162. virtual void mouseWheelMove (const MouseEvent& e,
  18163. float wheelIncrementX,
  18164. float wheelIncrementY);
  18165. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  18166. next mouse-drag operation.
  18167. This allows you to make sure that mouseDrag() events sent continuously, even
  18168. when the mouse isn't moving. This can be useful for things like auto-scrolling
  18169. components when the mouse is near an edge.
  18170. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  18171. minimum interval between consecutive mouse drag callbacks. The callbacks
  18172. will continue until the mouse is released, and then the interval will be reset,
  18173. so you need to make sure it's called every time you begin a drag event. If it
  18174. is called when the mouse isn't actually being pressed, it will apply to the next
  18175. mouse-drag operation that happens.
  18176. Passing an interval of 0 or less will cancel the auto-repeat.
  18177. @see mouseDrag
  18178. */
  18179. static void beginDragAutoRepeat (const int millisecondIntervalBetweenCallbacks);
  18180. /** Causes automatic repaints when the mouse enters or exits this component.
  18181. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  18182. on the component, it will trigger a repaint.
  18183. This is handy for things like buttons that need to draw themselves differently when
  18184. the mouse moves over them, and it avoids having to override all the different mouse
  18185. callbacks and call repaint().
  18186. @see mouseEnter, mouseExit, mouseDown, mouseUp
  18187. */
  18188. void setRepaintsOnMouseActivity (const bool shouldRepaint) throw();
  18189. /** Registers a listener to be told when mouse events occur in this component.
  18190. If you need to get informed about mouse events in a component but can't or
  18191. don't want to override its methods, you can attach any number of listeners
  18192. to the component, and these will get told about the events in addition to
  18193. the component's own callbacks being called.
  18194. Note that a MouseListener can also be attached to more than one component.
  18195. @param newListener the listener to register
  18196. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  18197. for events that happen to any child component
  18198. within this component, including deeply-nested
  18199. child components. If false, it will only be
  18200. told about events that this component handles.
  18201. @see MouseListener, removeMouseListener
  18202. */
  18203. void addMouseListener (MouseListener* const newListener,
  18204. const bool wantsEventsForAllNestedChildComponents) throw();
  18205. /** Deregisters a mouse listener.
  18206. @see addMouseListener, MouseListener
  18207. */
  18208. void removeMouseListener (MouseListener* const listenerToRemove) throw();
  18209. /** Adds a listener that wants to hear about keypresses that this component receives.
  18210. The listeners that are registered with a component are called by its keyPressed() or
  18211. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  18212. If you add an object as a key listener, be careful to remove it when the object
  18213. is deleted, or the component will be left with a dangling pointer.
  18214. @see keyPressed, keyStateChanged, removeKeyListener
  18215. */
  18216. void addKeyListener (KeyListener* const newListener) throw();
  18217. /** Removes a previously-registered key listener.
  18218. @see addKeyListener
  18219. */
  18220. void removeKeyListener (KeyListener* const listenerToRemove) throw();
  18221. /** Called when a key is pressed.
  18222. When a key is pressed, the component that has the keyboard focus will have this
  18223. method called. Remember that a component will only be given the focus if its
  18224. setWantsKeyboardFocus() method has been used to enable this.
  18225. If your implementation returns true, the event will be consumed and not passed
  18226. on to any other listeners. If it returns false, the key will be passed to any
  18227. KeyListeners that have been registered with this component. As soon as one of these
  18228. returns true, the process will stop, but if they all return false, the event will
  18229. be passed upwards to this component's parent, and so on.
  18230. The default implementation of this method does nothing and returns false.
  18231. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  18232. */
  18233. virtual bool keyPressed (const KeyPress& key);
  18234. /** Called when a key is pressed or released.
  18235. Whenever a key on the keyboard is pressed or released (including modifier keys
  18236. like shift and ctrl), this method will be called on the component that currently
  18237. has the keyboard focus. Remember that a component will only be given the focus if
  18238. its setWantsKeyboardFocus() method has been used to enable this.
  18239. If your implementation returns true, the event will be consumed and not passed
  18240. on to any other listeners. If it returns false, then any KeyListeners that have
  18241. been registered with this component will have their keyStateChanged methods called.
  18242. As soon as one of these returns true, the process will stop, but if they all return
  18243. false, the event will be passed upwards to this component's parent, and so on.
  18244. The default implementation of this method does nothing and returns false.
  18245. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  18246. method.
  18247. @param isKeyDown true if a key has been pressed; false if it has been released
  18248. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  18249. */
  18250. virtual bool keyStateChanged (const bool isKeyDown);
  18251. /** Called when a modifier key is pressed or released.
  18252. Whenever the shift, control, alt or command keys are pressed or released,
  18253. this method will be called on the component that currently has the keyboard focus.
  18254. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  18255. method has been used to enable this.
  18256. The default implementation of this method actually calls its parent's modifierKeysChanged
  18257. method, so that focused components which aren't interested in this will give their
  18258. parents a chance to act on the event instead.
  18259. @see keyStateChanged, ModifierKeys
  18260. */
  18261. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  18262. /** Enumeration used by the focusChanged() and focusLost() methods. */
  18263. enum FocusChangeType
  18264. {
  18265. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  18266. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  18267. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  18268. };
  18269. /** Called to indicate that this component has just acquired the keyboard focus.
  18270. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  18271. */
  18272. virtual void focusGained (FocusChangeType cause);
  18273. /** Called to indicate that this component has just lost the keyboard focus.
  18274. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  18275. */
  18276. virtual void focusLost (FocusChangeType cause);
  18277. /** Called to indicate that one of this component's children has been focused or unfocused.
  18278. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  18279. changed. It happens when focus moves from one of this component's children (at any depth)
  18280. to a component that isn't contained in this one, (or vice-versa).
  18281. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  18282. */
  18283. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  18284. /** Returns true if the mouse is currently over this component.
  18285. If the mouse isn't over the component, this will return false, even if the
  18286. mouse is currently being dragged - so you can use this in your mouseDrag
  18287. method to find out whether it's really over the component or not.
  18288. Note that when the mouse button is being held down, then the only component
  18289. for which this method will return true is the one that was originally
  18290. clicked on.
  18291. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  18292. */
  18293. bool isMouseOver() const throw();
  18294. /** Returns true if the mouse button is currently held down in this component.
  18295. Note that this is a test to see whether the mouse is being pressed in this
  18296. component, so it'll return false if called on component A when the mouse
  18297. is actually being dragged in component B.
  18298. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  18299. */
  18300. bool isMouseButtonDown() const throw();
  18301. /** True if the mouse is over this component, or if it's being dragged in this component.
  18302. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  18303. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  18304. */
  18305. bool isMouseOverOrDragging() const throw();
  18306. /** Returns true if a mouse button is currently down.
  18307. Unlike isMouseButtonDown, this will test the current state of the
  18308. buttons without regard to which component (if any) it has been
  18309. pressed in.
  18310. @see isMouseButtonDown, ModifierKeys
  18311. */
  18312. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  18313. /** Returns the mouse's current position, relative to this component.
  18314. The co-ordinates are relative to the component's top-left corner.
  18315. */
  18316. void getMouseXYRelative (int& x, int& y) const throw();
  18317. /** Returns the component that's currently underneath the mouse.
  18318. @returns the component or 0 if there isn't one.
  18319. @see contains, getComponentAt
  18320. */
  18321. static Component* JUCE_CALLTYPE getComponentUnderMouse() throw();
  18322. /** Allows the mouse to move beyond the edges of the screen.
  18323. Calling this method when the mouse button is currently pressed inside this component
  18324. will remove the cursor from the screen and allow the mouse to (seem to) move beyond
  18325. the edges of the screen.
  18326. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  18327. can be used for things like custom slider controls or dragging objects around, where
  18328. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  18329. The unbounded mode is automatically turned off when the mouse button is released, or
  18330. it can be turned off explicitly by calling this method again.
  18331. @param shouldUnboundedMovementBeEnabled whether to turn this mode on or off
  18332. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  18333. hidden; if true, it will only be hidden when it
  18334. is moved beyond the edge of the screen
  18335. */
  18336. void enableUnboundedMouseMovement (bool shouldUnboundedMovementBeEnabled,
  18337. bool keepCursorVisibleUntilOffscreen = false) throw();
  18338. /** Called when this component's size has been changed.
  18339. A component can implement this method to do things such as laying out its
  18340. child components when its width or height changes.
  18341. The method is called synchronously as a result of the setBounds or setSize
  18342. methods, so repeatedly changing a components size will repeatedly call its
  18343. resized method (unlike things like repainting, where multiple calls to repaint
  18344. are coalesced together).
  18345. If the component is a top-level window on the desktop, its size could also
  18346. be changed by operating-system factors beyond the application's control.
  18347. @see moved, setSize
  18348. */
  18349. virtual void resized();
  18350. /** Called when this component's position has been changed.
  18351. This is called when the position relative to its parent changes, not when
  18352. its absolute position on the screen changes (so it won't be called for
  18353. all child components when a parent component is moved).
  18354. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  18355. or any of the other repositioning methods, and like resized(), it will be
  18356. called each time those methods are called.
  18357. If the component is a top-level window on the desktop, its position could also
  18358. be changed by operating-system factors beyond the application's control.
  18359. @see resized, setBounds
  18360. */
  18361. virtual void moved();
  18362. /** Called when one of this component's children is moved or resized.
  18363. If the parent wants to know about changes to its immediate children (not
  18364. to children of its children), this is the method to override.
  18365. @see moved, resized, parentSizeChanged
  18366. */
  18367. virtual void childBoundsChanged (Component* child);
  18368. /** Called when this component's immediate parent has been resized.
  18369. If the component is a top-level window, this indicates that the screen size
  18370. has changed.
  18371. @see childBoundsChanged, moved, resized
  18372. */
  18373. virtual void parentSizeChanged();
  18374. /** Called when this component has been moved to the front of its siblings.
  18375. The component may have been brought to the front by the toFront() method, or
  18376. by the operating system if it's a top-level window.
  18377. @see toFront
  18378. */
  18379. virtual void broughtToFront();
  18380. /** Adds a listener to be told about changes to the component hierarchy or position.
  18381. Component listeners get called when this component's size, position or children
  18382. change - see the ComponentListener class for more details.
  18383. @param newListener the listener to register - if this is already registered, it
  18384. will be ignored.
  18385. @see ComponentListener, removeComponentListener
  18386. */
  18387. void addComponentListener (ComponentListener* const newListener) throw();
  18388. /** Removes a component listener.
  18389. @see addComponentListener
  18390. */
  18391. void removeComponentListener (ComponentListener* const listenerToRemove) throw();
  18392. /** Dispatches a numbered message to this component.
  18393. This is a quick and cheap way of allowing simple asynchronous messages to
  18394. be sent to components. It's also safe, because if the component that you
  18395. send the message to is a null or dangling pointer, this won't cause an error.
  18396. The command ID is later delivered to the component's handleCommandMessage() method by
  18397. the application's message queue.
  18398. @see handleCommandMessage
  18399. */
  18400. void postCommandMessage (const int commandId) throw();
  18401. /** Called to handle a command that was sent by postCommandMessage().
  18402. This is called by the message thread when a command message arrives, and
  18403. the component can override this method to process it in any way it needs to.
  18404. @see postCommandMessage
  18405. */
  18406. virtual void handleCommandMessage (int commandId);
  18407. /** Runs a component modally, waiting until the loop terminates.
  18408. This method first makes the component visible, brings it to the front and
  18409. gives it the keyboard focus.
  18410. It then runs a loop, dispatching messages from the system message queue, but
  18411. blocking all mouse or keyboard messages from reaching any components other
  18412. than this one and its children.
  18413. This loop continues until the component's exitModalState() method is called (or
  18414. the component is deleted), and then this method returns, returning the value
  18415. passed into exitModalState().
  18416. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  18417. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  18418. */
  18419. int runModalLoop();
  18420. /** Puts the component into a modal state.
  18421. This makes the component modal, so that messages are blocked from reaching
  18422. any components other than this one and its children, but unlike runModalLoop(),
  18423. this method returns immediately.
  18424. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  18425. get the focus, which is usually what you'll want it to do. If not, it will leave
  18426. the focus unchanged.
  18427. @see exitModalState, runModalLoop
  18428. */
  18429. void enterModalState (const bool takeKeyboardFocus = true);
  18430. /** Ends a component's modal state.
  18431. If this component is currently modal, this will turn of its modalness, and return
  18432. a value to the runModalLoop() method that might have be running its modal loop.
  18433. @see runModalLoop, enterModalState, isCurrentlyModal
  18434. */
  18435. void exitModalState (const int returnValue);
  18436. /** Returns true if this component is the modal one.
  18437. It's possible to have nested modal components, e.g. a pop-up dialog box
  18438. that launches another pop-up, but this will only return true for
  18439. the one at the top of the stack.
  18440. @see getCurrentlyModalComponent
  18441. */
  18442. bool isCurrentlyModal() const throw();
  18443. /** Returns the number of components that are currently in a modal state.
  18444. @see getCurrentlyModalComponent
  18445. */
  18446. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  18447. /** Returns one of the components that are currently modal.
  18448. The index specifies which of the possible modal components to return. The order
  18449. of the components in this list is the reverse of the order in which they became
  18450. modal - so the component at index 0 is always the active component, and the others
  18451. are progressively earlier ones that are themselves now blocked by later ones.
  18452. @returns the modal component, or null if no components are modal (or if the
  18453. index is out of range)
  18454. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  18455. */
  18456. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  18457. /** Checks whether there's a modal component somewhere that's stopping this one
  18458. from receiving messages.
  18459. If there is a modal component, its canModalEventBeSentToComponent() method
  18460. will be called to see if it will still allow this component to receive events.
  18461. @see runModalLoop, getCurrentlyModalComponent
  18462. */
  18463. bool isCurrentlyBlockedByAnotherModalComponent() const throw();
  18464. /** When a component is modal, this callback allows it to choose which other
  18465. components can still receive events.
  18466. When a modal component is active and the user clicks on a non-modal component,
  18467. this method is called on the modal component, and if it returns true, the
  18468. event is allowed to reach its target. If it returns false, the event is blocked
  18469. and the inputAttemptWhenModal() callback is made.
  18470. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  18471. implementation just returns false in all cases.
  18472. */
  18473. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  18474. /** Called when the user tries to click on a component that is blocked by another
  18475. modal component.
  18476. When a component is modal and the user clicks on one of the other components,
  18477. the modal component will receive this callback.
  18478. The default implementation of this method will play a beep, and bring the currently
  18479. modal component to the front, but it can be overridden to do other tasks.
  18480. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  18481. */
  18482. virtual void inputAttemptWhenModal();
  18483. /** Returns one of the component's properties as a string.
  18484. @param keyName the name of the property to retrieve
  18485. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18486. properties, then it will check whether the parent component has
  18487. the key.
  18488. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18489. */
  18490. const String getComponentProperty (const String& keyName,
  18491. const bool useParentComponentIfNotFound,
  18492. const String& defaultReturnValue = String::empty) const throw();
  18493. /** Returns one of the properties as an integer.
  18494. @param keyName the name of the property to retrieve
  18495. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18496. properties, then it will check whether the parent component has
  18497. the key.
  18498. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18499. */
  18500. int getComponentPropertyInt (const String& keyName,
  18501. const bool useParentComponentIfNotFound,
  18502. const int defaultReturnValue = 0) const throw();
  18503. /** Returns one of the properties as an double.
  18504. @param keyName the name of the property to retrieve
  18505. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18506. properties, then it will check whether the parent component has
  18507. the key.
  18508. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18509. */
  18510. double getComponentPropertyDouble (const String& keyName,
  18511. const bool useParentComponentIfNotFound,
  18512. const double defaultReturnValue = 0.0) const throw();
  18513. /** Returns one of the properties as an boolean.
  18514. The result will be true if the string found for this key name can be parsed as a non-zero
  18515. integer.
  18516. @param keyName the name of the property to retrieve
  18517. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18518. properties, then it will check whether the parent component has
  18519. the key.
  18520. @param defaultReturnValue a value to return if the named property doesn't actually exist
  18521. */
  18522. bool getComponentPropertyBool (const String& keyName,
  18523. const bool useParentComponentIfNotFound,
  18524. const bool defaultReturnValue = false) const throw();
  18525. /** Returns one of the properties as an colour.
  18526. @param keyName the name of the property to retrieve
  18527. @param useParentComponentIfNotFound if this is true and the key isn't present in this component's
  18528. properties, then it will check whether the parent component has
  18529. the key.
  18530. @param defaultReturnValue a colour to return if the named property doesn't actually exist
  18531. */
  18532. const Colour getComponentPropertyColour (const String& keyName,
  18533. const bool useParentComponentIfNotFound,
  18534. const Colour& defaultReturnValue = Colours::black) const throw();
  18535. /** Sets a named property as a string.
  18536. @param keyName the name of the property to set. (This mustn't be an empty string)
  18537. @param value the new value to set it to
  18538. @see removeComponentProperty
  18539. */
  18540. void setComponentProperty (const String& keyName, const String& value) throw();
  18541. /** Sets a named property to an integer.
  18542. @param keyName the name of the property to set. (This mustn't be an empty string)
  18543. @param value the new value to set it to
  18544. @see removeComponentProperty
  18545. */
  18546. void setComponentProperty (const String& keyName, const int value) throw();
  18547. /** Sets a named property to a double.
  18548. @param keyName the name of the property to set. (This mustn't be an empty string)
  18549. @param value the new value to set it to
  18550. @see removeComponentProperty
  18551. */
  18552. void setComponentProperty (const String& keyName, const double value) throw();
  18553. /** Sets a named property to a boolean.
  18554. @param keyName the name of the property to set. (This mustn't be an empty string)
  18555. @param value the new value to set it to
  18556. @see removeComponentProperty
  18557. */
  18558. void setComponentProperty (const String& keyName, const bool value) throw();
  18559. /** Sets a named property to a colour.
  18560. @param keyName the name of the property to set. (This mustn't be an empty string)
  18561. @param newColour the new colour to set it to
  18562. @see removeComponentProperty
  18563. */
  18564. void setComponentProperty (const String& keyName, const Colour& newColour) throw();
  18565. /** Deletes a named component property.
  18566. @param keyName the name of the property to delete. (This mustn't be an empty string)
  18567. @see setComponentProperty, getComponentProperty
  18568. */
  18569. void removeComponentProperty (const String& keyName) throw();
  18570. /** Returns the complete set of properties that have been set for this component.
  18571. If no properties have been set, this will return a null pointer.
  18572. @see getComponentProperty, setComponentProperty
  18573. */
  18574. PropertySet* getComponentProperties() const throw() { return propertySet_; }
  18575. /** Looks for a colour that has been registered with the given colour ID number.
  18576. If a colour has been set for this ID number using setColour(), then it is
  18577. returned. If none has been set, the method will try calling the component's
  18578. LookAndFeel class's findColour() method. If none has been registered with the
  18579. look-and-feel either, it will just return black.
  18580. The colour IDs for various purposes are stored as enums in the components that
  18581. they are relevent to - for an example, see Slider::ColourIds,
  18582. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  18583. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  18584. */
  18585. const Colour findColour (const int colourId, const bool inheritFromParent = false) const throw();
  18586. /** Registers a colour to be used for a particular purpose.
  18587. Changing a colour will cause a synchronous callback to the colourChanged()
  18588. method, which your component can override if it needs to do something when
  18589. colours are altered.
  18590. For more details about colour IDs, see the comments for findColour().
  18591. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  18592. */
  18593. void setColour (const int colourId, const Colour& colour);
  18594. /** If a colour has been set with setColour(), this will remove it.
  18595. This allows you to make a colour revert to its default state.
  18596. */
  18597. void removeColour (const int colourId);
  18598. /** Returns true if the specified colour ID has been explicitly set for this
  18599. component using the setColour() method.
  18600. */
  18601. bool isColourSpecified (const int colourId) const throw();
  18602. /** This looks for any colours that have been specified for this component,
  18603. and copies them to the specified target component.
  18604. */
  18605. void copyAllExplicitColoursTo (Component& target) const throw();
  18606. /** This method is called when a colour is changed by the setColour() method.
  18607. @see setColour, findColour
  18608. */
  18609. virtual void colourChanged();
  18610. /** Returns the underlying native window handle for this component.
  18611. This is platform-dependent and strictly for power-users only!
  18612. */
  18613. void* getWindowHandle() const throw();
  18614. /** When created, each component is given a number to uniquely identify it.
  18615. The number is incremented each time a new component is created, so it's a more
  18616. unique way of identifying a component than using its memory location (which
  18617. may be reused after the component is deleted, of course).
  18618. */
  18619. uint32 getComponentUID() const throw() { return componentUID; }
  18620. juce_UseDebuggingNewOperator
  18621. private:
  18622. friend class ComponentPeer;
  18623. friend class InternalDragRepeater;
  18624. static Component* currentlyFocusedComponent;
  18625. static Component* componentUnderMouse;
  18626. String componentName_;
  18627. Component* parentComponent_;
  18628. uint32 componentUID;
  18629. Rectangle bounds_;
  18630. unsigned short numDeepMouseListeners;
  18631. Array <Component*> childComponentList_;
  18632. LookAndFeel* lookAndFeel_;
  18633. MouseCursor cursor_;
  18634. ImageEffectFilter* effect_;
  18635. Image* bufferedImage_;
  18636. VoidArray* mouseListeners_;
  18637. VoidArray* keyListeners_;
  18638. VoidArray* componentListeners_;
  18639. PropertySet* propertySet_;
  18640. struct ComponentFlags
  18641. {
  18642. bool hasHeavyweightPeerFlag : 1;
  18643. bool visibleFlag : 1;
  18644. bool opaqueFlag : 1;
  18645. bool ignoresMouseClicksFlag : 1;
  18646. bool allowChildMouseClicksFlag : 1;
  18647. bool wantsFocusFlag : 1;
  18648. bool isFocusContainerFlag : 1;
  18649. bool dontFocusOnMouseClickFlag : 1;
  18650. bool alwaysOnTopFlag : 1;
  18651. bool bufferToImageFlag : 1;
  18652. bool bringToFrontOnClickFlag : 1;
  18653. bool repaintOnMouseActivityFlag : 1;
  18654. bool draggingFlag : 1;
  18655. bool mouseOverFlag : 1;
  18656. bool mouseInsideFlag : 1;
  18657. bool currentlyModalFlag : 1;
  18658. bool isDisabledFlag : 1;
  18659. bool childCompFocusedFlag : 1;
  18660. #ifdef JUCE_DEBUG
  18661. bool isInsidePaintCall : 1;
  18662. #endif
  18663. };
  18664. union
  18665. {
  18666. uint32 componentFlags_;
  18667. ComponentFlags flags;
  18668. };
  18669. void internalMouseEnter (int x, int y, const int64 time);
  18670. void internalMouseExit (int x, int y, const int64 time);
  18671. void internalMouseDown (int x, int y);
  18672. void internalMouseUp (const int oldModifiers, int x, int y, const int64 time);
  18673. void internalMouseDrag (int x, int y, const int64 time);
  18674. void internalMouseMove (int x, int y, const int64 time);
  18675. void internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time);
  18676. void internalBroughtToFront();
  18677. void internalFocusGain (const FocusChangeType cause);
  18678. void internalFocusLoss (const FocusChangeType cause);
  18679. void internalChildFocusChange (FocusChangeType cause);
  18680. void internalModalInputAttempt();
  18681. void internalModifierKeysChanged();
  18682. void internalChildrenChanged();
  18683. void internalHierarchyChanged();
  18684. void internalUpdateMouseCursor (const bool forcedUpdate) throw();
  18685. void sendMovedResizedMessages (const bool wasMoved, const bool wasResized);
  18686. void repaintParent() throw();
  18687. void sendFakeMouseMove() const;
  18688. void takeKeyboardFocus (const FocusChangeType cause);
  18689. void grabFocusInternal (const FocusChangeType cause, const bool canTryParent = true);
  18690. static void giveAwayFocus();
  18691. void sendEnablementChangeMessage();
  18692. static void* runModalLoopCallback (void*);
  18693. static void bringModalComponentToFront();
  18694. void subtractObscuredRegions (RectangleList& result,
  18695. const int deltaX, const int deltaY,
  18696. const Rectangle& clipRect,
  18697. const Component* const compToAvoid) const throw();
  18698. void clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  18699. const int deltaX, const int deltaY) const throw();
  18700. // how much of the component is not off the edges of its parents
  18701. const Rectangle getUnclippedArea() const;
  18702. void sendVisibilityChangeMessage();
  18703. // This is included here just to cause a compile error if your code is still handling
  18704. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  18705. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  18706. // implement its methods instead of this Component method).
  18707. virtual void filesDropped (const StringArray&, int, int) {}
  18708. // components aren't allowed to have copy constructors, as this would mess up parent
  18709. // hierarchies. You might need to give your subclasses a private dummy constructor like
  18710. // this one to avoid compiler warnings.
  18711. Component (const Component&);
  18712. const Component& operator= (const Component&);
  18713. // (dummy method to cause a deliberate compile error - if you hit this, you need to update your
  18714. // subclass to use the new parameters to keyStateChanged)
  18715. virtual void keyStateChanged() {};
  18716. protected:
  18717. /** @internal */
  18718. virtual void internalRepaint (int x, int y, int w, int h);
  18719. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  18720. /** Overridden from the MessageListener parent class.
  18721. You can override this if you really need to, but be sure to pass your unwanted messages up
  18722. to this base class implementation, as the Component class needs to send itself messages
  18723. to work properly.
  18724. */
  18725. void handleMessage (const Message&);
  18726. };
  18727. #endif // __JUCE_COMPONENT_JUCEHEADER__
  18728. /********* End of inlined file: juce_Component.h *********/
  18729. /********* Start of inlined file: juce_ApplicationCommandInfo.h *********/
  18730. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18731. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18732. /********* Start of inlined file: juce_ApplicationCommandID.h *********/
  18733. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18734. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18735. /** A type used to hold the unique ID for an application command.
  18736. This is a numeric type, so it can be stored as an integer.
  18737. @see ApplicationCommandInfo, ApplicationCommandManager,
  18738. ApplicationCommandTarget, KeyPressMappingSet
  18739. */
  18740. typedef int CommandID;
  18741. /** A set of general-purpose application command IDs.
  18742. Because these commands are likely to be used in most apps, they're defined
  18743. here to help different apps to use the same numeric values for them.
  18744. Of course you don't have to use these, but some of them are used internally by
  18745. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  18746. @see ApplicationCommandInfo, ApplicationCommandManager,
  18747. ApplicationCommandTarget, KeyPressMappingSet
  18748. */
  18749. namespace StandardApplicationCommandIDs
  18750. {
  18751. /** This command ID should be used to send a "Quit the App" command.
  18752. This command is recognised by the JUCEApplication class, so if it is invoked
  18753. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  18754. object will catch it and call JUCEApplication::systemRequestedQuit().
  18755. */
  18756. static const CommandID quit = 0x1001;
  18757. /** The command ID that should be used to send a "Delete" command. */
  18758. static const CommandID del = 0x1002;
  18759. /** The command ID that should be used to send a "Cut" command. */
  18760. static const CommandID cut = 0x1003;
  18761. /** The command ID that should be used to send a "Copy to clipboard" command. */
  18762. static const CommandID copy = 0x1004;
  18763. /** The command ID that should be used to send a "Paste from clipboard" command. */
  18764. static const CommandID paste = 0x1005;
  18765. /** The command ID that should be used to send a "Select all" command. */
  18766. static const CommandID selectAll = 0x1006;
  18767. /** The command ID that should be used to send a "Deselect all" command. */
  18768. static const CommandID deselectAll = 0x1007;
  18769. }
  18770. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  18771. /********* End of inlined file: juce_ApplicationCommandID.h *********/
  18772. /**
  18773. Holds information describing an application command.
  18774. This object is used to pass information about a particular command, such as its
  18775. name, description and other usage flags.
  18776. When an ApplicationCommandTarget is asked to provide information about the commands
  18777. it can perform, this is the structure gets filled-in to describe each one.
  18778. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  18779. ApplicationCommandManager
  18780. */
  18781. struct JUCE_API ApplicationCommandInfo
  18782. {
  18783. ApplicationCommandInfo (const CommandID commandID) throw();
  18784. /** Sets a number of the structures values at once.
  18785. The meanings of each of the parameters is described below, in the appropriate
  18786. member variable's description.
  18787. */
  18788. void setInfo (const String& shortName,
  18789. const String& description,
  18790. const String& categoryName,
  18791. const int flags) throw();
  18792. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  18793. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  18794. is false, the bit is set.
  18795. */
  18796. void setActive (const bool isActive) throw();
  18797. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  18798. */
  18799. void setTicked (const bool isTicked) throw();
  18800. /** Handy method for adding a keypress to the defaultKeypresses array.
  18801. This is just so you can write things like:
  18802. @code
  18803. myinfo.addDefaultKeypress (T('s'), ModifierKeys::commandModifier);
  18804. @endcode
  18805. instead of
  18806. @code
  18807. myinfo.defaultKeypresses.add (KeyPress (T('s'), ModifierKeys::commandModifier));
  18808. @endcode
  18809. */
  18810. void addDefaultKeypress (const int keyCode,
  18811. const ModifierKeys& modifiers) throw();
  18812. /** The command's unique ID number.
  18813. */
  18814. CommandID commandID;
  18815. /** A short name to describe the command.
  18816. This should be suitable for use in menus, on buttons that trigger the command, etc.
  18817. You can use the setInfo() method to quickly set this and some of the command's
  18818. other properties.
  18819. */
  18820. String shortName;
  18821. /** A longer description of the command.
  18822. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  18823. pop-up tooltip describing what the command does.
  18824. You can use the setInfo() method to quickly set this and some of the command's
  18825. other properties.
  18826. */
  18827. String description;
  18828. /** A named category that the command fits into.
  18829. You can give your commands any category you like, and these will be displayed in
  18830. contexts such as the KeyMappingEditorComponent, where the category is used to group
  18831. commands together.
  18832. You can use the setInfo() method to quickly set this and some of the command's
  18833. other properties.
  18834. */
  18835. String categoryName;
  18836. /** A list of zero or more keypresses that should be used as the default keys for
  18837. this command.
  18838. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  18839. this list to initialise the default set of key-to-command mappings.
  18840. @see addDefaultKeypress
  18841. */
  18842. Array <KeyPress> defaultKeypresses;
  18843. /** Flags describing the ways in which this command should be used.
  18844. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  18845. variable.
  18846. */
  18847. enum CommandFlags
  18848. {
  18849. /** Indicates that the command can't currently be performed.
  18850. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  18851. not currently permissable to perform the command. If the flag is set, then
  18852. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  18853. command or show themselves as not being enabled.
  18854. @see ApplicationCommandInfo::setActive
  18855. */
  18856. isDisabled = 1 << 0,
  18857. /** Indicates that the command should have a tick next to it on a menu.
  18858. If your command is shown on a menu and this is set, it'll show a tick next to
  18859. it. Other components such as buttons may also use this flag to indicate that it
  18860. is a value that can be toggled, and is currently in the 'on' state.
  18861. @see ApplicationCommandInfo::setTicked
  18862. */
  18863. isTicked = 1 << 1,
  18864. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  18865. it will call the command twice, once on key-down and again on key-up.
  18866. @see ApplicationCommandTarget::InvocationInfo
  18867. */
  18868. wantsKeyUpDownCallbacks = 1 << 2,
  18869. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  18870. command in its list.
  18871. */
  18872. hiddenFromKeyEditor = 1 << 3,
  18873. /** If this flag is present, then a KeyMappingEditorComponent will display the
  18874. command in its list, but won't allow the assigned keypress to be changed.
  18875. */
  18876. readOnlyInKeyEditor = 1 << 4,
  18877. /** If this flag is present and the command is invoked from a keypress, then any
  18878. buttons or menus that are also connected to the command will not flash to
  18879. indicate that they've been triggered.
  18880. */
  18881. dontTriggerVisualFeedback = 1 << 5
  18882. };
  18883. /** A bitwise-OR of the values specified in the CommandFlags enum.
  18884. You can use the setInfo() method to quickly set this and some of the command's
  18885. other properties.
  18886. */
  18887. int flags;
  18888. };
  18889. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  18890. /********* End of inlined file: juce_ApplicationCommandInfo.h *********/
  18891. /**
  18892. A command target publishes a list of command IDs that it can perform.
  18893. An ApplicationCommandManager despatches commands to targets, which must be
  18894. able to provide information about what commands they can handle.
  18895. To create a target, you'll need to inherit from this class, implementing all of
  18896. its pure virtual methods.
  18897. For info about how a target is chosen to receive a command, see
  18898. ApplicationCommandManager::getFirstCommandTarget().
  18899. @see ApplicationCommandManager, ApplicationCommandInfo
  18900. */
  18901. class JUCE_API ApplicationCommandTarget
  18902. {
  18903. public:
  18904. /** Creates a command target. */
  18905. ApplicationCommandTarget();
  18906. /** Destructor. */
  18907. virtual ~ApplicationCommandTarget();
  18908. /**
  18909. */
  18910. struct JUCE_API InvocationInfo
  18911. {
  18912. InvocationInfo (const CommandID commandID) throw();
  18913. /** The UID of the command that should be performed. */
  18914. CommandID commandID;
  18915. /** The command's flags.
  18916. See ApplicationCommandInfo for a description of these flag values.
  18917. */
  18918. int commandFlags;
  18919. /** The types of context in which the command might be called. */
  18920. enum InvocationMethod
  18921. {
  18922. direct = 0, /**< The command is being invoked directly by a piece of code. */
  18923. fromKeyPress, /**< The command is being invoked by a key-press. */
  18924. fromMenu, /**< The command is being invoked by a menu selection. */
  18925. fromButton /**< The command is being invoked by a button click. */
  18926. };
  18927. /** The type of event that triggered this command. */
  18928. InvocationMethod invocationMethod;
  18929. /** If triggered by a keypress or menu, this will be the component that had the
  18930. keyboard focus at the time.
  18931. If triggered by a button, it may be set to that component, or it may be null.
  18932. */
  18933. Component* originatingComponent;
  18934. /** The keypress that was used to invoke it.
  18935. Note that this will be an invalid keypress if the command was invoked
  18936. by some other means than a keyboard shortcut.
  18937. */
  18938. KeyPress keyPress;
  18939. /** True if the callback is being invoked when the key is pressed,
  18940. false if the key is being released.
  18941. @see KeyPressMappingSet::addCommand()
  18942. */
  18943. bool isKeyDown;
  18944. /** If the key is being released, this indicates how long it had been held
  18945. down for.
  18946. (Only relevant if isKeyDown is false.)
  18947. */
  18948. int millisecsSinceKeyPressed;
  18949. };
  18950. /** This must return the next target to try after this one.
  18951. When a command is being sent, and the first target can't handle
  18952. that command, this method is used to determine the next target that should
  18953. be tried.
  18954. It may return 0 if it doesn't know of another target.
  18955. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  18956. method to return a parent component that might want to handle it.
  18957. @see invoke
  18958. */
  18959. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  18960. /** This must return a complete list of commands that this target can handle.
  18961. Your target should add all the command IDs that it handles to the array that is
  18962. passed-in.
  18963. */
  18964. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  18965. /** This must provide details about one of the commands that this target can perform.
  18966. This will be called with one of the command IDs that the target provided in its
  18967. getAllCommands() methods.
  18968. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  18969. suitable information about the command. (The commandID field will already have been filled-in
  18970. by the caller).
  18971. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  18972. set all the fields at once.
  18973. If the command is currently inactive for some reason, this method must use
  18974. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  18975. bit of the ApplicationCommandInfo::flags field).
  18976. Any default key-presses for the command should be appended to the
  18977. ApplicationCommandInfo::defaultKeypresses field.
  18978. Note that if you change something that affects the status of the commands
  18979. that would be returned by this method (e.g. something that makes some commands
  18980. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  18981. to cause the manager to refresh its status.
  18982. */
  18983. virtual void getCommandInfo (const CommandID commandID,
  18984. ApplicationCommandInfo& result) = 0;
  18985. /** This must actually perform the specified command.
  18986. If this target is able to perform the command specified by the commandID field of the
  18987. InvocationInfo structure, then it should do so, and must return true.
  18988. If it can't handle this command, it should return false, which tells the caller to pass
  18989. the command on to the next target in line.
  18990. @see invoke, ApplicationCommandManager::invoke
  18991. */
  18992. virtual bool perform (const InvocationInfo& info) = 0;
  18993. /** Makes this target invoke a command.
  18994. Your code can call this method to invoke a command on this target, but normally
  18995. you'd call it indirectly via ApplicationCommandManager::invoke() or
  18996. ApplicationCommandManager::invokeDirectly().
  18997. If this target can perform the given command, it will call its perform() method to
  18998. do so. If not, then getNextCommandTarget() will be used to determine the next target
  18999. to try, and the command will be passed along to it.
  19000. @param invocationInfo this must be correctly filled-in, describing the context for
  19001. the invocation.
  19002. @param asynchronously if false, the command will be performed before this method returns.
  19003. If true, a message will be posted so that the command will be performed
  19004. later on the message thread, and this method will return immediately.
  19005. @see perform, ApplicationCommandManager::invoke
  19006. */
  19007. bool invoke (const InvocationInfo& invocationInfo,
  19008. const bool asynchronously);
  19009. /** Invokes a given command directly on this target.
  19010. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  19011. structure.
  19012. */
  19013. bool invokeDirectly (const CommandID commandID,
  19014. const bool asynchronously);
  19015. /** Searches this target and all subsequent ones for the first one that can handle
  19016. the specified command.
  19017. This will use getNextCommandTarget() to determine the chain of targets to try
  19018. after this one.
  19019. */
  19020. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  19021. /** Checks whether this command can currently be performed by this target.
  19022. This will return true only if a call to getCommandInfo() doesn't set the
  19023. isDisabled flag to indicate that the command is inactive.
  19024. */
  19025. bool isCommandActive (const CommandID commandID);
  19026. /** If this object is a Component, this method will seach upwards in its current
  19027. UI hierarchy for the next parent component that implements the
  19028. ApplicationCommandTarget class.
  19029. If your target is a Component, this is a very handy method to use in your
  19030. getNextCommandTarget() implementation.
  19031. */
  19032. ApplicationCommandTarget* findFirstTargetParentComponent();
  19033. juce_UseDebuggingNewOperator
  19034. private:
  19035. // (for async invocation of commands)
  19036. class CommandTargetMessageInvoker : public MessageListener
  19037. {
  19038. public:
  19039. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  19040. ~CommandTargetMessageInvoker();
  19041. void handleMessage (const Message& message);
  19042. private:
  19043. ApplicationCommandTarget* const owner;
  19044. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  19045. const CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  19046. };
  19047. CommandTargetMessageInvoker* messageInvoker;
  19048. friend class CommandTargetMessageInvoker;
  19049. bool tryToInvoke (const InvocationInfo& info, const bool async);
  19050. ApplicationCommandTarget (const ApplicationCommandTarget&);
  19051. const ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  19052. };
  19053. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  19054. /********* End of inlined file: juce_ApplicationCommandTarget.h *********/
  19055. /********* Start of inlined file: juce_ActionListener.h *********/
  19056. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  19057. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  19058. /**
  19059. Receives callbacks to indicate that some kind of event has occurred.
  19060. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  19061. about something that's happened.
  19062. @see ActionListenerList, ActionBroadcaster, ChangeListener
  19063. */
  19064. class JUCE_API ActionListener
  19065. {
  19066. public:
  19067. /** Destructor. */
  19068. virtual ~ActionListener() {}
  19069. /** Overridden by your subclass to receive the callback.
  19070. @param message the string that was specified when the event was triggered
  19071. by a call to ActionListenerList::sendActionMessage()
  19072. */
  19073. virtual void actionListenerCallback (const String& message) = 0;
  19074. };
  19075. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  19076. /********* End of inlined file: juce_ActionListener.h *********/
  19077. /**
  19078. An instance of this class is used to specify initialisation and shutdown
  19079. code for the application.
  19080. An application that wants to run in the JUCE framework needs to declare a
  19081. subclass of JUCEApplication and implement its various pure virtual methods.
  19082. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  19083. to declare an instance of this class and generate a suitable platform-specific
  19084. main() function.
  19085. e.g. @code
  19086. class MyJUCEApp : public JUCEApplication
  19087. {
  19088. // NEVER put objects inside a JUCEApplication class - only use pointers to
  19089. // objects, which you must create in the initialise() method.
  19090. MyApplicationWindow* myMainWindow;
  19091. public:
  19092. MyJUCEApp()
  19093. : myMainWindow (0)
  19094. {
  19095. // never create any Juce objects in the constructor - do all your initialisation
  19096. // in the initialise() method.
  19097. }
  19098. ~MyJUCEApp()
  19099. {
  19100. // all your shutdown code must have already been done in the shutdown() method -
  19101. // nothing should happen in this destructor.
  19102. }
  19103. void initialise (const String& commandLine)
  19104. {
  19105. myMainWindow = new MyApplicationWindow();
  19106. myMainWindow->setBounds (100, 100, 400, 500);
  19107. myMainWindow->setVisible (true);
  19108. }
  19109. void shutdown()
  19110. {
  19111. delete myMainWindow;
  19112. }
  19113. const String getApplicationName()
  19114. {
  19115. return T("Super JUCE-o-matic");
  19116. }
  19117. const String getApplicationVersion()
  19118. {
  19119. return T("1.0");
  19120. }
  19121. };
  19122. // this creates wrapper code to actually launch the app properly.
  19123. START_JUCE_APPLICATION (MyJUCEApp)
  19124. @endcode
  19125. Because this object will be created before Juce has properly initialised, you must
  19126. NEVER add any member variable objects that will be automatically constructed. Likewise
  19127. don't put ANY code in the constructor that could call Juce functions. Any objects that
  19128. you want to add to the class must be pointers, which you should instantiate during the
  19129. initialise() method, and delete in the shutdown() method.
  19130. @see MessageManager, DeletedAtShutdown
  19131. */
  19132. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  19133. private ActionListener
  19134. {
  19135. protected:
  19136. /** Constructs a JUCE app object.
  19137. If subclasses implement a constructor or destructor, they shouldn't call any
  19138. JUCE code in there - put your startup/shutdown code in initialise() and
  19139. shutdown() instead.
  19140. */
  19141. JUCEApplication();
  19142. public:
  19143. /** Destructor.
  19144. If subclasses implement a constructor or destructor, they shouldn't call any
  19145. JUCE code in there - put your startup/shutdown code in initialise() and
  19146. shutdown() instead.
  19147. */
  19148. virtual ~JUCEApplication();
  19149. /** Returns the global instance of the application object being run. */
  19150. static JUCEApplication* getInstance() throw();
  19151. /** Called when the application starts.
  19152. This will be called once to let the application do whatever initialisation
  19153. it needs, create its windows, etc.
  19154. After the method returns, the normal event-dispatch loop will be run,
  19155. until the quit() method is called, at which point the shutdown()
  19156. method will be called to let the application clear up anything it needs
  19157. to delete.
  19158. If during the initialise() method, the application decides not to start-up
  19159. after all, it can just call the quit() method and the event loop won't be run.
  19160. @param commandLineParameters the line passed in does not include the
  19161. name of the executable, just the parameter list.
  19162. @see shutdown, quit
  19163. */
  19164. virtual void initialise (const String& commandLineParameters) = 0;
  19165. /** Returns true if the application hasn't yet completed its initialise() method
  19166. and entered the main event loop.
  19167. This is handy for things like splash screens to know when the app's up-and-running
  19168. properly.
  19169. */
  19170. bool isInitialising() const throw();
  19171. /* Called to allow the application to clear up before exiting.
  19172. After JUCEApplication::quit() has been called, the event-dispatch loop will
  19173. terminate, and this method will get called to allow the app to sort itself
  19174. out.
  19175. Be careful that nothing happens in this method that might rely on messages
  19176. being sent, or any kind of window activity, because the message loop is no
  19177. longer running at this point.
  19178. @see DeletedAtShutdown
  19179. */
  19180. virtual void shutdown() = 0;
  19181. /** Returns the application's name.
  19182. An application must implement this to name itself.
  19183. */
  19184. virtual const String getApplicationName() = 0;
  19185. /** Returns the application's version number.
  19186. An application can implement this to give itself a version.
  19187. (The default implementation of this just returns an empty string).
  19188. */
  19189. virtual const String getApplicationVersion();
  19190. /** Checks whether multiple instances of the app are allowed.
  19191. If you application class returns true for this, more than one instance is
  19192. permitted to run (except on the Mac where this isn't possible).
  19193. If it's false, the second instance won't start, but it you will still get a
  19194. callback to anotherInstanceStarted() to tell you about this - which
  19195. gives you a chance to react to what the user was trying to do.
  19196. */
  19197. virtual bool moreThanOneInstanceAllowed();
  19198. /** Indicates that the user has tried to start up another instance of the app.
  19199. This will get called even if moreThanOneInstanceAllowed() is false.
  19200. */
  19201. virtual void anotherInstanceStarted (const String& commandLine);
  19202. /** Called when the operating system is trying to close the application.
  19203. The default implementation of this method is to call quit(), but it may
  19204. be overloaded to ignore the request or do some other special behaviour
  19205. instead. For example, you might want to offer the user the chance to save
  19206. their changes before quitting, and give them the chance to cancel.
  19207. If you want to send a quit signal to your app, this is the correct method
  19208. to call, because it means that requests that come from the system get handled
  19209. in the same way as those from your own application code. So e.g. you'd
  19210. call this method from a "quit" item on a menu bar.
  19211. */
  19212. virtual void systemRequestedQuit();
  19213. /** If any unhandled exceptions make it through to the message dispatch loop, this
  19214. callback will be triggered, in case you want to log them or do some other
  19215. type of error-handling.
  19216. If the type of exception is derived from the std::exception class, the pointer
  19217. passed-in will be valid. If the exception is of unknown type, this pointer
  19218. will be null.
  19219. */
  19220. virtual void unhandledException (const std::exception* e,
  19221. const String& sourceFilename,
  19222. const int lineNumber);
  19223. /** Signals that the main message loop should stop and the application should terminate.
  19224. This isn't synchronous, it just posts a quit message to the main queue, and
  19225. when this message arrives, the message loop will stop, the shutdown() method
  19226. will be called, and the app will exit.
  19227. Note that this will cause an unconditional quit to happen, so if you need an
  19228. extra level before this, e.g. to give the user the chance to save their work
  19229. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  19230. method - see that method's help for more info.
  19231. @see MessageManager, DeletedAtShutdown
  19232. */
  19233. static void quit();
  19234. /** Sets the value that should be returned as the application's exit code when the
  19235. app quits.
  19236. This is the value that's returned by the main() function. Normally you'd leave this
  19237. as 0 unless you want to indicate an error code.
  19238. @see getApplicationReturnValue
  19239. */
  19240. void setApplicationReturnValue (const int newReturnValue) throw();
  19241. /** Returns the value that has been set as the application's exit code.
  19242. @see setApplicationReturnValue
  19243. */
  19244. int getApplicationReturnValue() const throw() { return appReturnValue; }
  19245. /** Returns the application's command line params.
  19246. */
  19247. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  19248. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  19249. /** @internal */
  19250. static int main (String& commandLine, JUCEApplication* const newApp);
  19251. /** @internal */
  19252. static int main (int argc, char* argv[], JUCEApplication* const newApp);
  19253. /** @internal */
  19254. static void sendUnhandledException (const std::exception* const e,
  19255. const char* const sourceFile,
  19256. const int lineNumber);
  19257. /** @internal */
  19258. ApplicationCommandTarget* getNextCommandTarget();
  19259. /** @internal */
  19260. void getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result);
  19261. /** @internal */
  19262. void getAllCommands (Array <CommandID>& commands);
  19263. /** @internal */
  19264. bool perform (const InvocationInfo& info);
  19265. /** @internal */
  19266. void actionListenerCallback (const String& message);
  19267. private:
  19268. String commandLineParameters;
  19269. int appReturnValue;
  19270. bool stillInitialising;
  19271. InterProcessLock* appLock;
  19272. JUCEApplication (const JUCEApplication&);
  19273. const JUCEApplication& operator= (const JUCEApplication&);
  19274. public:
  19275. /** @internal */
  19276. bool initialiseApp (String& commandLine);
  19277. /** @internal */
  19278. static int shutdownAppAndClearUp();
  19279. };
  19280. #endif // __JUCE_APPLICATION_JUCEHEADER__
  19281. /********* End of inlined file: juce_Application.h *********/
  19282. #endif
  19283. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  19284. #endif
  19285. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  19286. #endif
  19287. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  19288. /********* Start of inlined file: juce_ApplicationCommandManager.h *********/
  19289. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  19290. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  19291. /********* Start of inlined file: juce_AsyncUpdater.h *********/
  19292. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  19293. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  19294. /**
  19295. Has a callback method that is triggered asynchronously.
  19296. This object allows an asynchronous callback function to be triggered, for
  19297. tasks such as coalescing multiple updates into a single callback later on.
  19298. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  19299. message thread calling handleAsyncUpdate() as soon as it can.
  19300. */
  19301. class JUCE_API AsyncUpdater
  19302. {
  19303. public:
  19304. /** Creates an AsyncUpdater object. */
  19305. AsyncUpdater() throw();
  19306. /** Destructor.
  19307. If there are any pending callbacks when the object is deleted, these are lost.
  19308. */
  19309. virtual ~AsyncUpdater();
  19310. /** Causes the callback to be triggered at a later time.
  19311. This method returns immediately, having made sure that a callback
  19312. to the handleAsyncUpdate() method will occur as soon as possible.
  19313. If an update callback is already pending but hasn't happened yet, calls
  19314. to this method will be ignored.
  19315. It's thread-safe to call this method from any number of threads without
  19316. needing to worry about locking.
  19317. */
  19318. void triggerAsyncUpdate() throw();
  19319. /** This will stop any pending updates from happening.
  19320. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  19321. callback happens, this will cancel the handleAsyncUpdate() callback.
  19322. */
  19323. void cancelPendingUpdate() throw();
  19324. /** If an update has been triggered and is pending, this will invoke it
  19325. synchronously.
  19326. Use this as a kind of "flush" operation - if an update is pending, the
  19327. handleAsyncUpdate() method will be called immediately; if no update is
  19328. pending, then nothing will be done.
  19329. */
  19330. void handleUpdateNowIfNeeded();
  19331. /** Called back to do whatever your class needs to do.
  19332. This method is called by the message thread at the next convenient time
  19333. after the triggerAsyncUpdate() method has been called.
  19334. */
  19335. virtual void handleAsyncUpdate() = 0;
  19336. private:
  19337. class AsyncUpdaterInternal : public MessageListener
  19338. {
  19339. public:
  19340. AsyncUpdaterInternal() throw() {}
  19341. ~AsyncUpdaterInternal() {}
  19342. void handleMessage (const Message&);
  19343. AsyncUpdater* owner;
  19344. private:
  19345. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  19346. const AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  19347. };
  19348. AsyncUpdaterInternal internalAsyncHandler;
  19349. bool asyncMessagePending;
  19350. };
  19351. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  19352. /********* End of inlined file: juce_AsyncUpdater.h *********/
  19353. /********* Start of inlined file: juce_Desktop.h *********/
  19354. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  19355. #define __JUCE_DESKTOP_JUCEHEADER__
  19356. /********* Start of inlined file: juce_DeletedAtShutdown.h *********/
  19357. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19358. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19359. /**
  19360. Classes derived from this will be automatically deleted when the application exits.
  19361. After JUCEApplication::shutdown() has been called, any objects derived from
  19362. DeletedAtShutdown which are still in existence will be deleted in the reverse
  19363. order to that in which they were created.
  19364. So if you've got a singleton and don't want to have to explicitly delete it, just
  19365. inherit from this and it'll be taken care of.
  19366. */
  19367. class JUCE_API DeletedAtShutdown
  19368. {
  19369. protected:
  19370. /** Creates a DeletedAtShutdown object. */
  19371. DeletedAtShutdown() throw();
  19372. /** Destructor.
  19373. It's ok to delete these objects explicitly - it's only the ones left
  19374. dangling at the end that will be deleted automatically.
  19375. */
  19376. virtual ~DeletedAtShutdown();
  19377. public:
  19378. /** Deletes all extant objects.
  19379. This shouldn't be used by applications, as it's called automatically
  19380. in the shutdown code of the JUCEApplication class.
  19381. */
  19382. static void deleteAll();
  19383. private:
  19384. DeletedAtShutdown (const DeletedAtShutdown&);
  19385. const DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  19386. };
  19387. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19388. /********* End of inlined file: juce_DeletedAtShutdown.h *********/
  19389. /********* Start of inlined file: juce_Timer.h *********/
  19390. #ifndef __JUCE_TIMER_JUCEHEADER__
  19391. #define __JUCE_TIMER_JUCEHEADER__
  19392. class InternalTimerThread;
  19393. /**
  19394. Repeatedly calls a user-defined method at a specified time interval.
  19395. A Timer's timerCallback() method will be repeatedly called at a given
  19396. interval. Initially when a Timer object is created, they will do nothing
  19397. until the startTimer() method is called, then the message thread will
  19398. start calling it back until stopTimer() is called.
  19399. The time interval isn't guaranteed to be precise to any more than maybe
  19400. 10-20ms, and the intervals may end up being much longer than requested if the
  19401. system is busy. Because it's the message thread that is doing the callbacks,
  19402. any messages that take a significant amount of time to process will block
  19403. all the timers for that period.
  19404. If you need to have a single callback that is shared by multiple timers with
  19405. different frequencies, then the MultiTimer class allows you to do that - its
  19406. structure is very similar to the Timer class, but contains multiple timers
  19407. internally, each one identified by an ID number.
  19408. @see MultiTimer
  19409. */
  19410. class JUCE_API Timer
  19411. {
  19412. protected:
  19413. /** Creates a Timer.
  19414. When created, the timer is stopped, so use startTimer() to get it going.
  19415. */
  19416. Timer() throw();
  19417. /** Creates a copy of another timer.
  19418. Note that this timer won't be started, even if the one you're copying
  19419. is running.
  19420. */
  19421. Timer (const Timer& other) throw();
  19422. public:
  19423. /** Destructor. */
  19424. virtual ~Timer();
  19425. /** The user-defined callback routine that actually gets called periodically.
  19426. It's perfectly ok to call startTimer() or stopTimer() from within this
  19427. callback to change the subsequent intervals.
  19428. */
  19429. virtual void timerCallback() = 0;
  19430. /** Starts the timer and sets the length of interval required.
  19431. If the timer is already started, this will reset it, so the
  19432. time between calling this method and the next timer callback
  19433. will not be less than the interval length passed in.
  19434. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  19435. rounded up to 1)
  19436. */
  19437. void startTimer (const int intervalInMilliseconds) throw();
  19438. /** Stops the timer.
  19439. No more callbacks will be made after this method returns.
  19440. If this is called from a different thread, any callbacks that may
  19441. be currently executing may be allowed to finish before the method
  19442. returns.
  19443. */
  19444. void stopTimer() throw();
  19445. /** Checks if the timer has been started.
  19446. @returns true if the timer is running.
  19447. */
  19448. bool isTimerRunning() const throw() { return periodMs > 0; }
  19449. /** Returns the timer's interval.
  19450. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  19451. */
  19452. int getTimerInterval() const throw() { return periodMs; }
  19453. private:
  19454. friend class InternalTimerThread;
  19455. int countdownMs, periodMs;
  19456. Timer* previous;
  19457. Timer* next;
  19458. const Timer& operator= (const Timer&);
  19459. };
  19460. #endif // __JUCE_TIMER_JUCEHEADER__
  19461. /********* End of inlined file: juce_Timer.h *********/
  19462. /**
  19463. Classes can implement this interface and register themselves with the Desktop class
  19464. to receive callbacks when the currently focused component changes.
  19465. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  19466. */
  19467. class JUCE_API FocusChangeListener
  19468. {
  19469. public:
  19470. /** Destructor. */
  19471. virtual ~FocusChangeListener() {}
  19472. /** Callback to indicate that the currently focused component has changed. */
  19473. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  19474. };
  19475. /**
  19476. Describes and controls aspects of the computer's desktop.
  19477. */
  19478. class JUCE_API Desktop : private DeletedAtShutdown,
  19479. private Timer,
  19480. private AsyncUpdater
  19481. {
  19482. public:
  19483. /** There's only one dektop object, and this method will return it.
  19484. */
  19485. static Desktop& JUCE_CALLTYPE getInstance() throw();
  19486. /** Returns a list of the positions of all the monitors available.
  19487. The first rectangle in the list will be the main monitor area.
  19488. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19489. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19490. */
  19491. const RectangleList getAllMonitorDisplayAreas (const bool clippedToWorkArea = true) const throw();
  19492. /** Returns the position and size of the main monitor.
  19493. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19494. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19495. */
  19496. const Rectangle getMainMonitorArea (const bool clippedToWorkArea = true) const throw();
  19497. /** Returns the position and size of the monitor which contains this co-ordinate.
  19498. If none of the monitors contains the point, this will just return the
  19499. main monitor.
  19500. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  19501. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  19502. */
  19503. const Rectangle getMonitorAreaContaining (int x, int y, const bool clippedToWorkArea = true) const throw();
  19504. /** Returns the mouse position.
  19505. The co-ordinates are relative to the top-left of the main monitor.
  19506. */
  19507. static void getMousePosition (int& x, int& y) throw();
  19508. /** Makes the mouse pointer jump to a given location.
  19509. The co-ordinates are relative to the top-left of the main monitor.
  19510. */
  19511. static void setMousePosition (int x, int y) throw();
  19512. /** Returns the last position at which a mouse button was pressed.
  19513. */
  19514. static void getLastMouseDownPosition (int& x, int& y) throw();
  19515. /** Returns the number of times the mouse button has been clicked since the
  19516. app started.
  19517. Each mouse-down event increments this number by 1.
  19518. */
  19519. static int getMouseButtonClickCounter() throw();
  19520. /** This lets you prevent the screensaver from becoming active.
  19521. Handy if you're running some sort of presentation app where having a screensaver
  19522. appear would be annoying.
  19523. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  19524. won't enable a screensaver unless the user has actually set one up).
  19525. The disablement will only happen while the Juce application is the foreground
  19526. process - if another task is running in front of it, then the screensaver will
  19527. be unaffected.
  19528. @see isScreenSaverEnabled
  19529. */
  19530. static void setScreenSaverEnabled (const bool isEnabled) throw();
  19531. /** Returns true if the screensaver has not been turned off.
  19532. This will return the last value passed into setScreenSaverEnabled(). Note that
  19533. it won't tell you whether the user is actually using a screen saver, just
  19534. whether this app is deliberately preventing one from running.
  19535. @see setScreenSaverEnabled
  19536. */
  19537. static bool isScreenSaverEnabled() throw();
  19538. /** Registers a MouseListener that will receive all mouse events that occur on
  19539. any component.
  19540. @see removeGlobalMouseListener
  19541. */
  19542. void addGlobalMouseListener (MouseListener* const listener) throw();
  19543. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  19544. method.
  19545. @see addGlobalMouseListener
  19546. */
  19547. void removeGlobalMouseListener (MouseListener* const listener) throw();
  19548. /** Registers a MouseListener that will receive a callback whenever the focused
  19549. component changes.
  19550. */
  19551. void addFocusChangeListener (FocusChangeListener* const listener) throw();
  19552. /** Unregisters a listener that was added with addFocusChangeListener(). */
  19553. void removeFocusChangeListener (FocusChangeListener* const listener) throw();
  19554. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  19555. The component must already be on the desktop for this method to work. It will
  19556. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  19557. etc will be hidden.
  19558. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  19559. the component that's currently being used will be resized back to the size
  19560. and position it was in before being put into this mode.
  19561. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  19562. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  19563. to hide as much on-screen paraphenalia as possible.
  19564. */
  19565. void setKioskModeComponent (Component* componentToUse,
  19566. const bool allowMenusAndBars = true);
  19567. /** Returns the component that is currently being used in kiosk-mode.
  19568. This is the component that was last set by setKioskModeComponent(). If none
  19569. has been set, this returns 0.
  19570. */
  19571. Component* getKioskModeComponent() const { return kioskModeComponent; }
  19572. /** Returns the number of components that are currently active as top-level
  19573. desktop windows.
  19574. @see getComponent, Component::addToDesktop
  19575. */
  19576. int getNumComponents() const throw();
  19577. /** Returns one of the top-level desktop window components.
  19578. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  19579. index is out-of-range.
  19580. @see getNumComponents, Component::addToDesktop
  19581. */
  19582. Component* getComponent (const int index) const throw();
  19583. /** Finds the component at a given screen location.
  19584. This will drill down into top-level windows to find the child component at
  19585. the given position.
  19586. Returns 0 if the co-ordinates are inside a non-Juce window.
  19587. */
  19588. Component* findComponentAt (const int screenX,
  19589. const int screenY) const;
  19590. juce_UseDebuggingNewOperator
  19591. /** Tells this object to refresh its idea of what the screen resolution is.
  19592. (Called internally by the native code).
  19593. */
  19594. void refreshMonitorSizes() throw();
  19595. /** True if the OS supports semitransparent windows */
  19596. static bool canUseSemiTransparentWindows() throw();
  19597. private:
  19598. friend class Component;
  19599. friend class ComponentPeer;
  19600. SortedSet <void*> mouseListeners, focusListeners;
  19601. VoidArray desktopComponents;
  19602. friend class DeletedAtShutdown;
  19603. friend class TopLevelWindowManager;
  19604. Desktop() throw();
  19605. ~Desktop() throw();
  19606. Array <Rectangle> monitorCoordsClipped, monitorCoordsUnclipped;
  19607. int lastMouseX, lastMouseY;
  19608. Component* kioskModeComponent;
  19609. Rectangle kioskComponentOriginalBounds;
  19610. void timerCallback();
  19611. void sendMouseMove();
  19612. void resetTimer() throw();
  19613. int getNumDisplayMonitors() const throw();
  19614. const Rectangle getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw();
  19615. void addDesktopComponent (Component* const c) throw();
  19616. void removeDesktopComponent (Component* const c) throw();
  19617. void componentBroughtToFront (Component* const c) throw();
  19618. void triggerFocusCallback() throw();
  19619. void handleAsyncUpdate();
  19620. Desktop (const Desktop&);
  19621. const Desktop& operator= (const Desktop&);
  19622. };
  19623. #endif // __JUCE_DESKTOP_JUCEHEADER__
  19624. /********* End of inlined file: juce_Desktop.h *********/
  19625. class KeyPressMappingSet;
  19626. class ApplicationCommandManagerListener;
  19627. /**
  19628. One of these objects holds a list of all the commands your app can perform,
  19629. and despatches these commands when needed.
  19630. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  19631. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  19632. to invoke automatically, which means you don't have to handle the result of a menu
  19633. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  19634. which can choose which events they want to handle.
  19635. This architecture also allows for nested ApplicationCommandTargets, so that for example
  19636. you could have two different objects, one inside the other, both of which can respond to
  19637. a "delete" command. Depending on which one has focus, the command will be sent to the
  19638. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  19639. method.
  19640. To set up your app to use commands, you'll need to do the following:
  19641. - Create a global ApplicationCommandManager to hold the list of all possible
  19642. commands. (This will also manage a set of key-mappings for them).
  19643. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  19644. This allows the object to provide a list of commands that it can perform, and
  19645. to handle them.
  19646. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  19647. or ApplicationCommandManager::registerCommand().
  19648. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  19649. method to access the key-mapper object, which you will need to register as a key-listener
  19650. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  19651. about setting this up.
  19652. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  19653. cause these commands to be invoked automatically.
  19654. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  19655. When a command is invoked, the ApplicationCommandManager will try to choose the best
  19656. ApplicationCommandTarget to receive the specified command. To do this it will use the
  19657. current keyboard focus to see which component might be interested, and will search the
  19658. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  19659. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  19660. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  19661. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  19662. point if the command still hasn't been performed, it will be passed to the current
  19663. JUCEApplication object (which is itself an ApplicationCommandTarget).
  19664. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  19665. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  19666. the object yourself.
  19667. @see ApplicationCommandTarget, ApplicationCommandInfo
  19668. */
  19669. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  19670. private FocusChangeListener
  19671. {
  19672. public:
  19673. /** Creates an ApplicationCommandManager.
  19674. Once created, you'll need to register all your app's commands with it, using
  19675. ApplicationCommandManager::registerAllCommandsForTarget() or
  19676. ApplicationCommandManager::registerCommand().
  19677. */
  19678. ApplicationCommandManager();
  19679. /** Destructor.
  19680. Make sure that you don't delete this if pointers to it are still being used by
  19681. objects such as PopupMenus or Buttons.
  19682. */
  19683. virtual ~ApplicationCommandManager();
  19684. /** Clears the current list of all commands.
  19685. Note that this will also clear the contents of the KeyPressMappingSet.
  19686. */
  19687. void clearCommands();
  19688. /** Adds a command to the list of registered commands.
  19689. @see registerAllCommandsForTarget
  19690. */
  19691. void registerCommand (const ApplicationCommandInfo& newCommand);
  19692. /** Adds all the commands that this target publishes to the manager's list.
  19693. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  19694. to get details about all the commands that this target can do, and will call
  19695. registerCommand() to add each one to the manger's list.
  19696. @see registerCommand
  19697. */
  19698. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  19699. /** Removes the command with a specified ID.
  19700. Note that this will also remove any key mappings that are mapped to the command.
  19701. */
  19702. void removeCommand (const CommandID commandID);
  19703. /** This should be called to tell the manager that one of its registered commands may have changed
  19704. its active status.
  19705. Because the command manager only finds out whether a command is active or inactive by querying
  19706. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  19707. allows things like buttons to update their enablement, etc.
  19708. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  19709. for any registered listeners.
  19710. */
  19711. void commandStatusChanged();
  19712. /** Returns the number of commands that have been registered.
  19713. @see registerCommand
  19714. */
  19715. int getNumCommands() const throw() { return commands.size(); }
  19716. /** Returns the details about one of the registered commands.
  19717. The index is between 0 and (getNumCommands() - 1).
  19718. */
  19719. const ApplicationCommandInfo* getCommandForIndex (const int index) const throw() { return commands [index]; }
  19720. /** Returns the details about a given command ID.
  19721. This will search the list of registered commands for one with the given command
  19722. ID number, and return its associated info. If no matching command is found, this
  19723. will return 0.
  19724. */
  19725. const ApplicationCommandInfo* getCommandForID (const CommandID commandID) const throw();
  19726. /** Returns the name field for a command.
  19727. An empty string is returned if no command with this ID has been registered.
  19728. @see getDescriptionOfCommand
  19729. */
  19730. const String getNameOfCommand (const CommandID commandID) const throw();
  19731. /** Returns the description field for a command.
  19732. An empty string is returned if no command with this ID has been registered. If the
  19733. command has no description, this will return its short name field instead.
  19734. @see getNameOfCommand
  19735. */
  19736. const String getDescriptionOfCommand (const CommandID commandID) const throw();
  19737. /** Returns the list of categories.
  19738. This will go through all registered commands, and return a list of all the distict
  19739. categoryName values from their ApplicationCommandInfo structure.
  19740. @see getCommandsInCategory()
  19741. */
  19742. const StringArray getCommandCategories() const throw();
  19743. /** Returns a list of all the command UIDs in a particular category.
  19744. @see getCommandCategories()
  19745. */
  19746. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  19747. /** Returns the manager's internal set of key mappings.
  19748. This object can be used to edit the keypresses. To actually link this object up
  19749. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  19750. class.
  19751. @see KeyPressMappingSet
  19752. */
  19753. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  19754. /** Invokes the given command directly, sending it to the default target.
  19755. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  19756. structure.
  19757. */
  19758. bool invokeDirectly (const CommandID commandID,
  19759. const bool asynchronously);
  19760. /** Sends a command to the default target.
  19761. This will choose a target using getFirstCommandTarget(), and send the specified command
  19762. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  19763. first target can't handle the command, it will be passed on to targets further down the
  19764. chain (see ApplicationCommandTarget::invoke() for more info).
  19765. @param invocationInfo this must be correctly filled-in, describing the context for
  19766. the invocation.
  19767. @param asynchronously if false, the command will be performed before this method returns.
  19768. If true, a message will be posted so that the command will be performed
  19769. later on the message thread, and this method will return immediately.
  19770. @see ApplicationCommandTarget::invoke
  19771. */
  19772. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  19773. const bool asynchronously);
  19774. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  19775. Whenever the manager needs to know which target a command should be sent to, it calls
  19776. this method to determine the first one to try.
  19777. By default, this method will return the target that was set by calling setFirstCommandTarget().
  19778. If no target is set, it will return the result of findDefaultComponentTarget().
  19779. If you need to make sure all commands go via your own custom target, then you can
  19780. either use setFirstCommandTarget() to specify a single target, or override this method
  19781. if you need more complex logic to choose one.
  19782. It may return 0 if no targets are available.
  19783. @see getTargetForCommand, invoke, invokeDirectly
  19784. */
  19785. virtual ApplicationCommandTarget* getFirstCommandTarget (const CommandID commandID);
  19786. /** Sets a target to be returned by getFirstCommandTarget().
  19787. If this is set to 0, then getFirstCommandTarget() will by default return the
  19788. result of findDefaultComponentTarget().
  19789. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  19790. deleting the target object.
  19791. */
  19792. void setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw();
  19793. /** Tries to find the best target to use to perform a given command.
  19794. This will call getFirstCommandTarget() to find the preferred target, and will
  19795. check whether that target can handle the given command. If it can't, then it'll use
  19796. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  19797. so on until no more are available.
  19798. If no targets are found that can perform the command, this method will return 0.
  19799. If a target is found, then it will get the target to fill-in the upToDateInfo
  19800. structure with the latest info about that command, so that the caller can see
  19801. whether the command is disabled, ticked, etc.
  19802. */
  19803. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID,
  19804. ApplicationCommandInfo& upToDateInfo);
  19805. /** Registers a listener that will be called when various events occur. */
  19806. void addListener (ApplicationCommandManagerListener* const listener) throw();
  19807. /** Deregisters a previously-added listener. */
  19808. void removeListener (ApplicationCommandManagerListener* const listener) throw();
  19809. /** Looks for a suitable command target based on which Components have the keyboard focus.
  19810. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  19811. but is exposed here in case it's useful.
  19812. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  19813. windows, etc., and using the findTargetForComponent() method.
  19814. */
  19815. static ApplicationCommandTarget* findDefaultComponentTarget();
  19816. /** Examines this component and all its parents in turn, looking for the first one
  19817. which is a ApplicationCommandTarget.
  19818. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  19819. that class.
  19820. */
  19821. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  19822. juce_UseDebuggingNewOperator
  19823. private:
  19824. OwnedArray <ApplicationCommandInfo> commands;
  19825. SortedSet <void*> listeners;
  19826. ScopedPointer <KeyPressMappingSet> keyMappings;
  19827. ApplicationCommandTarget* firstTarget;
  19828. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const;
  19829. void handleAsyncUpdate();
  19830. void globalFocusChanged (Component*);
  19831. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  19832. // version of this method.
  19833. virtual short getFirstCommandTarget() { return 0; }
  19834. };
  19835. /**
  19836. A listener that receives callbacks from an ApplicationCommandManager when
  19837. commands are invoked or the command list is changed.
  19838. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  19839. */
  19840. class JUCE_API ApplicationCommandManagerListener
  19841. {
  19842. public:
  19843. /** Destructor. */
  19844. virtual ~ApplicationCommandManagerListener() {}
  19845. /** Called when an app command is about to be invoked. */
  19846. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  19847. /** Called when commands are registered or deregistered from the
  19848. command manager, or when commands are made active or inactive.
  19849. Note that if you're using this to watch for changes to whether a command is disabled,
  19850. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  19851. whenever the status of your command might have changed.
  19852. */
  19853. virtual void applicationCommandListChanged() = 0;
  19854. };
  19855. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  19856. /********* End of inlined file: juce_ApplicationCommandManager.h *********/
  19857. #endif
  19858. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  19859. #endif
  19860. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  19861. /********* Start of inlined file: juce_ApplicationProperties.h *********/
  19862. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  19863. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  19864. /********* Start of inlined file: juce_PropertiesFile.h *********/
  19865. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  19866. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  19867. /** Wrapper on a file that stores a list of key/value data pairs.
  19868. Useful for storing application settings, etc. See the PropertySet class for
  19869. the interfaces that read and write values.
  19870. Not designed for very large amounts of data, as it keeps all the values in
  19871. memory and writes them out to disk lazily when they are changed.
  19872. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  19873. with it, and these will be signalled when a value changes.
  19874. @see PropertySet
  19875. */
  19876. class JUCE_API PropertiesFile : public PropertySet,
  19877. public ChangeBroadcaster,
  19878. private Timer
  19879. {
  19880. public:
  19881. enum FileFormatOptions
  19882. {
  19883. ignoreCaseOfKeyNames = 1,
  19884. storeAsBinary = 2,
  19885. storeAsCompressedBinary = 4,
  19886. storeAsXML = 8
  19887. };
  19888. /**
  19889. Creates a PropertiesFile object.
  19890. @param file the file to use
  19891. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  19892. is changed, the object will wait for this amount
  19893. of time and then save the file. If zero, the file
  19894. will be written to disk immediately on being changed
  19895. (which might be slow, as it'll re-write synchronously
  19896. each time a value-change method is called). If it is
  19897. less than zero, the file won't be saved until
  19898. save() or saveIfNeeded() are explicitly called.
  19899. @param options a combination of the flags in the FileFormatOptions
  19900. enum, which specify the type of file to save, and other
  19901. options.
  19902. */
  19903. PropertiesFile (const File& file,
  19904. const int millisecondsBeforeSaving,
  19905. const int options) throw();
  19906. /** Destructor.
  19907. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  19908. */
  19909. ~PropertiesFile();
  19910. /** This will flush all the values to disk if they've changed since the last
  19911. time they were saved.
  19912. Returns false if it fails to write to the file for some reason (maybe because
  19913. it's read-only or the directory doesn't exist or something).
  19914. @see save
  19915. */
  19916. bool saveIfNeeded();
  19917. /** This will force a write-to-disk of the current values, regardless of whether
  19918. anything has changed since the last save.
  19919. Returns false if it fails to write to the file for some reason (maybe because
  19920. it's read-only or the directory doesn't exist or something).
  19921. @see saveIfNeeded
  19922. */
  19923. bool save();
  19924. /** Returns true if the properties have been altered since the last time they were
  19925. saved.
  19926. */
  19927. bool needsToBeSaved() const throw();
  19928. /** Returns the file that's being used. */
  19929. const File getFile() const throw();
  19930. /** Handy utility to create a properties file in whatever the standard OS-specific
  19931. location is for these things.
  19932. This uses getDefaultAppSettingsFile() to decide what file to create, then
  19933. creates a PropertiesFile object with the specified properties. See
  19934. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  19935. what the parameters do.
  19936. @see getDefaultAppSettingsFile
  19937. */
  19938. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  19939. const String& fileNameSuffix,
  19940. const String& folderName,
  19941. const bool commonToAllUsers,
  19942. const int millisecondsBeforeSaving,
  19943. const int propertiesFileOptions);
  19944. /** Handy utility to choose a file in the standard OS-dependent location for application
  19945. settings files.
  19946. So on a Mac, this will return a file called:
  19947. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  19948. On Windows it'll return something like:
  19949. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  19950. On Linux it'll return
  19951. ~/.[folderName]/[applicationName].[fileNameSuffix]
  19952. If you pass an empty string as the folder name, it'll use the app name for this (or
  19953. omit the folder name on the Mac).
  19954. If commonToAllUsers is true, then this will return the same file for all users of the
  19955. computer, regardless of the current user. If it is false, the file will be specific to
  19956. only the current user. Use this to choose whether you're saving settings that are common
  19957. or user-specific.
  19958. */
  19959. static const File getDefaultAppSettingsFile (const String& applicationName,
  19960. const String& fileNameSuffix,
  19961. const String& folderName,
  19962. const bool commonToAllUsers);
  19963. juce_UseDebuggingNewOperator
  19964. protected:
  19965. virtual void propertyChanged();
  19966. private:
  19967. File file;
  19968. int timerInterval;
  19969. const int options;
  19970. bool needsWriting;
  19971. void timerCallback();
  19972. PropertiesFile (const PropertiesFile&);
  19973. const PropertiesFile& operator= (const PropertiesFile&);
  19974. };
  19975. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  19976. /********* End of inlined file: juce_PropertiesFile.h *********/
  19977. /**
  19978. Manages a collection of properties.
  19979. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  19980. as a singleton.
  19981. It holds two different PropertiesFile objects internally, one for user-specific
  19982. settings (stored in your user directory), and one for settings that are common to
  19983. all users (stored in a folder accessible to all users).
  19984. The class manages the creation of these files on-demand, allowing access via the
  19985. getUserSettings() and getCommonSettings() methods. It also has a few handy
  19986. methods like testWriteAccess() to check that the files can be saved.
  19987. If you're using one of these as a singleton, then your app's start-up code should
  19988. first of all call setStorageParameters() to tell it the parameters to use to create
  19989. the properties files.
  19990. @see PropertiesFile
  19991. */
  19992. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  19993. {
  19994. public:
  19995. /**
  19996. Creates an ApplicationProperties object.
  19997. Before using it, you must call setStorageParameters() to give it the info
  19998. it needs to create the property files.
  19999. */
  20000. ApplicationProperties() throw();
  20001. /** Destructor.
  20002. */
  20003. ~ApplicationProperties();
  20004. juce_DeclareSingleton (ApplicationProperties, false)
  20005. /** Gives the object the information it needs to create the appropriate properties files.
  20006. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  20007. info about how these parameters are used.
  20008. */
  20009. void setStorageParameters (const String& applicationName,
  20010. const String& fileNameSuffix,
  20011. const String& folderName,
  20012. const int millisecondsBeforeSaving,
  20013. const int propertiesFileOptions) throw();
  20014. /** Tests whether the files can be successfully written to, and can show
  20015. an error message if not.
  20016. Returns true if none of the tests fail.
  20017. @param testUserSettings if true, the user settings file will be tested
  20018. @param testCommonSettings if true, the common settings file will be tested
  20019. @param showWarningDialogOnFailure if true, the method will show a helpful error
  20020. message box if either of the tests fail
  20021. */
  20022. bool testWriteAccess (const bool testUserSettings,
  20023. const bool testCommonSettings,
  20024. const bool showWarningDialogOnFailure);
  20025. /** Returns the user settings file.
  20026. The first time this is called, it will create and load the properties file.
  20027. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  20028. the common settings are used as a second-chance place to look. This is done via the
  20029. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  20030. to the fallback for the user settings.
  20031. @see getCommonSettings
  20032. */
  20033. PropertiesFile* getUserSettings() throw();
  20034. /** Returns the common settings file.
  20035. The first time this is called, it will create and load the properties file.
  20036. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  20037. read-only (e.g. because the user doesn't have permission to write
  20038. to shared files), then this will return the user settings instead,
  20039. (like getUserSettings() would do). This is handy if you'd like to
  20040. write a value to the common settings, but if that's no possible,
  20041. then you'd rather write to the user settings than none at all.
  20042. If returnUserPropsIfReadOnly is false, this method will always return
  20043. the common settings, even if any changes to them can't be saved.
  20044. @see getUserSettings
  20045. */
  20046. PropertiesFile* getCommonSettings (const bool returnUserPropsIfReadOnly) throw();
  20047. /** Saves both files if they need to be saved.
  20048. @see PropertiesFile::saveIfNeeded
  20049. */
  20050. bool saveIfNeeded();
  20051. /** Flushes and closes both files if they are open.
  20052. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  20053. and closes both files. They will then be re-opened the next time getUserSettings()
  20054. or getCommonSettings() is called.
  20055. */
  20056. void closeFiles();
  20057. juce_UseDebuggingNewOperator
  20058. private:
  20059. ScopedPointer <PropertiesFile> userProps, commonProps;
  20060. String appName, fileSuffix, folderName;
  20061. int msBeforeSaving, options;
  20062. int commonSettingsAreReadOnly;
  20063. ApplicationProperties (const ApplicationProperties&);
  20064. const ApplicationProperties& operator= (const ApplicationProperties&);
  20065. void openFiles() throw();
  20066. };
  20067. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  20068. /********* End of inlined file: juce_ApplicationProperties.h *********/
  20069. #endif
  20070. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  20071. /********* Start of inlined file: juce_AiffAudioFormat.h *********/
  20072. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  20073. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  20074. /********* Start of inlined file: juce_AudioFormat.h *********/
  20075. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  20076. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  20077. /********* Start of inlined file: juce_AudioFormatReader.h *********/
  20078. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  20079. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  20080. class AudioFormat;
  20081. /**
  20082. Reads samples from an audio file stream.
  20083. A subclass that reads a specific type of audio format will be created by
  20084. an AudioFormat object.
  20085. @see AudioFormat, AudioFormatWriter
  20086. */
  20087. class JUCE_API AudioFormatReader
  20088. {
  20089. protected:
  20090. /** Creates an AudioFormatReader object.
  20091. @param sourceStream the stream to read from - this will be deleted
  20092. by this object when it is no longer needed. (Some
  20093. specialised readers might not use this parameter and
  20094. can leave it as 0).
  20095. @param formatName the description that will be returned by the getFormatName()
  20096. method
  20097. */
  20098. AudioFormatReader (InputStream* const sourceStream,
  20099. const String& formatName);
  20100. public:
  20101. /** Destructor. */
  20102. virtual ~AudioFormatReader();
  20103. /** Returns a description of what type of format this is.
  20104. E.g. "AIFF"
  20105. */
  20106. const String getFormatName() const throw() { return formatName; }
  20107. /** Reads samples from the stream.
  20108. @param destSamples an array of buffers into which the sample data for each
  20109. channel will be written.
  20110. If the format is fixed-point, each channel will be written
  20111. as an array of 32-bit signed integers using the full
  20112. range -0x80000000 to 0x7fffffff, regardless of the source's
  20113. bit-depth. If it is a floating-point format, you should cast
  20114. the resulting array to a (float**) to get the values (in the
  20115. range -1.0 to 1.0 or beyond)
  20116. If the format is stereo, then destSamples[0] is the left channel
  20117. data, and destSamples[1] is the right channel.
  20118. The numDestChannels parameter indicates how many pointers this array
  20119. contains, but some of these pointers can be null if you don't want to
  20120. read data for some of the channels
  20121. @param numDestChannels the number of array elements in the destChannels array
  20122. @param startSampleInSource the position in the audio file or stream at which the samples
  20123. should be read, as a number of samples from the start of the
  20124. stream. It's ok for this to be beyond the start or end of the
  20125. available data - any samples that are out-of-range will be returned
  20126. as zeros.
  20127. @param numSamplesToRead the number of samples to read. If this is greater than the number
  20128. of samples that the file or stream contains. the result will be padded
  20129. with zeros
  20130. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  20131. for some of the channels that you pass in, then they should be filled with
  20132. copies of valid source channels.
  20133. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  20134. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  20135. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  20136. was false, then only the first channel would be filled with the file's contents, and
  20137. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  20138. from a stereo file, then the last 3 would all end up with copies of the same data.
  20139. @returns true if the operation succeeded, false if there was an error. Note
  20140. that reading sections of data beyond the extent of the stream isn't an
  20141. error - the reader should just return zeros for these regions
  20142. @see readMaxLevels
  20143. */
  20144. bool read (int** destSamples,
  20145. int numDestChannels,
  20146. int64 startSampleInSource,
  20147. int numSamplesToRead,
  20148. const bool fillLeftoverChannelsWithCopies);
  20149. /** Finds the highest and lowest sample levels from a section of the audio stream.
  20150. This will read a block of samples from the stream, and measure the
  20151. highest and lowest sample levels from the channels in that section, returning
  20152. these as normalised floating-point levels.
  20153. @param startSample the offset into the audio stream to start reading from. It's
  20154. ok for this to be beyond the start or end of the stream.
  20155. @param numSamples how many samples to read
  20156. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  20157. @param highestLeft on return, this is the highest absolute sample from the left channel
  20158. @param lowestRight on return, this is the lowest absolute sample from the right
  20159. channel (if there is one)
  20160. @param highestRight on return, this is the highest absolute sample from the right
  20161. channel (if there is one)
  20162. @see read
  20163. */
  20164. virtual void readMaxLevels (int64 startSample,
  20165. int64 numSamples,
  20166. float& lowestLeft,
  20167. float& highestLeft,
  20168. float& lowestRight,
  20169. float& highestRight);
  20170. /** Scans the source looking for a sample whose magnitude is in a specified range.
  20171. This will read from the source, either forwards or backwards between two sample
  20172. positions, until it finds a sample whose magnitude lies between two specified levels.
  20173. If it finds a suitable sample, it returns its position; if not, it will return -1.
  20174. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  20175. points when you're searching for a continuous range of samples
  20176. @param startSample the first sample to look at
  20177. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  20178. the search will go backwards
  20179. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  20180. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  20181. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  20182. of this many consecutive samples, all of which lie
  20183. within the target range. When it finds such a sequence,
  20184. it returns the position of the first in-range sample
  20185. it found (i.e. the earliest one if scanning forwards, the
  20186. latest one if scanning backwards)
  20187. */
  20188. int64 searchForLevel (int64 startSample,
  20189. int64 numSamplesToSearch,
  20190. const double magnitudeRangeMinimum,
  20191. const double magnitudeRangeMaximum,
  20192. const int minimumConsecutiveSamples);
  20193. /** The sample-rate of the stream. */
  20194. double sampleRate;
  20195. /** The number of bits per sample, e.g. 16, 24, 32. */
  20196. unsigned int bitsPerSample;
  20197. /** The total number of samples in the audio stream. */
  20198. int64 lengthInSamples;
  20199. /** The total number of channels in the audio stream. */
  20200. unsigned int numChannels;
  20201. /** Indicates whether the data is floating-point or fixed. */
  20202. bool usesFloatingPointData;
  20203. /** A set of metadata values that the reader has pulled out of the stream.
  20204. Exactly what these values are depends on the format, so you can
  20205. check out the format implementation code to see what kind of stuff
  20206. they understand.
  20207. */
  20208. StringPairArray metadataValues;
  20209. /** The input stream, for use by subclasses. */
  20210. InputStream* input;
  20211. /** Subclasses must implement this method to perform the low-level read operation.
  20212. Callers should use read() instead of calling this directly.
  20213. @param destSamples the array of destination buffers to fill. Some of these
  20214. pointers may be null
  20215. @param numDestChannels the number of items in the destSamples array. This
  20216. value is guaranteed not to be greater than the number of
  20217. channels that this reader object contains
  20218. @param startOffsetInDestBuffer the number of samples from the start of the
  20219. dest data at which to begin writing
  20220. @param startSampleInFile the number of samples into the source data at which
  20221. to begin reading. This value is guaranteed to be >= 0.
  20222. @param numSamples the number of samples to read
  20223. */
  20224. virtual bool readSamples (int** destSamples,
  20225. int numDestChannels,
  20226. int startOffsetInDestBuffer,
  20227. int64 startSampleInFile,
  20228. int numSamples) = 0;
  20229. juce_UseDebuggingNewOperator
  20230. private:
  20231. String formatName;
  20232. AudioFormatReader (const AudioFormatReader&);
  20233. const AudioFormatReader& operator= (const AudioFormatReader&);
  20234. };
  20235. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  20236. /********* End of inlined file: juce_AudioFormatReader.h *********/
  20237. /********* Start of inlined file: juce_AudioFormatWriter.h *********/
  20238. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  20239. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  20240. /********* Start of inlined file: juce_AudioSource.h *********/
  20241. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  20242. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  20243. /********* Start of inlined file: juce_AudioSampleBuffer.h *********/
  20244. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20245. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20246. class AudioFormatReader;
  20247. class AudioFormatWriter;
  20248. /**
  20249. A multi-channel buffer of 32-bit floating point audio samples.
  20250. */
  20251. class JUCE_API AudioSampleBuffer
  20252. {
  20253. public:
  20254. /** Creates a buffer with a specified number of channels and samples.
  20255. The contents of the buffer will initially be undefined, so use clear() to
  20256. set all the samples to zero.
  20257. The buffer will allocate its memory internally, and this will be released
  20258. when the buffer is deleted.
  20259. */
  20260. AudioSampleBuffer (const int numChannels,
  20261. const int numSamples) throw();
  20262. /** Creates a buffer using a pre-allocated block of memory.
  20263. Note that if the buffer is resized or its number of channels is changed, it
  20264. will re-allocate memory internally and copy the existing data to this new area,
  20265. so it will then stop directly addressing this memory.
  20266. @param dataToReferTo a pre-allocated array containing pointers to the data
  20267. for each channel that should be used by this buffer. The
  20268. buffer will only refer to this memory, it won't try to delete
  20269. it when the buffer is deleted or resized.
  20270. @param numChannels the number of channels to use - this must correspond to the
  20271. number of elements in the array passed in
  20272. @param numSamples the number of samples to use - this must correspond to the
  20273. size of the arrays passed in
  20274. */
  20275. AudioSampleBuffer (float** dataToReferTo,
  20276. const int numChannels,
  20277. const int numSamples) throw();
  20278. /** Copies another buffer.
  20279. This buffer will make its own copy of the other's data, unless the buffer was created
  20280. using an external data buffer, in which case boths buffers will just point to the same
  20281. shared block of data.
  20282. */
  20283. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  20284. /** Copies another buffer onto this one.
  20285. This buffer's size will be changed to that of the other buffer.
  20286. */
  20287. const AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  20288. /** Destructor.
  20289. This will free any memory allocated by the buffer.
  20290. */
  20291. virtual ~AudioSampleBuffer() throw();
  20292. /** Returns the number of channels of audio data that this buffer contains.
  20293. @see getSampleData
  20294. */
  20295. int getNumChannels() const throw() { return numChannels; }
  20296. /** Returns the number of samples allocated in each of the buffer's channels.
  20297. @see getSampleData
  20298. */
  20299. int getNumSamples() const throw() { return size; }
  20300. /** Returns a pointer one of the buffer's channels.
  20301. For speed, this doesn't check whether the channel number is out of range,
  20302. so be careful when using it!
  20303. */
  20304. float* getSampleData (const int channelNumber) const throw()
  20305. {
  20306. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20307. return channels [channelNumber];
  20308. }
  20309. /** Returns a pointer to a sample in one of the buffer's channels.
  20310. For speed, this doesn't check whether the channel and sample number
  20311. are out-of-range, so be careful when using it!
  20312. */
  20313. float* getSampleData (const int channelNumber,
  20314. const int sampleOffset) const throw()
  20315. {
  20316. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  20317. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  20318. return channels [channelNumber] + sampleOffset;
  20319. }
  20320. /** Returns an array of pointers to the channels in the buffer.
  20321. Don't modify any of the pointers that are returned, and bear in mind that
  20322. these will become invalid if the buffer is resized.
  20323. */
  20324. float** getArrayOfChannels() const throw() { return channels; }
  20325. /** Chages the buffer's size or number of channels.
  20326. This can expand or contract the buffer's length, and add or remove channels.
  20327. If keepExistingContent is true, it will try to preserve as much of the
  20328. old data as it can in the new buffer.
  20329. If clearExtraSpace is true, then any extra channels or space that is
  20330. allocated will be also be cleared. If false, then this space is left
  20331. uninitialised.
  20332. If avoidReallocating is true, then changing the buffer's size won't reduce the
  20333. amount of memory that is currently allocated (but it will still increase it if
  20334. the new size is bigger than the amount it currently has). If this is false, then
  20335. a new allocation will be done so that the buffer uses takes up the minimum amount
  20336. of memory that it needs.
  20337. */
  20338. void setSize (const int newNumChannels,
  20339. const int newNumSamples,
  20340. const bool keepExistingContent = false,
  20341. const bool clearExtraSpace = false,
  20342. const bool avoidReallocating = false) throw();
  20343. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  20344. There's also a constructor that lets you specify arrays like this, but this
  20345. lets you change the channels dynamically.
  20346. Note that if the buffer is resized or its number of channels is changed, it
  20347. will re-allocate memory internally and copy the existing data to this new area,
  20348. so it will then stop directly addressing this memory.
  20349. @param dataToReferTo a pre-allocated array containing pointers to the data
  20350. for each channel that should be used by this buffer. The
  20351. buffer will only refer to this memory, it won't try to delete
  20352. it when the buffer is deleted or resized.
  20353. @param numChannels the number of channels to use - this must correspond to the
  20354. number of elements in the array passed in
  20355. @param numSamples the number of samples to use - this must correspond to the
  20356. size of the arrays passed in
  20357. */
  20358. void setDataToReferTo (float** dataToReferTo,
  20359. const int numChannels,
  20360. const int numSamples) throw();
  20361. /** Clears all the samples in all channels. */
  20362. void clear() throw();
  20363. /** Clears a specified region of all the channels.
  20364. For speed, this doesn't check whether the channel and sample number
  20365. are in-range, so be careful!
  20366. */
  20367. void clear (const int startSample,
  20368. const int numSamples) throw();
  20369. /** Clears a specified region of just one channel.
  20370. For speed, this doesn't check whether the channel and sample number
  20371. are in-range, so be careful!
  20372. */
  20373. void clear (const int channel,
  20374. const int startSample,
  20375. const int numSamples) throw();
  20376. /** Applies a gain multiple to a region of one channel.
  20377. For speed, this doesn't check whether the channel and sample number
  20378. are in-range, so be careful!
  20379. */
  20380. void applyGain (const int channel,
  20381. const int startSample,
  20382. int numSamples,
  20383. const float gain) throw();
  20384. /** Applies a gain multiple to a region of all the channels.
  20385. For speed, this doesn't check whether the sample numbers
  20386. are in-range, so be careful!
  20387. */
  20388. void applyGain (const int startSample,
  20389. const int numSamples,
  20390. const float gain) throw();
  20391. /** Applies a range of gains to a region of a channel.
  20392. The gain that is applied to each sample will vary from
  20393. startGain on the first sample to endGain on the last Sample,
  20394. so it can be used to do basic fades.
  20395. For speed, this doesn't check whether the sample numbers
  20396. are in-range, so be careful!
  20397. */
  20398. void applyGainRamp (const int channel,
  20399. const int startSample,
  20400. int numSamples,
  20401. float startGain,
  20402. float endGain) throw();
  20403. /** Adds samples from another buffer to this one.
  20404. @param destChannel the channel within this buffer to add the samples to
  20405. @param destStartSample the start sample within this buffer's channel
  20406. @param source the source buffer to add from
  20407. @param sourceChannel the channel within the source buffer to read from
  20408. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20409. @param numSamples the number of samples to process
  20410. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  20411. added to this buffer's samples
  20412. @see copyFrom
  20413. */
  20414. void addFrom (const int destChannel,
  20415. const int destStartSample,
  20416. const AudioSampleBuffer& source,
  20417. const int sourceChannel,
  20418. const int sourceStartSample,
  20419. int numSamples,
  20420. const float gainToApplyToSource = 1.0f) throw();
  20421. /** Adds samples from an array of floats to one of the channels.
  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 gainToApplyToSource an optional gain to apply to the source samples before they are
  20427. added to this buffer's samples
  20428. @see copyFrom
  20429. */
  20430. void addFrom (const int destChannel,
  20431. const int destStartSample,
  20432. const float* source,
  20433. int numSamples,
  20434. const float gainToApplyToSource = 1.0f) throw();
  20435. /** Adds samples from an array of floats, applying a gain ramp to them.
  20436. @param destChannel the channel within this buffer to add the samples to
  20437. @param destStartSample the start sample within this buffer's channel
  20438. @param source the source data to use
  20439. @param numSamples the number of samples to process
  20440. @param startGain the gain to apply to the first sample (this is multiplied with
  20441. the source samples before they are added to this buffer)
  20442. @param endGain the gain to apply to the final sample. The gain is linearly
  20443. interpolated between the first and last samples.
  20444. */
  20445. void addFromWithRamp (const int destChannel,
  20446. const int destStartSample,
  20447. const float* source,
  20448. int numSamples,
  20449. float startGain,
  20450. float endGain) throw();
  20451. /** Copies samples from another buffer to this one.
  20452. @param destChannel the channel within this buffer to copy the samples to
  20453. @param destStartSample the start sample within this buffer's channel
  20454. @param source the source buffer to read from
  20455. @param sourceChannel the channel within the source buffer to read from
  20456. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  20457. @param numSamples the number of samples to process
  20458. @see addFrom
  20459. */
  20460. void copyFrom (const int destChannel,
  20461. const int destStartSample,
  20462. const AudioSampleBuffer& source,
  20463. const int sourceChannel,
  20464. const int sourceStartSample,
  20465. int numSamples) throw();
  20466. /** Copies samples from an array of floats into one of the channels.
  20467. @param destChannel the channel within this buffer to copy the samples to
  20468. @param destStartSample the start sample within this buffer's channel
  20469. @param source the source buffer to read from
  20470. @param numSamples the number of samples to process
  20471. @see addFrom
  20472. */
  20473. void copyFrom (const int destChannel,
  20474. const int destStartSample,
  20475. const float* source,
  20476. int numSamples) throw();
  20477. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  20478. @param destChannel the channel within this buffer to copy the samples to
  20479. @param destStartSample the start sample within this buffer's channel
  20480. @param source the source buffer to read from
  20481. @param numSamples the number of samples to process
  20482. @param gain the gain to apply
  20483. @see addFrom
  20484. */
  20485. void copyFrom (const int destChannel,
  20486. const int destStartSample,
  20487. const float* source,
  20488. int numSamples,
  20489. const float gain) throw();
  20490. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  20491. @param destChannel the channel within this buffer to copy the samples to
  20492. @param destStartSample the start sample within this buffer's channel
  20493. @param source the source buffer to read from
  20494. @param numSamples the number of samples to process
  20495. @param startGain the gain to apply to the first sample (this is multiplied with
  20496. the source samples before they are copied to this buffer)
  20497. @param endGain the gain to apply to the final sample. The gain is linearly
  20498. interpolated between the first and last samples.
  20499. @see addFrom
  20500. */
  20501. void copyFromWithRamp (const int destChannel,
  20502. const int destStartSample,
  20503. const float* source,
  20504. int numSamples,
  20505. float startGain,
  20506. float endGain) throw();
  20507. /** Finds the highest and lowest sample values in a given range.
  20508. @param channel the channel to read from
  20509. @param startSample the start sample within the channel
  20510. @param numSamples the number of samples to check
  20511. @param minVal on return, the lowest value that was found
  20512. @param maxVal on return, the highest value that was found
  20513. */
  20514. void findMinMax (const int channel,
  20515. const int startSample,
  20516. int numSamples,
  20517. float& minVal,
  20518. float& maxVal) const throw();
  20519. /** Finds the highest absolute sample value within a region of a channel.
  20520. */
  20521. float getMagnitude (const int channel,
  20522. const int startSample,
  20523. const int numSamples) const throw();
  20524. /** Finds the highest absolute sample value within a region on all channels.
  20525. */
  20526. float getMagnitude (const int startSample,
  20527. const int numSamples) const throw();
  20528. /** Returns the root mean squared level for a region of a channel.
  20529. */
  20530. float getRMSLevel (const int channel,
  20531. const int startSample,
  20532. const int numSamples) const throw();
  20533. /** Fills a section of the buffer using an AudioReader as its source.
  20534. This will convert the reader's fixed- or floating-point data to
  20535. the buffer's floating-point format, and will try to intelligently
  20536. cope with mismatches between the number of channels in the reader
  20537. and the buffer.
  20538. @see writeToAudioWriter
  20539. */
  20540. void readFromAudioReader (AudioFormatReader* reader,
  20541. const int startSample,
  20542. const int numSamples,
  20543. const int readerStartSample,
  20544. const bool useReaderLeftChan,
  20545. const bool useReaderRightChan) throw();
  20546. /** Writes a section of this buffer to an audio writer.
  20547. This saves you having to mess about with channels or floating/fixed
  20548. point conversion.
  20549. @see readFromAudioReader
  20550. */
  20551. void writeToAudioWriter (AudioFormatWriter* writer,
  20552. const int startSample,
  20553. const int numSamples) const throw();
  20554. juce_UseDebuggingNewOperator
  20555. private:
  20556. int numChannels, size, allocatedBytes;
  20557. float** channels;
  20558. HeapBlock <char> allocatedData;
  20559. float* preallocatedChannelSpace [32];
  20560. void allocateData();
  20561. void allocateChannels (float** const dataToReferTo);
  20562. };
  20563. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  20564. /********* End of inlined file: juce_AudioSampleBuffer.h *********/
  20565. /**
  20566. Used by AudioSource::getNextAudioBlock().
  20567. */
  20568. struct JUCE_API AudioSourceChannelInfo
  20569. {
  20570. /** The destination buffer to fill with audio data.
  20571. When the AudioSource::getNextAudioBlock() method is called, the active section
  20572. of this buffer should be filled with whatever output the source produces.
  20573. Only the samples specified by the startSample and numSamples members of this structure
  20574. should be affected by the call.
  20575. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  20576. method can be treated as the input if the source is performing some kind of filter operation,
  20577. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  20578. a handy way of doing this.
  20579. The number of channels in the buffer could be anything, so the AudioSource
  20580. must cope with this in whatever way is appropriate for its function.
  20581. */
  20582. AudioSampleBuffer* buffer;
  20583. /** The first sample in the buffer from which the callback is expected
  20584. to write data. */
  20585. int startSample;
  20586. /** The number of samples in the buffer which the callback is expected to
  20587. fill with data. */
  20588. int numSamples;
  20589. /** Convenient method to clear the buffer if the source is not producing any data. */
  20590. void clearActiveBufferRegion() const
  20591. {
  20592. if (buffer != 0)
  20593. buffer->clear (startSample, numSamples);
  20594. }
  20595. };
  20596. /**
  20597. Base class for objects that can produce a continuous stream of audio.
  20598. @see AudioFormatReaderSource, ResamplingAudioSource
  20599. */
  20600. class JUCE_API AudioSource
  20601. {
  20602. protected:
  20603. /** Creates an AudioSource. */
  20604. AudioSource() throw() {}
  20605. public:
  20606. /** Destructor. */
  20607. virtual ~AudioSource() {}
  20608. /** Tells the source to prepare for playing.
  20609. The source can use this opportunity to initialise anything it needs to.
  20610. Note that this method could be called more than once in succession without
  20611. a matching call to releaseResources(), so make sure your code is robust and
  20612. can handle that kind of situation.
  20613. @param samplesPerBlockExpected the number of samples that the source
  20614. will be expected to supply each time its
  20615. getNextAudioBlock() method is called. This
  20616. number may vary slightly, because it will be dependent
  20617. on audio hardware callbacks, and these aren't
  20618. guaranteed to always use a constant block size, so
  20619. the source should be able to cope with small variations.
  20620. @param sampleRate the sample rate that the output will be used at - this
  20621. is needed by sources such as tone generators.
  20622. @see releaseResources, getNextAudioBlock
  20623. */
  20624. virtual void prepareToPlay (int samplesPerBlockExpected,
  20625. double sampleRate) = 0;
  20626. /** Allows the source to release anything it no longer needs after playback has stopped.
  20627. This will be called when the source is no longer going to have its getNextAudioBlock()
  20628. method called, so it should release any spare memory, etc. that it might have
  20629. allocated during the prepareToPlay() call.
  20630. Note that there's no guarantee that prepareToPlay() will actually have been called before
  20631. releaseResources(), and it may be called more than once in succession, so make sure your
  20632. code is robust and doesn't make any assumptions about when it will be called.
  20633. @see prepareToPlay, getNextAudioBlock
  20634. */
  20635. virtual void releaseResources() = 0;
  20636. /** Called repeatedly to fetch subsequent blocks of audio data.
  20637. After calling the prepareToPlay() method, this callback will be made each
  20638. time the audio playback hardware (or whatever other destination the audio
  20639. data is going to) needs another block of data.
  20640. It will generally be called on a high-priority system thread, or possibly even
  20641. an interrupt, so be careful not to do too much work here, as that will cause
  20642. audio glitches!
  20643. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  20644. */
  20645. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  20646. };
  20647. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  20648. /********* End of inlined file: juce_AudioSource.h *********/
  20649. /**
  20650. Writes samples to an audio file stream.
  20651. A subclass that writes a specific type of audio format will be created by
  20652. an AudioFormat object.
  20653. After creating one of these with the AudioFormat::createWriterFor() method
  20654. you can call its write() method to store the samples, and then delete it.
  20655. @see AudioFormat, AudioFormatReader
  20656. */
  20657. class JUCE_API AudioFormatWriter
  20658. {
  20659. protected:
  20660. /** Creates an AudioFormatWriter object.
  20661. @param destStream the stream to write to - this will be deleted
  20662. by this object when it is no longer needed
  20663. @param formatName the description that will be returned by the getFormatName()
  20664. method
  20665. @param sampleRate the sample rate to use - the base class just stores
  20666. this value, it doesn't do anything with it
  20667. @param numberOfChannels the number of channels to write - the base class just stores
  20668. this value, it doesn't do anything with it
  20669. @param bitsPerSample the bit depth of the stream - the base class just stores
  20670. this value, it doesn't do anything with it
  20671. */
  20672. AudioFormatWriter (OutputStream* const destStream,
  20673. const String& formatName,
  20674. const double sampleRate,
  20675. const unsigned int numberOfChannels,
  20676. const unsigned int bitsPerSample);
  20677. public:
  20678. /** Destructor. */
  20679. virtual ~AudioFormatWriter();
  20680. /** Returns a description of what type of format this is.
  20681. E.g. "AIFF file"
  20682. */
  20683. const String getFormatName() const throw() { return formatName; }
  20684. /** Writes a set of samples to the audio stream.
  20685. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  20686. can use AudioSampleBuffer::writeToAudioWriter().
  20687. @param samplesToWrite an array of arrays containing the sample data for
  20688. each channel to write. This is a zero-terminated
  20689. array of arrays, and can contain a different number
  20690. of channels than the actual stream uses, and the
  20691. writer should do its best to cope with this.
  20692. If the format is fixed-point, each channel will be formatted
  20693. as an array of signed integers using the full 32-bit
  20694. range -0x80000000 to 0x7fffffff, regardless of the source's
  20695. bit-depth. If it is a floating-point format, you should treat
  20696. the arrays as arrays of floats, and just cast it to an (int**)
  20697. to pass it into the method.
  20698. @param numSamples the number of samples to write
  20699. */
  20700. virtual bool write (const int** samplesToWrite,
  20701. int numSamples) = 0;
  20702. /** Reads a section of samples from an AudioFormatReader, and writes these to
  20703. the output.
  20704. This will take care of any floating-point conversion that's required to convert
  20705. between the two formats. It won't deal with sample-rate conversion, though.
  20706. If numSamplesToRead < 0, it will write the entire length of the reader.
  20707. @returns false if it can't read or write properly during the operation
  20708. */
  20709. bool writeFromAudioReader (AudioFormatReader& reader,
  20710. int64 startSample,
  20711. int64 numSamplesToRead);
  20712. /** Reads some samples from an AudioSource, and writes these to the output.
  20713. The source must already have been initialised with the AudioSource::prepareToPlay() method
  20714. @param source the source to read from
  20715. @param numSamplesToRead total number of samples to read and write
  20716. @param samplesPerBlock the maximum number of samples to fetch from the source
  20717. @returns false if it can't read or write properly during the operation
  20718. */
  20719. bool writeFromAudioSource (AudioSource& source,
  20720. int numSamplesToRead,
  20721. const int samplesPerBlock = 2048);
  20722. /** Returns the sample rate being used. */
  20723. double getSampleRate() const throw() { return sampleRate; }
  20724. /** Returns the number of channels being written. */
  20725. int getNumChannels() const throw() { return numChannels; }
  20726. /** Returns the bit-depth of the data being written. */
  20727. int getBitsPerSample() const throw() { return bitsPerSample; }
  20728. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  20729. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  20730. juce_UseDebuggingNewOperator
  20731. protected:
  20732. /** The sample rate of the stream. */
  20733. double sampleRate;
  20734. /** The number of channels being written to the stream. */
  20735. unsigned int numChannels;
  20736. /** The bit depth of the file. */
  20737. unsigned int bitsPerSample;
  20738. /** True if it's a floating-point format, false if it's fixed-point. */
  20739. bool usesFloatingPointData;
  20740. /** The output stream for Use by subclasses. */
  20741. OutputStream* output;
  20742. private:
  20743. String formatName;
  20744. };
  20745. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  20746. /********* End of inlined file: juce_AudioFormatWriter.h *********/
  20747. /**
  20748. Subclasses of AudioFormat are used to read and write different audio
  20749. file formats.
  20750. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  20751. */
  20752. class JUCE_API AudioFormat
  20753. {
  20754. public:
  20755. /** Destructor. */
  20756. virtual ~AudioFormat();
  20757. /** Returns the name of this format.
  20758. e.g. "WAV file" or "AIFF file"
  20759. */
  20760. const String& getFormatName() const;
  20761. /** Returns all the file extensions that might apply to a file of this format.
  20762. The first item will be the one that's preferred when creating a new file.
  20763. So for a wav file this might just return ".wav"; for an AIFF file it might
  20764. return two items, ".aif" and ".aiff"
  20765. */
  20766. const StringArray& getFileExtensions() const;
  20767. /** Returns true if this the given file can be read by this format.
  20768. Subclasses shouldn't do too much work here, just check the extension or
  20769. file type. The base class implementation just checks the file's extension
  20770. against one of the ones that was registered in the constructor.
  20771. */
  20772. virtual bool canHandleFile (const File& fileToTest);
  20773. /** Returns a set of sample rates that the format can read and write. */
  20774. virtual const Array <int> getPossibleSampleRates() = 0;
  20775. /** Returns a set of bit depths that the format can read and write. */
  20776. virtual const Array <int> getPossibleBitDepths() = 0;
  20777. /** Returns true if the format can do 2-channel audio. */
  20778. virtual bool canDoStereo() = 0;
  20779. /** Returns true if the format can do 1-channel audio. */
  20780. virtual bool canDoMono() = 0;
  20781. /** Returns true if the format uses compressed data. */
  20782. virtual bool isCompressed();
  20783. /** Returns a list of different qualities that can be used when writing.
  20784. Non-compressed formats will just return an empty array, but for something
  20785. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  20786. When calling createWriterFor(), an index from this array is passed in to
  20787. tell the format which option is required.
  20788. */
  20789. virtual const StringArray getQualityOptions();
  20790. /** Tries to create an object that can read from a stream containing audio
  20791. data in this format.
  20792. The reader object that is returned can be used to read from the stream, and
  20793. should then be deleted by the caller.
  20794. @param sourceStream the stream to read from - the AudioFormatReader object
  20795. that is returned will delete this stream when it no longer
  20796. needs it.
  20797. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  20798. should delete the stream object that was passed-in. (If a valid
  20799. reader is returned, it will always be in charge of deleting the
  20800. stream, so this parameter is ignored)
  20801. @see AudioFormatReader
  20802. */
  20803. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  20804. const bool deleteStreamIfOpeningFails) = 0;
  20805. /** Tries to create an object that can write to a stream with this audio format.
  20806. The writer object that is returned can be used to write to the stream, and
  20807. should then be deleted by the caller.
  20808. If the stream can't be created for some reason (e.g. the parameters passed in
  20809. here aren't suitable), this will return 0.
  20810. @param streamToWriteTo the stream that the data will go to - this will be
  20811. deleted by the AudioFormatWriter object when it's no longer
  20812. needed. If no AudioFormatWriter can be created by this method,
  20813. the stream will NOT be deleted, so that the caller can re-use it
  20814. to try to open a different format, etc
  20815. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  20816. returned by getPossibleSampleRates()
  20817. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  20818. the choice will depend on the results of canDoMono() and
  20819. canDoStereo()
  20820. @param bitsPerSample the bits per sample to use - this must be one of the values
  20821. returned by getPossibleBitDepths()
  20822. @param metadataValues a set of metadata values that the writer should try to write
  20823. to the stream. Exactly what these are depends on the format,
  20824. and the subclass doesn't actually have to do anything with
  20825. them if it doesn't want to. Have a look at the specific format
  20826. implementation classes to see possible values that can be
  20827. used
  20828. @param qualityOptionIndex the index of one of compression qualities returned by the
  20829. getQualityOptions() method. If there aren't any quality options
  20830. for this format, just pass 0 in this parameter, as it'll be
  20831. ignored
  20832. @see AudioFormatWriter
  20833. */
  20834. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  20835. double sampleRateToUse,
  20836. unsigned int numberOfChannels,
  20837. int bitsPerSample,
  20838. const StringPairArray& metadataValues,
  20839. int qualityOptionIndex) = 0;
  20840. protected:
  20841. /** Creates an AudioFormat object.
  20842. @param formatName this sets the value that will be returned by getFormatName()
  20843. @param fileExtensions a zero-terminated list of file extensions - this is what will
  20844. be returned by getFileExtension()
  20845. */
  20846. AudioFormat (const String& formatName,
  20847. const tchar** const fileExtensions);
  20848. private:
  20849. String formatName;
  20850. StringArray fileExtensions;
  20851. };
  20852. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  20853. /********* End of inlined file: juce_AudioFormat.h *********/
  20854. /**
  20855. Reads and Writes AIFF format audio files.
  20856. @see AudioFormat
  20857. */
  20858. class JUCE_API AiffAudioFormat : public AudioFormat
  20859. {
  20860. public:
  20861. /** Creates an format object. */
  20862. AiffAudioFormat();
  20863. /** Destructor. */
  20864. ~AiffAudioFormat();
  20865. const Array <int> getPossibleSampleRates();
  20866. const Array <int> getPossibleBitDepths();
  20867. bool canDoStereo();
  20868. bool canDoMono();
  20869. #if JUCE_MAC
  20870. bool canHandleFile (const File& fileToTest);
  20871. #endif
  20872. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  20873. const bool deleteStreamIfOpeningFails);
  20874. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  20875. double sampleRateToUse,
  20876. unsigned int numberOfChannels,
  20877. int bitsPerSample,
  20878. const StringPairArray& metadataValues,
  20879. int qualityOptionIndex);
  20880. juce_UseDebuggingNewOperator
  20881. };
  20882. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  20883. /********* End of inlined file: juce_AiffAudioFormat.h *********/
  20884. #endif
  20885. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  20886. /********* Start of inlined file: juce_AudioCDBurner.h *********/
  20887. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  20888. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  20889. #if JUCE_USE_CDBURNER
  20890. /**
  20891. */
  20892. class AudioCDBurner
  20893. {
  20894. public:
  20895. /** Returns a list of available optical drives.
  20896. Use openDevice() to open one of the items from this list.
  20897. */
  20898. static const StringArray findAvailableDevices();
  20899. /** Tries to open one of the optical drives.
  20900. The deviceIndex is an index into the array returned by findAvailableDevices().
  20901. */
  20902. static AudioCDBurner* openDevice (const int deviceIndex);
  20903. /** Destructor. */
  20904. ~AudioCDBurner();
  20905. /** Returns true if there's a writable disk in the drive.
  20906. */
  20907. bool isDiskPresent() const;
  20908. /** Returns the number of free blocks on the disk.
  20909. There are 75 blocks per second, at 44100Hz.
  20910. */
  20911. int getNumAvailableAudioBlocks() const;
  20912. /** Adds a track to be written.
  20913. The source passed-in here will be kept by this object, and it will
  20914. be used and deleted at some point in the future, either during the
  20915. burn() method or when this AudioCDBurner object is deleted. Your caller
  20916. method shouldn't keep a reference to it or use it again after passing
  20917. it in here.
  20918. */
  20919. bool addAudioTrack (AudioSource* source, int numSamples);
  20920. /**
  20921. Return true to cancel the current burn operation
  20922. */
  20923. class BurnProgressListener
  20924. {
  20925. public:
  20926. BurnProgressListener() throw() {}
  20927. virtual ~BurnProgressListener() {}
  20928. /** Called at intervals to report on the progress of the AudioCDBurner.
  20929. To cancel the burn, return true from this.
  20930. */
  20931. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  20932. };
  20933. const String burn (BurnProgressListener* listener,
  20934. const bool ejectDiscAfterwards,
  20935. const bool peformFakeBurnForTesting);
  20936. juce_UseDebuggingNewOperator
  20937. private:
  20938. AudioCDBurner (const int deviceIndex);
  20939. void* internal;
  20940. };
  20941. #endif
  20942. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  20943. /********* End of inlined file: juce_AudioCDBurner.h *********/
  20944. #endif
  20945. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  20946. /********* Start of inlined file: juce_AudioCDReader.h *********/
  20947. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  20948. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  20949. #if JUCE_USE_CDREADER
  20950. #if JUCE_MAC
  20951. #endif
  20952. /**
  20953. A type of AudioFormatReader that reads from an audio CD.
  20954. One of these can be used to read a CD as if it's one big audio stream. Use the
  20955. getPositionOfTrackStart() method to find where the individual tracks are
  20956. within the stream.
  20957. @see AudioFormatReader
  20958. */
  20959. class JUCE_API AudioCDReader : public AudioFormatReader
  20960. {
  20961. public:
  20962. /** Returns a list of names of Audio CDs currently available for reading.
  20963. If there's a CD drive but no CD in it, this might return an empty list, or
  20964. possibly a device that can be opened but which has no tracks, depending
  20965. on the platform.
  20966. @see createReaderForCD
  20967. */
  20968. static const StringArray getAvailableCDNames();
  20969. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  20970. @param index the index of one of the available CDs - use getAvailableCDNames()
  20971. to find out how many there are.
  20972. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  20973. caller will be responsible for deleting the object returned.
  20974. */
  20975. static AudioCDReader* createReaderForCD (const int index);
  20976. /** Destructor. */
  20977. ~AudioCDReader();
  20978. /** Implementation of the AudioFormatReader method. */
  20979. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  20980. int64 startSampleInFile, int numSamples);
  20981. /** Checks whether the CD has been removed from the drive.
  20982. */
  20983. bool isCDStillPresent() const;
  20984. /** Returns the total number of tracks (audio + data).
  20985. */
  20986. int getNumTracks() const;
  20987. /** Finds the sample offset of the start of a track.
  20988. @param trackNum the track number, where 0 is the first track.
  20989. */
  20990. int getPositionOfTrackStart (int trackNum) const;
  20991. /** Returns true if a given track is an audio track.
  20992. @param trackNum the track number, where 0 is the first track.
  20993. */
  20994. bool isTrackAudio (int trackNum) const;
  20995. /** Refreshes the object's table of contents.
  20996. If the disc has been ejected and a different one put in since this
  20997. object was created, this will cause it to update its idea of how many tracks
  20998. there are, etc.
  20999. */
  21000. void refreshTrackLengths();
  21001. /** Enables scanning for indexes within tracks.
  21002. @see getLastIndex
  21003. */
  21004. void enableIndexScanning (bool enabled);
  21005. /** Returns the index number found during the last read() call.
  21006. Index scanning is turned off by default - turn it on with enableIndexScanning().
  21007. Then when the read() method is called, if it comes across an index within that
  21008. block, the index number is stored and returned by this method.
  21009. Some devices might not support indexes, of course.
  21010. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  21011. @see enableIndexScanning
  21012. */
  21013. int getLastIndex() const;
  21014. /** Scans a track to find the position of any indexes within it.
  21015. @param trackNumber the track to look in, where 0 is the first track on the disc
  21016. @returns an array of sample positions of any index points found (not including
  21017. the index that marks the start of the track)
  21018. */
  21019. const Array <int> findIndexesInTrack (const int trackNumber);
  21020. /** Returns the CDDB id number for the CD.
  21021. It's not a great way of identifying a disc, but it's traditional.
  21022. */
  21023. int getCDDBId();
  21024. /** Tries to eject the disk.
  21025. Of course this might not be possible, if some other process is using it.
  21026. */
  21027. void ejectDisk();
  21028. juce_UseDebuggingNewOperator
  21029. private:
  21030. #if JUCE_MAC
  21031. File volumeDir;
  21032. OwnedArray<File> tracks;
  21033. Array <int> trackStartSamples;
  21034. int currentReaderTrack;
  21035. ScopedPointer <AudioFormatReader> reader;
  21036. AudioCDReader (const File& volume);
  21037. public:
  21038. static int compareElements (const File* const, const File* const) throw();
  21039. private:
  21040. #elif JUCE_WINDOWS
  21041. int numTracks;
  21042. int trackStarts[100];
  21043. bool audioTracks [100];
  21044. void* handle;
  21045. bool indexingEnabled;
  21046. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  21047. MemoryBlock buffer;
  21048. AudioCDReader (void* handle);
  21049. int getIndexAt (int samplePos);
  21050. #elif JUCE_LINUX
  21051. AudioCDReader();
  21052. #endif
  21053. AudioCDReader (const AudioCDReader&);
  21054. const AudioCDReader& operator= (const AudioCDReader&);
  21055. };
  21056. #endif
  21057. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  21058. /********* End of inlined file: juce_AudioCDReader.h *********/
  21059. #endif
  21060. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  21061. #endif
  21062. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  21063. /********* Start of inlined file: juce_AudioFormatManager.h *********/
  21064. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  21065. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  21066. /**
  21067. A class for keeping a list of available audio formats, and for deciding which
  21068. one to use to open a given file.
  21069. You can either use this class as a singleton object, or create instances of it
  21070. yourself. Once created, use its registerFormat() method to tell it which
  21071. formats it should use.
  21072. @see AudioFormat
  21073. */
  21074. class JUCE_API AudioFormatManager
  21075. {
  21076. public:
  21077. /** Creates an empty format manager.
  21078. Before it'll be any use, you'll need to call registerFormat() with all the
  21079. formats you want it to be able to recognise.
  21080. */
  21081. AudioFormatManager();
  21082. /** Destructor. */
  21083. ~AudioFormatManager();
  21084. juce_DeclareSingleton (AudioFormatManager, false);
  21085. /** Adds a format to the manager's list of available file types.
  21086. The object passed-in will be deleted by this object, so don't keep a pointer
  21087. to it!
  21088. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  21089. return this one when called.
  21090. */
  21091. void registerFormat (AudioFormat* newFormat,
  21092. const bool makeThisTheDefaultFormat);
  21093. /** Handy method to make it easy to register the formats that come with Juce.
  21094. Currently, this will add WAV and AIFF to the list.
  21095. */
  21096. void registerBasicFormats();
  21097. /** Clears the list of known formats. */
  21098. void clearFormats();
  21099. /** Returns the number of currently registered file formats. */
  21100. int getNumKnownFormats() const;
  21101. /** Returns one of the registered file formats. */
  21102. AudioFormat* getKnownFormat (const int index) const;
  21103. /** Looks for which of the known formats is listed as being for a given file
  21104. extension.
  21105. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  21106. */
  21107. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  21108. /** Returns the format which has been set as the default one.
  21109. You can set a format as being the default when it is registered. It's useful
  21110. when you want to write to a file, because the best format may change between
  21111. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  21112. If none has been set as the default, this method will just return the first
  21113. one in the list.
  21114. */
  21115. AudioFormat* getDefaultFormat() const;
  21116. /** Returns a set of wildcards for file-matching that contains the extensions for
  21117. all known formats.
  21118. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  21119. */
  21120. const String getWildcardForAllFormats() const;
  21121. /** Searches through the known formats to try to create a suitable reader for
  21122. this file.
  21123. If none of the registered formats can open the file, it'll return 0. If it
  21124. returns a reader, it's the caller's responsibility to delete the reader.
  21125. */
  21126. AudioFormatReader* createReaderFor (const File& audioFile);
  21127. /** Searches through the known formats to try to create a suitable reader for
  21128. this stream.
  21129. The stream object that is passed-in will be deleted by this method or by the
  21130. reader that is returned, so the caller should not keep any references to it.
  21131. The stream that is passed-in must be capable of being repositioned so
  21132. that all the formats can have a go at opening it.
  21133. If none of the registered formats can open the stream, it'll return 0. If it
  21134. returns a reader, it's the caller's responsibility to delete the reader.
  21135. */
  21136. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  21137. juce_UseDebuggingNewOperator
  21138. private:
  21139. VoidArray knownFormats;
  21140. int defaultFormatIndex;
  21141. };
  21142. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  21143. /********* End of inlined file: juce_AudioFormatManager.h *********/
  21144. #endif
  21145. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21146. #endif
  21147. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21148. #endif
  21149. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  21150. /********* Start of inlined file: juce_AudioSubsectionReader.h *********/
  21151. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  21152. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  21153. /**
  21154. This class is used to wrap an AudioFormatReader and only read from a
  21155. subsection of the file.
  21156. So if you have a reader which can read a 1000 sample file, you could wrap it
  21157. in one of these to only access, e.g. samples 100 to 200, and any samples
  21158. outside that will come back as 0. Accessing sample 0 from this reader will
  21159. actually read the first sample from the other's subsection, which might
  21160. be at a non-zero position.
  21161. @see AudioFormatReader
  21162. */
  21163. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  21164. {
  21165. public:
  21166. /** Creates a AudioSubsectionReader for a given data source.
  21167. @param sourceReader the source reader from which we'll be taking data
  21168. @param subsectionStartSample the sample within the source reader which will be
  21169. mapped onto sample 0 for this reader.
  21170. @param subsectionLength the number of samples from the source that will
  21171. make up the subsection. If this reader is asked for
  21172. any samples beyond this region, it will return zero.
  21173. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  21174. this object is deleted.
  21175. */
  21176. AudioSubsectionReader (AudioFormatReader* const sourceReader,
  21177. const int64 subsectionStartSample,
  21178. const int64 subsectionLength,
  21179. const bool deleteSourceWhenDeleted);
  21180. /** Destructor. */
  21181. ~AudioSubsectionReader();
  21182. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  21183. int64 startSampleInFile, int numSamples);
  21184. void readMaxLevels (int64 startSample,
  21185. int64 numSamples,
  21186. float& lowestLeft,
  21187. float& highestLeft,
  21188. float& lowestRight,
  21189. float& highestRight);
  21190. juce_UseDebuggingNewOperator
  21191. private:
  21192. AudioFormatReader* const source;
  21193. int64 startSample, length;
  21194. const bool deleteSourceWhenDeleted;
  21195. AudioSubsectionReader (const AudioSubsectionReader&);
  21196. const AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  21197. };
  21198. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  21199. /********* End of inlined file: juce_AudioSubsectionReader.h *********/
  21200. #endif
  21201. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  21202. /********* Start of inlined file: juce_AudioThumbnail.h *********/
  21203. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  21204. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  21205. class AudioThumbnailCache;
  21206. /**
  21207. Makes it easy to quickly draw scaled views of the waveform shape of an
  21208. audio file.
  21209. To use this class, just create an AudioThumbNail class for the file you want
  21210. to draw, call setSource to tell it which file or resource to use, then call
  21211. drawChannel() to draw it.
  21212. The class will asynchronously scan the wavefile to create its scaled-down view,
  21213. so you should make your UI repaint itself as this data comes in. To do this, the
  21214. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  21215. listeners should repaint themselves.
  21216. The thumbnail stores an internal low-res version of the wave data, and this can
  21217. be loaded and saved to avoid having to scan the file again.
  21218. @see AudioThumbnailCache
  21219. */
  21220. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  21221. public TimeSliceClient,
  21222. private Timer
  21223. {
  21224. public:
  21225. /** Creates an audio thumbnail.
  21226. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  21227. of the audio data, this is the scale at which it should be done. (This
  21228. number is the number of original samples that will be averaged for each
  21229. low-res sample)
  21230. @param formatManagerToUse the audio format manager that is used to open the file
  21231. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  21232. thread and storage that is used to by the thumbnail, and the cache
  21233. object can be shared between multiple thumbnails
  21234. */
  21235. AudioThumbnail (const int sourceSamplesPerThumbnailSample,
  21236. AudioFormatManager& formatManagerToUse,
  21237. AudioThumbnailCache& cacheToUse);
  21238. /** Destructor. */
  21239. ~AudioThumbnail();
  21240. /** Specifies the file or stream that contains the audio file.
  21241. For a file, just call
  21242. @code
  21243. setSource (new FileInputSource (file))
  21244. @endcode
  21245. You can pass a zero in here to clear the thumbnail.
  21246. The source that is passed in will be deleted by this object when it is no
  21247. longer needed
  21248. */
  21249. void setSource (InputSource* const newSource);
  21250. /** Reloads the low res thumbnail data from an input stream.
  21251. The thumb will automatically attempt to reload itself from its
  21252. AudioThumbnailCache.
  21253. */
  21254. void loadFrom (InputStream& input);
  21255. /** Saves the low res thumbnail data to an output stream.
  21256. The thumb will automatically attempt to save itself to its
  21257. AudioThumbnailCache after it finishes scanning the wave file.
  21258. */
  21259. void saveTo (OutputStream& output) const;
  21260. /** Returns the number of channels in the file.
  21261. */
  21262. int getNumChannels() const throw();
  21263. /** Returns the length of the audio file, in seconds.
  21264. */
  21265. double getTotalLength() const throw();
  21266. /** Renders the waveform shape for a channel.
  21267. The waveform will be drawn within the specified rectangle, where startTime
  21268. and endTime specify the times within the audio file that should be positioned
  21269. at the left and right edges of the rectangle.
  21270. The waveform will be scaled vertically so that a full-volume sample will fill
  21271. the rectangle vertically, but you can also specify an extra vertical scale factor
  21272. with the verticalZoomFactor parameter.
  21273. */
  21274. void drawChannel (Graphics& g,
  21275. int x, int y, int w, int h,
  21276. double startTimeSeconds,
  21277. double endTimeSeconds,
  21278. int channelNum,
  21279. const float verticalZoomFactor);
  21280. /** Returns true if the low res preview is fully generated.
  21281. */
  21282. bool isFullyLoaded() const throw();
  21283. /** @internal */
  21284. bool useTimeSlice();
  21285. /** @internal */
  21286. void timerCallback();
  21287. juce_UseDebuggingNewOperator
  21288. private:
  21289. AudioFormatManager& formatManagerToUse;
  21290. AudioThumbnailCache& cache;
  21291. ScopedPointer <InputSource> source;
  21292. CriticalSection readerLock;
  21293. ScopedPointer <AudioFormatReader> reader;
  21294. MemoryBlock data, cachedLevels;
  21295. int orginalSamplesPerThumbnailSample;
  21296. int numChannelsCached, numSamplesCached;
  21297. double cachedStart, cachedTimePerPixel;
  21298. bool cacheNeedsRefilling;
  21299. void clear();
  21300. AudioFormatReader* createReader() const;
  21301. void generateSection (AudioFormatReader& reader,
  21302. int64 startSample,
  21303. int numSamples);
  21304. char* getChannelData (int channel) const;
  21305. void refillCache (const int numSamples,
  21306. double startTime,
  21307. const double timePerPixel);
  21308. friend class AudioThumbnailCache;
  21309. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  21310. bool initialiseFromAudioFile (AudioFormatReader& reader);
  21311. // returns true if more needs to be read
  21312. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  21313. };
  21314. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  21315. /********* End of inlined file: juce_AudioThumbnail.h *********/
  21316. #endif
  21317. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  21318. /********* Start of inlined file: juce_AudioThumbnailCache.h *********/
  21319. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  21320. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  21321. struct ThumbnailCacheEntry;
  21322. /**
  21323. An instance of this class is used to manage multiple AudioThumbnail objects.
  21324. The cache runs a single background thread that is shared by all the thumbnails
  21325. that need it, and it maintains a set of low-res previews in memory, to avoid
  21326. having to re-scan audio files too often.
  21327. @see AudioThumbnail
  21328. */
  21329. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  21330. {
  21331. public:
  21332. /** Creates a cache object.
  21333. The maxNumThumbsToStore parameter lets you specify how many previews should
  21334. be kept in memory at once.
  21335. */
  21336. AudioThumbnailCache (const int maxNumThumbsToStore);
  21337. /** Destructor. */
  21338. ~AudioThumbnailCache();
  21339. /** Clears out any stored thumbnails.
  21340. */
  21341. void clear();
  21342. /** Reloads the specified thumb if this cache contains the appropriate stored
  21343. data.
  21344. This is called automatically by the AudioThumbnail class, so you shouldn't
  21345. normally need to call it directly.
  21346. */
  21347. bool loadThumb (AudioThumbnail& thumb, const int64 hashCode);
  21348. /** Stores the cachable data from the specified thumb in this cache.
  21349. This is called automatically by the AudioThumbnail class, so you shouldn't
  21350. normally need to call it directly.
  21351. */
  21352. void storeThumb (const AudioThumbnail& thumb, const int64 hashCode);
  21353. juce_UseDebuggingNewOperator
  21354. private:
  21355. OwnedArray <ThumbnailCacheEntry> thumbs;
  21356. int maxNumThumbsToStore;
  21357. friend class AudioThumbnail;
  21358. void addThumbnail (AudioThumbnail* const thumb);
  21359. void removeThumbnail (AudioThumbnail* const thumb);
  21360. };
  21361. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  21362. /********* End of inlined file: juce_AudioThumbnailCache.h *********/
  21363. #endif
  21364. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  21365. /********* Start of inlined file: juce_FlacAudioFormat.h *********/
  21366. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  21367. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  21368. #if JUCE_USE_FLAC || defined (DOXYGEN)
  21369. /**
  21370. Reads and writes the lossless-compression FLAC audio format.
  21371. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  21372. and make sure your include search path and library search path are set up to find
  21373. the FLAC header files and static libraries.
  21374. @see AudioFormat
  21375. */
  21376. class JUCE_API FlacAudioFormat : public AudioFormat
  21377. {
  21378. public:
  21379. FlacAudioFormat();
  21380. ~FlacAudioFormat();
  21381. const Array <int> getPossibleSampleRates();
  21382. const Array <int> getPossibleBitDepths();
  21383. bool canDoStereo();
  21384. bool canDoMono();
  21385. bool isCompressed();
  21386. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21387. const bool deleteStreamIfOpeningFails);
  21388. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21389. double sampleRateToUse,
  21390. unsigned int numberOfChannels,
  21391. int bitsPerSample,
  21392. const StringPairArray& metadataValues,
  21393. int qualityOptionIndex);
  21394. juce_UseDebuggingNewOperator
  21395. };
  21396. #endif
  21397. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  21398. /********* End of inlined file: juce_FlacAudioFormat.h *********/
  21399. #endif
  21400. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  21401. /********* Start of inlined file: juce_OggVorbisAudioFormat.h *********/
  21402. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  21403. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  21404. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  21405. /**
  21406. Reads and writes the Ogg-Vorbis audio format.
  21407. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  21408. and make sure your include search path and library search path are set up to find
  21409. the Vorbis and Ogg header files and static libraries.
  21410. @see AudioFormat,
  21411. */
  21412. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  21413. {
  21414. public:
  21415. OggVorbisAudioFormat();
  21416. ~OggVorbisAudioFormat();
  21417. const Array <int> getPossibleSampleRates();
  21418. const Array <int> getPossibleBitDepths();
  21419. bool canDoStereo();
  21420. bool canDoMono();
  21421. bool isCompressed();
  21422. const StringArray getQualityOptions();
  21423. /** Tries to estimate the quality level of an ogg file based on its size.
  21424. If it can't read the file for some reason, this will just return 1 (medium quality),
  21425. otherwise it will return the approximate quality setting that would have been used
  21426. to create the file.
  21427. @see getQualityOptions
  21428. */
  21429. int estimateOggFileQuality (const File& source);
  21430. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21431. const bool deleteStreamIfOpeningFails);
  21432. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21433. double sampleRateToUse,
  21434. unsigned int numberOfChannels,
  21435. int bitsPerSample,
  21436. const StringPairArray& metadataValues,
  21437. int qualityOptionIndex);
  21438. juce_UseDebuggingNewOperator
  21439. };
  21440. #endif
  21441. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  21442. /********* End of inlined file: juce_OggVorbisAudioFormat.h *********/
  21443. #endif
  21444. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  21445. /********* Start of inlined file: juce_QuickTimeAudioFormat.h *********/
  21446. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  21447. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  21448. #if JUCE_QUICKTIME
  21449. /**
  21450. Uses QuickTime to read the audio track a movie or media file.
  21451. As well as QuickTime movies, this should also manage to open other audio
  21452. files that quicktime can understand, like mp3, m4a, etc.
  21453. @see AudioFormat
  21454. */
  21455. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  21456. {
  21457. public:
  21458. /** Creates a format object. */
  21459. QuickTimeAudioFormat();
  21460. /** Destructor. */
  21461. ~QuickTimeAudioFormat();
  21462. const Array <int> getPossibleSampleRates();
  21463. const Array <int> getPossibleBitDepths();
  21464. bool canDoStereo();
  21465. bool canDoMono();
  21466. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21467. const bool deleteStreamIfOpeningFails);
  21468. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21469. double sampleRateToUse,
  21470. unsigned int numberOfChannels,
  21471. int bitsPerSample,
  21472. const StringPairArray& metadataValues,
  21473. int qualityOptionIndex);
  21474. juce_UseDebuggingNewOperator
  21475. };
  21476. #endif
  21477. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  21478. /********* End of inlined file: juce_QuickTimeAudioFormat.h *********/
  21479. #endif
  21480. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  21481. /********* Start of inlined file: juce_WavAudioFormat.h *********/
  21482. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  21483. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  21484. /**
  21485. Reads and Writes WAV format audio files.
  21486. @see AudioFormat
  21487. */
  21488. class JUCE_API WavAudioFormat : public AudioFormat
  21489. {
  21490. public:
  21491. /** Creates a format object. */
  21492. WavAudioFormat();
  21493. /** Destructor. */
  21494. ~WavAudioFormat();
  21495. /** Metadata property name used by wav readers and writers for adding
  21496. a BWAV chunk to the file.
  21497. @see AudioFormatReader::metadataValues, createWriterFor
  21498. */
  21499. static const tchar* const bwavDescription;
  21500. /** Metadata property name used by wav readers and writers for adding
  21501. a BWAV chunk to the file.
  21502. @see AudioFormatReader::metadataValues, createWriterFor
  21503. */
  21504. static const tchar* const bwavOriginator;
  21505. /** Metadata property name used by wav readers and writers for adding
  21506. a BWAV chunk to the file.
  21507. @see AudioFormatReader::metadataValues, createWriterFor
  21508. */
  21509. static const tchar* const bwavOriginatorRef;
  21510. /** Metadata property name used by wav readers and writers for adding
  21511. a BWAV chunk to the file.
  21512. Date format is: yyyy-mm-dd
  21513. @see AudioFormatReader::metadataValues, createWriterFor
  21514. */
  21515. static const tchar* const bwavOriginationDate;
  21516. /** Metadata property name used by wav readers and writers for adding
  21517. a BWAV chunk to the file.
  21518. Time format is: hh-mm-ss
  21519. @see AudioFormatReader::metadataValues, createWriterFor
  21520. */
  21521. static const tchar* const bwavOriginationTime;
  21522. /** Metadata property name used by wav readers and writers for adding
  21523. a BWAV chunk to the file.
  21524. This is the number of samples from the start of an edit that the
  21525. file is supposed to begin at. Seems like an obvious mistake to
  21526. only allow a file to occur in an edit once, but that's the way
  21527. it is..
  21528. @see AudioFormatReader::metadataValues, createWriterFor
  21529. */
  21530. static const tchar* const bwavTimeReference;
  21531. /** Metadata property name used by wav readers and writers for adding
  21532. a BWAV chunk to the file.
  21533. This is a
  21534. @see AudioFormatReader::metadataValues, createWriterFor
  21535. */
  21536. static const tchar* const bwavCodingHistory;
  21537. /** Utility function to fill out the appropriate metadata for a BWAV file.
  21538. This just makes it easier than using the property names directly, and it
  21539. fills out the time and date in the right format.
  21540. */
  21541. static const StringPairArray createBWAVMetadata (const String& description,
  21542. const String& originator,
  21543. const String& originatorRef,
  21544. const Time& dateAndTime,
  21545. const int64 timeReferenceSamples,
  21546. const String& codingHistory);
  21547. const Array <int> getPossibleSampleRates();
  21548. const Array <int> getPossibleBitDepths();
  21549. bool canDoStereo();
  21550. bool canDoMono();
  21551. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  21552. const bool deleteStreamIfOpeningFails);
  21553. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  21554. double sampleRateToUse,
  21555. unsigned int numberOfChannels,
  21556. int bitsPerSample,
  21557. const StringPairArray& metadataValues,
  21558. int qualityOptionIndex);
  21559. /** Utility function to replace the metadata in a wav file with a new set of values.
  21560. If possible, this cheats by overwriting just the metadata region of the file, rather
  21561. than by copying the whole file again.
  21562. */
  21563. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  21564. juce_UseDebuggingNewOperator
  21565. };
  21566. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  21567. /********* End of inlined file: juce_WavAudioFormat.h *********/
  21568. #endif
  21569. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  21570. /********* Start of inlined file: juce_AudioFormatReaderSource.h *********/
  21571. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  21572. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  21573. /********* Start of inlined file: juce_PositionableAudioSource.h *********/
  21574. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  21575. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  21576. /**
  21577. A type of AudioSource which can be repositioned.
  21578. The basic AudioSource just streams continuously with no idea of a current
  21579. time or length, so the PositionableAudioSource is used for a finite stream
  21580. that has a current read position.
  21581. @see AudioSource, AudioTransportSource
  21582. */
  21583. class JUCE_API PositionableAudioSource : public AudioSource
  21584. {
  21585. protected:
  21586. /** Creates the PositionableAudioSource. */
  21587. PositionableAudioSource() throw() {}
  21588. public:
  21589. /** Destructor */
  21590. ~PositionableAudioSource() {}
  21591. /** Tells the stream to move to a new position.
  21592. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  21593. should return samples from this position.
  21594. Note that this may be called on a different thread to getNextAudioBlock(),
  21595. so the subclass should make sure it's synchronised.
  21596. */
  21597. virtual void setNextReadPosition (int newPosition) = 0;
  21598. /** Returns the position from which the next block will be returned.
  21599. @see setNextReadPosition
  21600. */
  21601. virtual int getNextReadPosition() const = 0;
  21602. /** Returns the total length of the stream (in samples). */
  21603. virtual int getTotalLength() const = 0;
  21604. /** Returns true if this source is actually playing in a loop. */
  21605. virtual bool isLooping() const = 0;
  21606. };
  21607. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  21608. /********* End of inlined file: juce_PositionableAudioSource.h *********/
  21609. /**
  21610. A type of AudioSource that will read from an AudioFormatReader.
  21611. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  21612. */
  21613. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  21614. {
  21615. public:
  21616. /** Creates an AudioFormatReaderSource for a given reader.
  21617. @param sourceReader the reader to use as the data source
  21618. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  21619. when this object is deleted; if false it will be
  21620. left up to the caller to manage its lifetime
  21621. */
  21622. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  21623. const bool deleteReaderWhenThisIsDeleted);
  21624. /** Destructor. */
  21625. ~AudioFormatReaderSource();
  21626. /** Toggles loop-mode.
  21627. If set to true, it will continuously loop the input source. If false,
  21628. it will just emit silence after the source has finished.
  21629. @see isLooping
  21630. */
  21631. void setLooping (const bool shouldLoop) throw();
  21632. /** Returns whether loop-mode is turned on or not. */
  21633. bool isLooping() const { return looping; }
  21634. /** Returns the reader that's being used. */
  21635. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  21636. /** Implementation of the AudioSource method. */
  21637. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  21638. /** Implementation of the AudioSource method. */
  21639. void releaseResources();
  21640. /** Implementation of the AudioSource method. */
  21641. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  21642. /** Implements the PositionableAudioSource method. */
  21643. void setNextReadPosition (int newPosition);
  21644. /** Implements the PositionableAudioSource method. */
  21645. int getNextReadPosition() const;
  21646. /** Implements the PositionableAudioSource method. */
  21647. int getTotalLength() const;
  21648. juce_UseDebuggingNewOperator
  21649. private:
  21650. AudioFormatReader* reader;
  21651. bool deleteReader;
  21652. int volatile nextPlayPos;
  21653. bool volatile looping;
  21654. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  21655. AudioFormatReaderSource (const AudioFormatReaderSource&);
  21656. const AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  21657. };
  21658. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  21659. /********* End of inlined file: juce_AudioFormatReaderSource.h *********/
  21660. #endif
  21661. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  21662. #endif
  21663. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  21664. /********* Start of inlined file: juce_AudioSourcePlayer.h *********/
  21665. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  21666. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  21667. /********* Start of inlined file: juce_AudioIODevice.h *********/
  21668. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21669. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21670. class AudioIODevice;
  21671. /**
  21672. One of these is passed to an AudioIODevice object to stream the audio data
  21673. in and out.
  21674. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  21675. method on its own high-priority audio thread, when it needs to send or receive
  21676. the next block of data.
  21677. @see AudioIODevice, AudioDeviceManager
  21678. */
  21679. class JUCE_API AudioIODeviceCallback
  21680. {
  21681. public:
  21682. /** Destructor. */
  21683. virtual ~AudioIODeviceCallback() {}
  21684. /** Processes a block of incoming and outgoing audio data.
  21685. The subclass's implementation should use the incoming audio for whatever
  21686. purposes it needs to, and must fill all the output channels with the next
  21687. block of output data before returning.
  21688. The channel data is arranged with the same array indices as the channel name
  21689. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  21690. that aren't specified in AudioIODevice::open() will have a null pointer for their
  21691. associated channel, so remember to check for this.
  21692. @param inputChannelData a set of arrays containing the audio data for each
  21693. incoming channel - this data is valid until the function
  21694. returns. There will be one channel of data for each input
  21695. channel that was enabled when the audio device was opened
  21696. (see AudioIODevice::open())
  21697. @param numInputChannels the number of pointers to channel data in the
  21698. inputChannelData array.
  21699. @param outputChannelData a set of arrays which need to be filled with the data
  21700. that should be sent to each outgoing channel of the device.
  21701. There will be one channel of data for each output channel
  21702. that was enabled when the audio device was opened (see
  21703. AudioIODevice::open())
  21704. The initial contents of the array is undefined, so the
  21705. callback function must fill all the channels with zeros if
  21706. its output is silence. Failing to do this could cause quite
  21707. an unpleasant noise!
  21708. @param numOutputChannels the number of pointers to channel data in the
  21709. outputChannelData array.
  21710. @param numSamples the number of samples in each channel of the input and
  21711. output arrays. The number of samples will depend on the
  21712. audio device's buffer size and will usually remain constant,
  21713. although this isn't guaranteed, so make sure your code can
  21714. cope with reasonable changes in the buffer size from one
  21715. callback to the next.
  21716. */
  21717. virtual void audioDeviceIOCallback (const float** inputChannelData,
  21718. int numInputChannels,
  21719. float** outputChannelData,
  21720. int numOutputChannels,
  21721. int numSamples) = 0;
  21722. /** Called to indicate that the device is about to start calling back.
  21723. This will be called just before the audio callbacks begin, either when this
  21724. callback has just been added to an audio device, or after the device has been
  21725. restarted because of a sample-rate or block-size change.
  21726. You can use this opportunity to find out the sample rate and block size
  21727. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  21728. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  21729. @param device the audio IO device that will be used to drive the callback.
  21730. Note that if you're going to store this this pointer, it is
  21731. only valid until the next time that audioDeviceStopped is called.
  21732. */
  21733. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  21734. /** Called to indicate that the device has stopped.
  21735. */
  21736. virtual void audioDeviceStopped() = 0;
  21737. };
  21738. /**
  21739. Base class for an audio device with synchronised input and output channels.
  21740. Subclasses of this are used to implement different protocols such as DirectSound,
  21741. ASIO, CoreAudio, etc.
  21742. To create one of these, you'll need to use the AudioIODeviceType class - see the
  21743. documentation for that class for more info.
  21744. For an easier way of managing audio devices and their settings, have a look at the
  21745. AudioDeviceManager class.
  21746. @see AudioIODeviceType, AudioDeviceManager
  21747. */
  21748. class JUCE_API AudioIODevice
  21749. {
  21750. public:
  21751. /** Destructor. */
  21752. virtual ~AudioIODevice();
  21753. /** Returns the device's name, (as set in the constructor). */
  21754. const String& getName() const throw() { return name; }
  21755. /** Returns the type of the device.
  21756. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  21757. */
  21758. const String& getTypeName() const throw() { return typeName; }
  21759. /** Returns the names of all the available output channels on this device.
  21760. To find out which of these are currently in use, call getActiveOutputChannels().
  21761. */
  21762. virtual const StringArray getOutputChannelNames() = 0;
  21763. /** Returns the names of all the available input channels on this device.
  21764. To find out which of these are currently in use, call getActiveInputChannels().
  21765. */
  21766. virtual const StringArray getInputChannelNames() = 0;
  21767. /** Returns the number of sample-rates this device supports.
  21768. To find out which rates are available on this device, use this method to
  21769. find out how many there are, and getSampleRate() to get the rates.
  21770. @see getSampleRate
  21771. */
  21772. virtual int getNumSampleRates() = 0;
  21773. /** Returns one of the sample-rates this device supports.
  21774. To find out which rates are available on this device, use getNumSampleRates() to
  21775. find out how many there are, and getSampleRate() to get the individual rates.
  21776. The sample rate is set by the open() method.
  21777. (Note that for DirectSound some rates might not work, depending on combinations
  21778. of i/o channels that are being opened).
  21779. @see getNumSampleRates
  21780. */
  21781. virtual double getSampleRate (int index) = 0;
  21782. /** Returns the number of sizes of buffer that are available.
  21783. @see getBufferSizeSamples, getDefaultBufferSize
  21784. */
  21785. virtual int getNumBufferSizesAvailable() = 0;
  21786. /** Returns one of the possible buffer-sizes.
  21787. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  21788. @returns a number of samples
  21789. @see getNumBufferSizesAvailable, getDefaultBufferSize
  21790. */
  21791. virtual int getBufferSizeSamples (int index) = 0;
  21792. /** Returns the default buffer-size to use.
  21793. @returns a number of samples
  21794. @see getNumBufferSizesAvailable, getBufferSizeSamples
  21795. */
  21796. virtual int getDefaultBufferSize() = 0;
  21797. /** Tries to open the device ready to play.
  21798. @param inputChannels a BitArray in which a set bit indicates that the corresponding
  21799. input channel should be enabled
  21800. @param outputChannels a BitArray in which a set bit indicates that the corresponding
  21801. output channel should be enabled
  21802. @param sampleRate the sample rate to try to use - to find out which rates are
  21803. available, see getNumSampleRates() and getSampleRate()
  21804. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  21805. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  21806. @returns an error description if there's a problem, or an empty string if it succeeds in
  21807. opening the device
  21808. @see close
  21809. */
  21810. virtual const String open (const BitArray& inputChannels,
  21811. const BitArray& outputChannels,
  21812. double sampleRate,
  21813. int bufferSizeSamples) = 0;
  21814. /** Closes and releases the device if it's open. */
  21815. virtual void close() = 0;
  21816. /** Returns true if the device is still open.
  21817. A device might spontaneously close itself if something goes wrong, so this checks if
  21818. it's still open.
  21819. */
  21820. virtual bool isOpen() = 0;
  21821. /** Starts the device actually playing.
  21822. This must be called after the device has been opened.
  21823. @param callback the callback to use for streaming the data.
  21824. @see AudioIODeviceCallback, open
  21825. */
  21826. virtual void start (AudioIODeviceCallback* callback) = 0;
  21827. /** Stops the device playing.
  21828. Once a device has been started, this will stop it. Any pending calls to the
  21829. callback class will be flushed before this method returns.
  21830. */
  21831. virtual void stop() = 0;
  21832. /** Returns true if the device is still calling back.
  21833. The device might mysteriously stop, so this checks whether it's
  21834. still playing.
  21835. */
  21836. virtual bool isPlaying() = 0;
  21837. /** Returns the last error that happened if anything went wrong. */
  21838. virtual const String getLastError() = 0;
  21839. /** Returns the buffer size that the device is currently using.
  21840. If the device isn't actually open, this value doesn't really mean much.
  21841. */
  21842. virtual int getCurrentBufferSizeSamples() = 0;
  21843. /** Returns the sample rate that the device is currently using.
  21844. If the device isn't actually open, this value doesn't really mean much.
  21845. */
  21846. virtual double getCurrentSampleRate() = 0;
  21847. /** Returns the device's current physical bit-depth.
  21848. If the device isn't actually open, this value doesn't really mean much.
  21849. */
  21850. virtual int getCurrentBitDepth() = 0;
  21851. /** Returns a mask showing which of the available output channels are currently
  21852. enabled.
  21853. @see getOutputChannelNames
  21854. */
  21855. virtual const BitArray getActiveOutputChannels() const = 0;
  21856. /** Returns a mask showing which of the available input channels are currently
  21857. enabled.
  21858. @see getInputChannelNames
  21859. */
  21860. virtual const BitArray getActiveInputChannels() const = 0;
  21861. /** Returns the device's output latency.
  21862. This is the delay in samples between a callback getting a block of data, and
  21863. that data actually getting played.
  21864. */
  21865. virtual int getOutputLatencyInSamples() = 0;
  21866. /** Returns the device's input latency.
  21867. This is the delay in samples between some audio actually arriving at the soundcard,
  21868. and the callback getting passed this block of data.
  21869. */
  21870. virtual int getInputLatencyInSamples() = 0;
  21871. /** True if this device can show a pop-up control panel for editing its settings.
  21872. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  21873. to display it.
  21874. */
  21875. virtual bool hasControlPanel() const;
  21876. /** Shows a device-specific control panel if there is one.
  21877. This should only be called for devices which return true from hasControlPanel().
  21878. */
  21879. virtual bool showControlPanel();
  21880. protected:
  21881. /** Creates a device, setting its name and type member variables. */
  21882. AudioIODevice (const String& deviceName,
  21883. const String& typeName);
  21884. /** @internal */
  21885. String name, typeName;
  21886. };
  21887. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  21888. /********* End of inlined file: juce_AudioIODevice.h *********/
  21889. /**
  21890. Wrapper class to continuously stream audio from an audio source to an
  21891. AudioIODevice.
  21892. This object acts as an AudioIODeviceCallback, so can be attached to an
  21893. output device, and will stream audio from an AudioSource.
  21894. */
  21895. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  21896. {
  21897. public:
  21898. /** Creates an empty AudioSourcePlayer. */
  21899. AudioSourcePlayer();
  21900. /** Destructor.
  21901. Make sure this object isn't still being used by an AudioIODevice before
  21902. deleting it!
  21903. */
  21904. virtual ~AudioSourcePlayer();
  21905. /** Changes the current audio source to play from.
  21906. If the source passed in is already being used, this method will do nothing.
  21907. If the source is not null, its prepareToPlay() method will be called
  21908. before it starts being used for playback.
  21909. If there's another source currently playing, its releaseResources() method
  21910. will be called after it has been swapped for the new one.
  21911. @param newSource the new source to use - this will NOT be deleted
  21912. by this object when no longer needed, so it's the
  21913. caller's responsibility to manage it.
  21914. */
  21915. void setSource (AudioSource* newSource);
  21916. /** Returns the source that's playing.
  21917. May return 0 if there's no source.
  21918. */
  21919. AudioSource* getCurrentSource() const throw() { return source; }
  21920. /** Sets a gain to apply to the audio data. */
  21921. void setGain (const float newGain) throw();
  21922. /** Implementation of the AudioIODeviceCallback method. */
  21923. void audioDeviceIOCallback (const float** inputChannelData,
  21924. int totalNumInputChannels,
  21925. float** outputChannelData,
  21926. int totalNumOutputChannels,
  21927. int numSamples);
  21928. /** Implementation of the AudioIODeviceCallback method. */
  21929. void audioDeviceAboutToStart (AudioIODevice* device);
  21930. /** Implementation of the AudioIODeviceCallback method. */
  21931. void audioDeviceStopped();
  21932. juce_UseDebuggingNewOperator
  21933. private:
  21934. CriticalSection readLock;
  21935. AudioSource* source;
  21936. double sampleRate;
  21937. int bufferSize;
  21938. float* channels [128];
  21939. float* outputChans [128];
  21940. const float* inputChans [128];
  21941. AudioSampleBuffer tempBuffer;
  21942. float lastGain, gain;
  21943. AudioSourcePlayer (const AudioSourcePlayer&);
  21944. const AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  21945. };
  21946. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  21947. /********* End of inlined file: juce_AudioSourcePlayer.h *********/
  21948. #endif
  21949. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  21950. /********* Start of inlined file: juce_AudioTransportSource.h *********/
  21951. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  21952. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  21953. /********* Start of inlined file: juce_BufferingAudioSource.h *********/
  21954. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  21955. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  21956. /**
  21957. An AudioSource which takes another source as input, and buffers it using a thread.
  21958. Create this as a wrapper around another thread, and it will read-ahead with
  21959. a background thread to smooth out playback. You can either create one of these
  21960. directly, or use it indirectly using an AudioTransportSource.
  21961. @see PositionableAudioSource, AudioTransportSource
  21962. */
  21963. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  21964. {
  21965. public:
  21966. /** Creates a BufferingAudioSource.
  21967. @param source the input source to read from
  21968. @param deleteSourceWhenDeleted if true, then the input source object will
  21969. be deleted when this object is deleted
  21970. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  21971. */
  21972. BufferingAudioSource (PositionableAudioSource* source,
  21973. const bool deleteSourceWhenDeleted,
  21974. int numberOfSamplesToBuffer);
  21975. /** Destructor.
  21976. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  21977. flag was set in the constructor.
  21978. */
  21979. ~BufferingAudioSource();
  21980. /** Implementation of the AudioSource method. */
  21981. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  21982. /** Implementation of the AudioSource method. */
  21983. void releaseResources();
  21984. /** Implementation of the AudioSource method. */
  21985. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  21986. /** Implements the PositionableAudioSource method. */
  21987. void setNextReadPosition (int newPosition);
  21988. /** Implements the PositionableAudioSource method. */
  21989. int getNextReadPosition() const;
  21990. /** Implements the PositionableAudioSource method. */
  21991. int getTotalLength() const { return source->getTotalLength(); }
  21992. /** Implements the PositionableAudioSource method. */
  21993. bool isLooping() const { return source->isLooping(); }
  21994. juce_UseDebuggingNewOperator
  21995. private:
  21996. PositionableAudioSource* source;
  21997. bool deleteSourceWhenDeleted;
  21998. int numberOfSamplesToBuffer;
  21999. AudioSampleBuffer buffer;
  22000. CriticalSection bufferStartPosLock;
  22001. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  22002. bool wasSourceLooping;
  22003. double volatile sampleRate;
  22004. friend class SharedBufferingAudioSourceThread;
  22005. bool readNextBufferChunk();
  22006. void readBufferSection (int start, int length, int bufferOffset);
  22007. BufferingAudioSource (const BufferingAudioSource&);
  22008. const BufferingAudioSource& operator= (const BufferingAudioSource&);
  22009. };
  22010. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  22011. /********* End of inlined file: juce_BufferingAudioSource.h *********/
  22012. /********* Start of inlined file: juce_ResamplingAudioSource.h *********/
  22013. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  22014. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  22015. /**
  22016. A type of AudioSource that takes an input source and changes its sample rate.
  22017. @see AudioSource
  22018. */
  22019. class JUCE_API ResamplingAudioSource : public AudioSource
  22020. {
  22021. public:
  22022. /** Creates a ResamplingAudioSource for a given input source.
  22023. @param inputSource the input source to read from
  22024. @param deleteInputWhenDeleted if true, the input source will be deleted when
  22025. this object is deleted
  22026. */
  22027. ResamplingAudioSource (AudioSource* const inputSource,
  22028. const bool deleteInputWhenDeleted);
  22029. /** Destructor. */
  22030. ~ResamplingAudioSource();
  22031. /** Changes the resampling ratio.
  22032. (This value can be changed at any time, even while the source is running).
  22033. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  22034. values will speed it up; lower values will slow it
  22035. down. The ratio must be greater than 0
  22036. */
  22037. void setResamplingRatio (const double samplesInPerOutputSample);
  22038. /** Returns the current resampling ratio.
  22039. This is the value that was set by setResamplingRatio().
  22040. */
  22041. double getResamplingRatio() const throw() { return ratio; }
  22042. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22043. void releaseResources();
  22044. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22045. juce_UseDebuggingNewOperator
  22046. private:
  22047. AudioSource* const input;
  22048. const bool deleteInputWhenDeleted;
  22049. double ratio, lastRatio;
  22050. AudioSampleBuffer buffer;
  22051. int bufferPos, sampsInBuffer;
  22052. double subSampleOffset;
  22053. double coefficients[6];
  22054. CriticalSection ratioLock;
  22055. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  22056. void createLowPass (const double proportionalRate);
  22057. struct FilterState
  22058. {
  22059. double x1, x2, y1, y2;
  22060. };
  22061. FilterState filterStates[2];
  22062. void resetFilters();
  22063. void applyFilter (float* samples, int num, FilterState& fs);
  22064. ResamplingAudioSource (const ResamplingAudioSource&);
  22065. const ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  22066. };
  22067. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  22068. /********* End of inlined file: juce_ResamplingAudioSource.h *********/
  22069. /**
  22070. An AudioSource that takes a PositionableAudioSource and allows it to be
  22071. played, stopped, started, etc.
  22072. This can also be told use a buffer and background thread to read ahead, and
  22073. if can correct for different sample-rates.
  22074. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  22075. to control playback of an audio file.
  22076. @see AudioSource, AudioSourcePlayer
  22077. */
  22078. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  22079. public ChangeBroadcaster
  22080. {
  22081. public:
  22082. /** Creates an AudioTransportSource.
  22083. After creating one of these, use the setSource() method to select an input source.
  22084. */
  22085. AudioTransportSource();
  22086. /** Destructor. */
  22087. ~AudioTransportSource();
  22088. /** Sets the reader that is being used as the input source.
  22089. This will stop playback, reset the position to 0 and change to the new reader.
  22090. The source passed in will not be deleted by this object, so must be managed by
  22091. the caller.
  22092. @param newSource the new input source to use. This may be zero
  22093. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  22094. is zero, no reading ahead will be done; if it's
  22095. greater than zero, a BufferingAudioSource will be used
  22096. to do the reading-ahead
  22097. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  22098. rate of the source, and playback will be sample-rate
  22099. adjusted to maintain playback at the correct pitch. If
  22100. this is 0, no sample-rate adjustment will be performed
  22101. */
  22102. void setSource (PositionableAudioSource* const newSource,
  22103. int readAheadBufferSize = 0,
  22104. double sourceSampleRateToCorrectFor = 0.0);
  22105. /** Changes the current playback position in the source stream.
  22106. The next time the getNextAudioBlock() method is called, this
  22107. is the time from which it'll read data.
  22108. @see getPosition
  22109. */
  22110. void setPosition (double newPosition);
  22111. /** Returns the position that the next data block will be read from
  22112. This is a time in seconds.
  22113. */
  22114. double getCurrentPosition() const;
  22115. /** Returns true if the player has stopped because its input stream ran out of data.
  22116. */
  22117. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  22118. /** Starts playing (if a source has been selected).
  22119. If it starts playing, this will send a message to any ChangeListeners
  22120. that are registered with this object.
  22121. */
  22122. void start();
  22123. /** Stops playing.
  22124. If it's actually playing, this will send a message to any ChangeListeners
  22125. that are registered with this object.
  22126. */
  22127. void stop();
  22128. /** Returns true if it's currently playing. */
  22129. bool isPlaying() const throw() { return playing; }
  22130. /** Changes the gain to apply to the output.
  22131. @param newGain a factor by which to multiply the outgoing samples,
  22132. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  22133. */
  22134. void setGain (const float newGain) throw();
  22135. /** Returns the current gain setting.
  22136. @see setGain
  22137. */
  22138. float getGain() const throw() { return gain; }
  22139. /** Implementation of the AudioSource method. */
  22140. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22141. /** Implementation of the AudioSource method. */
  22142. void releaseResources();
  22143. /** Implementation of the AudioSource method. */
  22144. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22145. /** Implements the PositionableAudioSource method. */
  22146. void setNextReadPosition (int newPosition);
  22147. /** Implements the PositionableAudioSource method. */
  22148. int getNextReadPosition() const;
  22149. /** Implements the PositionableAudioSource method. */
  22150. int getTotalLength() const;
  22151. /** Implements the PositionableAudioSource method. */
  22152. bool isLooping() const;
  22153. juce_UseDebuggingNewOperator
  22154. private:
  22155. PositionableAudioSource* source;
  22156. ResamplingAudioSource* resamplerSource;
  22157. BufferingAudioSource* bufferingSource;
  22158. PositionableAudioSource* positionableSource;
  22159. AudioSource* masterSource;
  22160. CriticalSection callbackLock;
  22161. float volatile gain, lastGain;
  22162. bool volatile playing, stopped;
  22163. double sampleRate, sourceSampleRate;
  22164. int blockSize, readAheadBufferSize;
  22165. bool isPrepared, inputStreamEOF;
  22166. AudioTransportSource (const AudioTransportSource&);
  22167. const AudioTransportSource& operator= (const AudioTransportSource&);
  22168. };
  22169. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  22170. /********* End of inlined file: juce_AudioTransportSource.h *********/
  22171. #endif
  22172. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  22173. #endif
  22174. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  22175. /********* Start of inlined file: juce_ChannelRemappingAudioSource.h *********/
  22176. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  22177. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  22178. /**
  22179. An AudioSource that takes the audio from another source, and re-maps its
  22180. input and output channels to a different arrangement.
  22181. You can use this to increase or decrease the number of channels that an
  22182. audio source uses, or to re-order those channels.
  22183. Call the reset() method before using it to set up a default mapping, and then
  22184. the setInputChannelMapping() and setOutputChannelMapping() methods to
  22185. create an appropriate mapping, otherwise no channels will be connected and
  22186. it'll produce silence.
  22187. @see AudioSource
  22188. */
  22189. class ChannelRemappingAudioSource : public AudioSource
  22190. {
  22191. public:
  22192. /** Creates a remapping source that will pass on audio from the given input.
  22193. @param source the input source to use. Make sure that this doesn't
  22194. get deleted before the ChannelRemappingAudioSource object
  22195. @param deleteSourceWhenDeleted if true, the input source will be deleted
  22196. when this object is deleted, if false, the caller is
  22197. responsible for its deletion
  22198. */
  22199. ChannelRemappingAudioSource (AudioSource* const source,
  22200. const bool deleteSourceWhenDeleted);
  22201. /** Destructor. */
  22202. ~ChannelRemappingAudioSource();
  22203. /** Specifies a number of channels that this audio source must produce from its
  22204. getNextAudioBlock() callback.
  22205. */
  22206. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  22207. /** Clears any mapped channels.
  22208. After this, no channels are mapped, so this object will produce silence. Create
  22209. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  22210. */
  22211. void clearAllMappings() throw();
  22212. /** Creates an input channel mapping.
  22213. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  22214. data will be sent to destChannelIndex of our input source.
  22215. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  22216. source specified when this object was created).
  22217. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  22218. during our getNextAudioBlock() callback
  22219. */
  22220. void setInputChannelMapping (const int destChannelIndex,
  22221. const int sourceChannelIndex) throw();
  22222. /** Creates an output channel mapping.
  22223. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  22224. our input audio source will be copied to channel destChannelIndex of the final buffer.
  22225. @param sourceChannelIndex the index of an output channel coming from our input audio source
  22226. (i.e. the source specified when this object was created).
  22227. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  22228. during our getNextAudioBlock() callback
  22229. */
  22230. void setOutputChannelMapping (const int sourceChannelIndex,
  22231. const int destChannelIndex) throw();
  22232. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  22233. our input audio source.
  22234. */
  22235. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  22236. /** Returns the output channel to which channel outputChannelIndex of our input audio
  22237. source will be sent to.
  22238. */
  22239. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  22240. /** Returns an XML object to encapsulate the state of the mappings.
  22241. @see restoreFromXml
  22242. */
  22243. XmlElement* createXml() const throw();
  22244. /** Restores the mappings from an XML object created by createXML().
  22245. @see createXml
  22246. */
  22247. void restoreFromXml (const XmlElement& e) throw();
  22248. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22249. void releaseResources();
  22250. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22251. juce_UseDebuggingNewOperator
  22252. private:
  22253. int requiredNumberOfChannels;
  22254. Array <int> remappedInputs, remappedOutputs;
  22255. AudioSource* const source;
  22256. const bool deleteSourceWhenDeleted;
  22257. AudioSampleBuffer buffer;
  22258. AudioSourceChannelInfo remappedInfo;
  22259. CriticalSection lock;
  22260. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  22261. const ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  22262. };
  22263. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  22264. /********* End of inlined file: juce_ChannelRemappingAudioSource.h *********/
  22265. #endif
  22266. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  22267. /********* Start of inlined file: juce_IIRFilterAudioSource.h *********/
  22268. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  22269. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  22270. /********* Start of inlined file: juce_IIRFilter.h *********/
  22271. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  22272. #define __JUCE_IIRFILTER_JUCEHEADER__
  22273. /**
  22274. An IIR filter that can perform low, high, or band-pass filtering on an
  22275. audio signal.
  22276. @see IIRFilterAudioSource
  22277. */
  22278. class JUCE_API IIRFilter
  22279. {
  22280. public:
  22281. /** Creates a filter.
  22282. Initially the filter is inactive, so will have no effect on samples that
  22283. you process with it. Use the appropriate method to turn it into the type
  22284. of filter needed.
  22285. */
  22286. IIRFilter() throw();
  22287. /** Creates a copy of another filter. */
  22288. IIRFilter (const IIRFilter& other) throw();
  22289. /** Destructor. */
  22290. ~IIRFilter() throw();
  22291. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  22292. Note that this clears the processing state, but the type of filter and
  22293. its coefficients aren't changed. To put a filter into an inactive state, use
  22294. the makeInactive() method.
  22295. */
  22296. void reset() throw();
  22297. /** Performs the filter operation on the given set of samples.
  22298. */
  22299. void processSamples (float* const samples,
  22300. const int numSamples) throw();
  22301. /** Processes a single sample, without any locking or checking.
  22302. Use this if you need fast processing of a single value, but be aware that
  22303. this isn't thread-safe in the way that processSamples() is.
  22304. */
  22305. float processSingleSampleRaw (const float sample) throw();
  22306. /** Sets the filter up to act as a low-pass filter.
  22307. */
  22308. void makeLowPass (const double sampleRate,
  22309. const double frequency) throw();
  22310. /** Sets the filter up to act as a high-pass filter.
  22311. */
  22312. void makeHighPass (const double sampleRate,
  22313. const double frequency) throw();
  22314. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  22315. The gain is a scale factor that the low frequencies are multiplied by, so values
  22316. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  22317. attenuate them.
  22318. */
  22319. void makeLowShelf (const double sampleRate,
  22320. const double cutOffFrequency,
  22321. const double Q,
  22322. const float gainFactor) throw();
  22323. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  22324. The gain is a scale factor that the high frequencies are multiplied by, so values
  22325. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  22326. attenuate them.
  22327. */
  22328. void makeHighShelf (const double sampleRate,
  22329. const double cutOffFrequency,
  22330. const double Q,
  22331. const float gainFactor) throw();
  22332. /** Sets the filter up to act as a band pass filter centred around a
  22333. frequency, with a variable Q and gain.
  22334. The gain is a scale factor that the centre frequencies are multiplied by, so
  22335. values greater than 1.0 will boost the centre frequencies, values less than
  22336. 1.0 will attenuate them.
  22337. */
  22338. void makeBandPass (const double sampleRate,
  22339. const double centreFrequency,
  22340. const double Q,
  22341. const float gainFactor) throw();
  22342. /** Clears the filter's coefficients so that it becomes inactive.
  22343. */
  22344. void makeInactive() throw();
  22345. /** Makes this filter duplicate the set-up of another one.
  22346. */
  22347. void copyCoefficientsFrom (const IIRFilter& other) throw();
  22348. juce_UseDebuggingNewOperator
  22349. protected:
  22350. CriticalSection processLock;
  22351. void setCoefficients (double c1, double c2, double c3,
  22352. double c4, double c5, double c6) throw();
  22353. bool active;
  22354. float coefficients[6];
  22355. float x1, x2, y1, y2;
  22356. // (use the copyCoefficientsFrom() method instead of this operator)
  22357. const IIRFilter& operator= (const IIRFilter&);
  22358. };
  22359. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  22360. /********* End of inlined file: juce_IIRFilter.h *********/
  22361. /**
  22362. An AudioSource that performs an IIR filter on another source.
  22363. */
  22364. class JUCE_API IIRFilterAudioSource : public AudioSource
  22365. {
  22366. public:
  22367. /** Creates a IIRFilterAudioSource for a given input source.
  22368. @param inputSource the input source to read from
  22369. @param deleteInputWhenDeleted if true, the input source will be deleted when
  22370. this object is deleted
  22371. */
  22372. IIRFilterAudioSource (AudioSource* const inputSource,
  22373. const bool deleteInputWhenDeleted);
  22374. /** Destructor. */
  22375. ~IIRFilterAudioSource();
  22376. /** Changes the filter to use the same parameters as the one being passed in.
  22377. */
  22378. void setFilterParameters (const IIRFilter& newSettings);
  22379. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22380. void releaseResources();
  22381. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22382. juce_UseDebuggingNewOperator
  22383. private:
  22384. AudioSource* const input;
  22385. const bool deleteInputWhenDeleted;
  22386. OwnedArray <IIRFilter> iirFilters;
  22387. IIRFilterAudioSource (const IIRFilterAudioSource&);
  22388. const IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  22389. };
  22390. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  22391. /********* End of inlined file: juce_IIRFilterAudioSource.h *********/
  22392. #endif
  22393. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  22394. /********* Start of inlined file: juce_MixerAudioSource.h *********/
  22395. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  22396. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  22397. /**
  22398. An AudioSource that mixes together the output of a set of other AudioSources.
  22399. Input sources can be added and removed while the mixer is running as long as their
  22400. prepareToPlay() and releaseResources() methods are called before and after adding
  22401. them to the mixer.
  22402. */
  22403. class JUCE_API MixerAudioSource : public AudioSource
  22404. {
  22405. public:
  22406. /** Creates a MixerAudioSource.
  22407. */
  22408. MixerAudioSource();
  22409. /** Destructor. */
  22410. ~MixerAudioSource();
  22411. /** Adds an input source to the mixer.
  22412. If the mixer is running you'll need to make sure that the input source
  22413. is ready to play by calling its prepareToPlay() method before adding it.
  22414. If the mixer is stopped, then its input sources will be automatically
  22415. prepared when the mixer's prepareToPlay() method is called.
  22416. @param newInput the source to add to the mixer
  22417. @param deleteWhenRemoved if true, then this source will be deleted when
  22418. the mixer is deleted or when removeAllInputs() is
  22419. called (unless the source is previously removed
  22420. with the removeInputSource method)
  22421. */
  22422. void addInputSource (AudioSource* newInput,
  22423. const bool deleteWhenRemoved);
  22424. /** Removes an input source.
  22425. If the mixer is running, this will remove the source but not call its
  22426. releaseResources() method, so the caller might want to do this manually.
  22427. @param input the source to remove
  22428. @param deleteSource whether to delete this source after it's been removed
  22429. */
  22430. void removeInputSource (AudioSource* input,
  22431. const bool deleteSource);
  22432. /** Removes all the input sources.
  22433. If the mixer is running, this will remove the sources but not call their
  22434. releaseResources() method, so the caller might want to do this manually.
  22435. Any sources which were added with the deleteWhenRemoved flag set will be
  22436. deleted by this method.
  22437. */
  22438. void removeAllInputs();
  22439. /** Implementation of the AudioSource method.
  22440. This will call prepareToPlay() on all its input sources.
  22441. */
  22442. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22443. /** Implementation of the AudioSource method.
  22444. This will call releaseResources() on all its input sources.
  22445. */
  22446. void releaseResources();
  22447. /** Implementation of the AudioSource method. */
  22448. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22449. juce_UseDebuggingNewOperator
  22450. private:
  22451. VoidArray inputs;
  22452. BitArray inputsToDelete;
  22453. CriticalSection lock;
  22454. AudioSampleBuffer tempBuffer;
  22455. double currentSampleRate;
  22456. int bufferSizeExpected;
  22457. MixerAudioSource (const MixerAudioSource&);
  22458. const MixerAudioSource& operator= (const MixerAudioSource&);
  22459. };
  22460. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  22461. /********* End of inlined file: juce_MixerAudioSource.h *********/
  22462. #endif
  22463. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22464. #endif
  22465. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  22466. #endif
  22467. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  22468. /********* Start of inlined file: juce_ToneGeneratorAudioSource.h *********/
  22469. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  22470. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  22471. /**
  22472. A simple AudioSource that generates a sine wave.
  22473. */
  22474. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  22475. {
  22476. public:
  22477. /** Creates a ToneGeneratorAudioSource. */
  22478. ToneGeneratorAudioSource();
  22479. /** Destructor. */
  22480. ~ToneGeneratorAudioSource();
  22481. /** Sets the signal's amplitude. */
  22482. void setAmplitude (const float newAmplitude);
  22483. /** Sets the signal's frequency. */
  22484. void setFrequency (const double newFrequencyHz);
  22485. /** Implementation of the AudioSource method. */
  22486. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22487. /** Implementation of the AudioSource method. */
  22488. void releaseResources();
  22489. /** Implementation of the AudioSource method. */
  22490. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22491. juce_UseDebuggingNewOperator
  22492. private:
  22493. double frequency, sampleRate;
  22494. double currentPhase, phasePerSample;
  22495. float amplitude;
  22496. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  22497. const ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  22498. };
  22499. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  22500. /********* End of inlined file: juce_ToneGeneratorAudioSource.h *********/
  22501. #endif
  22502. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  22503. /********* Start of inlined file: juce_AudioDeviceManager.h *********/
  22504. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  22505. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  22506. /********* Start of inlined file: juce_AudioIODeviceType.h *********/
  22507. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  22508. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  22509. class AudioDeviceManager;
  22510. class Component;
  22511. /**
  22512. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  22513. To get a list of available audio driver types, use the createDeviceTypes()
  22514. method. Each of the objects returned can then be used to list the available
  22515. devices of that type. E.g.
  22516. @code
  22517. OwnedArray <AudioIODeviceType> types;
  22518. AudioIODeviceType::createDeviceTypes (types);
  22519. for (int i = 0; i < types.size(); ++i)
  22520. {
  22521. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  22522. types[i]->scanForDevices(); // This must be called before getting the list of devices
  22523. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  22524. for (int j = 0; j < deviceNames.size(); ++j)
  22525. {
  22526. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  22527. ...
  22528. }
  22529. }
  22530. @endcode
  22531. For an easier way of managing audio devices and their settings, have a look at the
  22532. AudioDeviceManager class.
  22533. @see AudioIODevice, AudioDeviceManager
  22534. */
  22535. class JUCE_API AudioIODeviceType
  22536. {
  22537. public:
  22538. /** Returns the name of this type of driver that this object manages.
  22539. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  22540. */
  22541. const String& getTypeName() const throw() { return typeName; }
  22542. /** Refreshes the object's cached list of known devices.
  22543. This must be called at least once before calling getDeviceNames() or any of
  22544. the other device creation methods.
  22545. */
  22546. virtual void scanForDevices() = 0;
  22547. /** Returns the list of available devices of this type.
  22548. The scanForDevices() method must have been called to create this list.
  22549. @param wantInputNames only really used by DirectSound where devices are split up
  22550. into inputs and outputs, this indicates whether to use
  22551. the input or output name to refer to a pair of devices.
  22552. */
  22553. virtual const StringArray getDeviceNames (const bool wantInputNames = false) const = 0;
  22554. /** Returns the name of the default device.
  22555. This will be one of the names from the getDeviceNames() list.
  22556. @param forInput if true, this means that a default input device should be
  22557. returned; if false, it should return the default output
  22558. */
  22559. virtual int getDefaultDeviceIndex (const bool forInput) const = 0;
  22560. /** Returns the index of a given device in the list of device names.
  22561. If asInput is true, it shows the index in the inputs list, otherwise it
  22562. looks for it in the outputs list.
  22563. */
  22564. virtual int getIndexOfDevice (AudioIODevice* device, const bool asInput) const = 0;
  22565. /** Returns true if two different devices can be used for the input and output.
  22566. */
  22567. virtual bool hasSeparateInputsAndOutputs() const = 0;
  22568. /** Creates one of the devices of this type.
  22569. The deviceName must be one of the strings returned by getDeviceNames(), and
  22570. scanForDevices() must have been called before this method is used.
  22571. */
  22572. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  22573. const String& inputDeviceName) = 0;
  22574. struct DeviceSetupDetails
  22575. {
  22576. AudioDeviceManager* manager;
  22577. int minNumInputChannels, maxNumInputChannels;
  22578. int minNumOutputChannels, maxNumOutputChannels;
  22579. bool useStereoPairs;
  22580. };
  22581. /** Destructor. */
  22582. virtual ~AudioIODeviceType();
  22583. protected:
  22584. AudioIODeviceType (const tchar* const typeName);
  22585. private:
  22586. String typeName;
  22587. AudioIODeviceType (const AudioIODeviceType&);
  22588. const AudioIODeviceType& operator= (const AudioIODeviceType&);
  22589. };
  22590. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  22591. /********* End of inlined file: juce_AudioIODeviceType.h *********/
  22592. /********* Start of inlined file: juce_MidiInput.h *********/
  22593. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  22594. #define __JUCE_MIDIINPUT_JUCEHEADER__
  22595. /********* Start of inlined file: juce_MidiMessage.h *********/
  22596. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  22597. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  22598. /**
  22599. Encapsulates a MIDI message.
  22600. @see MidiMessageSequence, MidiOutput, MidiInput
  22601. */
  22602. class JUCE_API MidiMessage
  22603. {
  22604. public:
  22605. /** Creates a 3-byte short midi message.
  22606. @param byte1 message byte 1
  22607. @param byte2 message byte 2
  22608. @param byte3 message byte 3
  22609. @param timeStamp the time to give the midi message - this value doesn't
  22610. use any particular units, so will be application-specific
  22611. */
  22612. MidiMessage (const int byte1,
  22613. const int byte2,
  22614. const int byte3,
  22615. const double timeStamp = 0) throw();
  22616. /** Creates a 2-byte short midi message.
  22617. @param byte1 message byte 1
  22618. @param byte2 message byte 2
  22619. @param timeStamp the time to give the midi message - this value doesn't
  22620. use any particular units, so will be application-specific
  22621. */
  22622. MidiMessage (const int byte1,
  22623. const int byte2,
  22624. const double timeStamp = 0) throw();
  22625. /** Creates a 1-byte short midi message.
  22626. @param byte1 message byte 1
  22627. @param timeStamp the time to give the midi message - this value doesn't
  22628. use any particular units, so will be application-specific
  22629. */
  22630. MidiMessage (const int byte1,
  22631. const double timeStamp = 0) throw();
  22632. /** Creates a midi message from a block of data. */
  22633. MidiMessage (const uint8* const data,
  22634. const int dataSize,
  22635. const double timeStamp = 0) throw();
  22636. /** Reads the next midi message from some data.
  22637. This will read as many bytes from a data stream as it needs to make a
  22638. complete message, and will return the number of bytes it used. This lets
  22639. you read a sequence of midi messages from a file or stream.
  22640. @param data the data to read from
  22641. @param size the maximum number of bytes it's allowed to read
  22642. @param numBytesUsed returns the number of bytes that were actually needed
  22643. @param lastStatusByte in a sequence of midi messages, the initial byte
  22644. can be dropped from a message if it's the same as the
  22645. first byte of the previous message, so this lets you
  22646. supply the byte to use if the first byte of the message
  22647. has in fact been dropped.
  22648. @param timeStamp the time to give the midi message - this value doesn't
  22649. use any particular units, so will be application-specific
  22650. */
  22651. MidiMessage (const uint8* data,
  22652. int size,
  22653. int& numBytesUsed,
  22654. uint8 lastStatusByte,
  22655. double timeStamp = 0) throw();
  22656. /** Creates a copy of another midi message. */
  22657. MidiMessage (const MidiMessage& other) throw();
  22658. /** Creates a copy of another midi message, with a different timestamp. */
  22659. MidiMessage (const MidiMessage& other,
  22660. const double newTimeStamp) throw();
  22661. /** Destructor. */
  22662. ~MidiMessage() throw();
  22663. /** Copies this message from another one. */
  22664. const MidiMessage& operator= (const MidiMessage& other) throw();
  22665. /** Returns a pointer to the raw midi data.
  22666. @see getRawDataSize
  22667. */
  22668. uint8* getRawData() const throw() { return data; }
  22669. /** Returns the number of bytes of data in the message.
  22670. @see getRawData
  22671. */
  22672. int getRawDataSize() const throw() { return size; }
  22673. /** Returns the timestamp associated with this message.
  22674. The exact meaning of this time and its units will vary, as messages are used in
  22675. a variety of different contexts.
  22676. If you're getting the message from a midi file, this could be a time in seconds, or
  22677. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  22678. If the message is being used in a MidiBuffer, it might indicate the number of
  22679. audio samples from the start of the buffer.
  22680. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  22681. for details of the way that it initialises this value.
  22682. @see setTimeStamp, addToTimeStamp
  22683. */
  22684. double getTimeStamp() const throw() { return timeStamp; }
  22685. /** Changes the message's associated timestamp.
  22686. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  22687. @see addToTimeStamp, getTimeStamp
  22688. */
  22689. void setTimeStamp (const double newTimestamp) throw() { timeStamp = newTimestamp; }
  22690. /** Adds a value to the message's timestamp.
  22691. The units for the timestamp will be application-specific.
  22692. */
  22693. void addToTimeStamp (const double delta) throw() { timeStamp += delta; }
  22694. /** Returns the midi channel associated with the message.
  22695. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  22696. if it's a sysex)
  22697. @see isForChannel, setChannel
  22698. */
  22699. int getChannel() const throw();
  22700. /** Returns true if the message applies to the given midi channel.
  22701. @param channelNumber the channel number to look for, in the range 1 to 16
  22702. @see getChannel, setChannel
  22703. */
  22704. bool isForChannel (const int channelNumber) const throw();
  22705. /** Changes the message's midi channel.
  22706. This won't do anything for non-channel messages like sysexes.
  22707. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  22708. */
  22709. void setChannel (const int newChannelNumber) throw();
  22710. /** Returns true if this is a system-exclusive message.
  22711. */
  22712. bool isSysEx() const throw();
  22713. /** Returns a pointer to the sysex data inside the message.
  22714. If this event isn't a sysex event, it'll return 0.
  22715. @see getSysExDataSize
  22716. */
  22717. const uint8* getSysExData() const throw();
  22718. /** Returns the size of the sysex data.
  22719. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  22720. @see getSysExData
  22721. */
  22722. int getSysExDataSize() const throw();
  22723. /** Returns true if this message is a 'key-down' event.
  22724. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  22725. velocity 0, it will still be considered to be a note-on and the
  22726. method will return true. If returnTrueForVelocity0 is false, then
  22727. if this is a note-on event with velocity 0, it'll be regarded as
  22728. a note-off, and the method will return false
  22729. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  22730. */
  22731. bool isNoteOn (const bool returnTrueForVelocity0 = false) const throw();
  22732. /** Creates a key-down message (using a floating-point velocity).
  22733. @param channel the midi channel, in the range 1 to 16
  22734. @param noteNumber the key number, 0 to 127
  22735. @param velocity in the range 0 to 1.0
  22736. @see isNoteOn
  22737. */
  22738. static const MidiMessage noteOn (const int channel,
  22739. const int noteNumber,
  22740. const float velocity) throw();
  22741. /** Creates a key-down message (using an integer velocity).
  22742. @param channel the midi channel, in the range 1 to 16
  22743. @param noteNumber the key number, 0 to 127
  22744. @param velocity in the range 0 to 127
  22745. @see isNoteOn
  22746. */
  22747. static const MidiMessage noteOn (const int channel,
  22748. const int noteNumber,
  22749. const uint8 velocity) throw();
  22750. /** Returns true if this message is a 'key-up' event.
  22751. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  22752. for a note-on event with a velocity of 0.
  22753. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  22754. */
  22755. bool isNoteOff (const bool returnTrueForNoteOnVelocity0 = true) const throw();
  22756. /** Creates a key-up message.
  22757. @param channel the midi channel, in the range 1 to 16
  22758. @param noteNumber the key number, 0 to 127
  22759. @see isNoteOff
  22760. */
  22761. static const MidiMessage noteOff (const int channel,
  22762. const int noteNumber) throw();
  22763. /** Returns true if this message is a 'key-down' or 'key-up' event.
  22764. @see isNoteOn, isNoteOff
  22765. */
  22766. bool isNoteOnOrOff() const throw();
  22767. /** Returns the midi note number for note-on and note-off messages.
  22768. If the message isn't a note-on or off, the value returned will be
  22769. meaningless.
  22770. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  22771. */
  22772. int getNoteNumber() const throw();
  22773. /** Changes the midi note number of a note-on or note-off message.
  22774. If the message isn't a note on or off, this will do nothing.
  22775. */
  22776. void setNoteNumber (const int newNoteNumber) throw();
  22777. /** Returns the velocity of a note-on or note-off message.
  22778. The value returned will be in the range 0 to 127.
  22779. If the message isn't a note-on or off event, it will return 0.
  22780. @see getFloatVelocity
  22781. */
  22782. uint8 getVelocity() const throw();
  22783. /** Returns the velocity of a note-on or note-off message.
  22784. The value returned will be in the range 0 to 1.0
  22785. If the message isn't a note-on or off event, it will return 0.
  22786. @see getVelocity, setVelocity
  22787. */
  22788. float getFloatVelocity() const throw();
  22789. /** Changes the velocity of a note-on or note-off message.
  22790. If the message isn't a note on or off, this will do nothing.
  22791. @param newVelocity the new velocity, in the range 0 to 1.0
  22792. @see getFloatVelocity, multiplyVelocity
  22793. */
  22794. void setVelocity (const float newVelocity) throw();
  22795. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  22796. If the message isn't a note on or off, this will do nothing.
  22797. @param scaleFactor the value by which to multiply the velocity
  22798. @see setVelocity
  22799. */
  22800. void multiplyVelocity (const float scaleFactor) throw();
  22801. /** Returns true if the message is a program (patch) change message.
  22802. @see getProgramChangeNumber, getGMInstrumentName
  22803. */
  22804. bool isProgramChange() const throw();
  22805. /** Returns the new program number of a program change message.
  22806. If the message isn't a program change, the value returned will be
  22807. nonsense.
  22808. @see isProgramChange, getGMInstrumentName
  22809. */
  22810. int getProgramChangeNumber() const throw();
  22811. /** Creates a program-change message.
  22812. @param channel the midi channel, in the range 1 to 16
  22813. @param programNumber the midi program number, 0 to 127
  22814. @see isProgramChange, getGMInstrumentName
  22815. */
  22816. static const MidiMessage programChange (const int channel,
  22817. const int programNumber) throw();
  22818. /** Returns true if the message is a pitch-wheel move.
  22819. @see getPitchWheelValue, pitchWheel
  22820. */
  22821. bool isPitchWheel() const throw();
  22822. /** Returns the pitch wheel position from a pitch-wheel move message.
  22823. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  22824. If called for messages which aren't pitch wheel events, the number returned will be
  22825. nonsense.
  22826. @see isPitchWheel
  22827. */
  22828. int getPitchWheelValue() const throw();
  22829. /** Creates a pitch-wheel move message.
  22830. @param channel the midi channel, in the range 1 to 16
  22831. @param position the wheel position, in the range 0 to 16383
  22832. @see isPitchWheel
  22833. */
  22834. static const MidiMessage pitchWheel (const int channel,
  22835. const int position) throw();
  22836. /** Returns true if the message is an aftertouch event.
  22837. For aftertouch events, use the getNoteNumber() method to find out the key
  22838. that it applies to, and getAftertouchValue() to find out the amount. Use
  22839. getChannel() to find out the channel.
  22840. @see getAftertouchValue, getNoteNumber
  22841. */
  22842. bool isAftertouch() const throw();
  22843. /** Returns the amount of aftertouch from an aftertouch messages.
  22844. The value returned is in the range 0 to 127, and will be nonsense for messages
  22845. other than aftertouch messages.
  22846. @see isAftertouch
  22847. */
  22848. int getAfterTouchValue() const throw();
  22849. /** Creates an aftertouch message.
  22850. @param channel the midi channel, in the range 1 to 16
  22851. @param noteNumber the key number, 0 to 127
  22852. @param aftertouchAmount the amount of aftertouch, 0 to 127
  22853. @see isAftertouch
  22854. */
  22855. static const MidiMessage aftertouchChange (const int channel,
  22856. const int noteNumber,
  22857. const int aftertouchAmount) throw();
  22858. /** Returns true if the message is a channel-pressure change event.
  22859. This is like aftertouch, but common to the whole channel rather than a specific
  22860. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  22861. to find out the channel.
  22862. @see channelPressureChange
  22863. */
  22864. bool isChannelPressure() const throw();
  22865. /** Returns the pressure from a channel pressure change message.
  22866. @returns the pressure, in the range 0 to 127
  22867. @see isChannelPressure, channelPressureChange
  22868. */
  22869. int getChannelPressureValue() const throw();
  22870. /** Creates a channel-pressure change event.
  22871. @param channel the midi channel: 1 to 16
  22872. @param pressure the pressure, 0 to 127
  22873. @see isChannelPressure
  22874. */
  22875. static const MidiMessage channelPressureChange (const int channel,
  22876. const int pressure) throw();
  22877. /** Returns true if this is a midi controller message.
  22878. @see getControllerNumber, getControllerValue, controllerEvent
  22879. */
  22880. bool isController() const throw();
  22881. /** Returns the controller number of a controller message.
  22882. The name of the controller can be looked up using the getControllerName() method.
  22883. Note that the value returned is invalid for messages that aren't controller changes.
  22884. @see isController, getControllerName, getControllerValue
  22885. */
  22886. int getControllerNumber() const throw();
  22887. /** Returns the controller value from a controller message.
  22888. A value 0 to 127 is returned to indicate the new controller position.
  22889. Note that the value returned is invalid for messages that aren't controller changes.
  22890. @see isController, getControllerNumber
  22891. */
  22892. int getControllerValue() const throw();
  22893. /** Creates a controller message.
  22894. @param channel the midi channel, in the range 1 to 16
  22895. @param controllerType the type of controller
  22896. @param value the controller value
  22897. @see isController
  22898. */
  22899. static const MidiMessage controllerEvent (const int channel,
  22900. const int controllerType,
  22901. const int value) throw();
  22902. /** Checks whether this message is an all-notes-off message.
  22903. @see allNotesOff
  22904. */
  22905. bool isAllNotesOff() const throw();
  22906. /** Checks whether this message is an all-sound-off message.
  22907. @see allSoundOff
  22908. */
  22909. bool isAllSoundOff() const throw();
  22910. /** Creates an all-notes-off message.
  22911. @param channel the midi channel, in the range 1 to 16
  22912. @see isAllNotesOff
  22913. */
  22914. static const MidiMessage allNotesOff (const int channel) throw();
  22915. /** Creates an all-sound-off message.
  22916. @param channel the midi channel, in the range 1 to 16
  22917. @see isAllSoundOff
  22918. */
  22919. static const MidiMessage allSoundOff (const int channel) throw();
  22920. /** Creates an all-controllers-off message.
  22921. @param channel the midi channel, in the range 1 to 16
  22922. */
  22923. static const MidiMessage allControllersOff (const int channel) throw();
  22924. /** Returns true if this event is a meta-event.
  22925. Meta-events are things like tempo changes, track names, etc.
  22926. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  22927. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  22928. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  22929. */
  22930. bool isMetaEvent() const throw();
  22931. /** Returns a meta-event's type number.
  22932. If the message isn't a meta-event, this will return -1.
  22933. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  22934. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  22935. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  22936. */
  22937. int getMetaEventType() const throw();
  22938. /** Returns a pointer to the data in a meta-event.
  22939. @see isMetaEvent, getMetaEventLength
  22940. */
  22941. const uint8* getMetaEventData() const throw();
  22942. /** Returns the length of the data for a meta-event.
  22943. @see isMetaEvent, getMetaEventData
  22944. */
  22945. int getMetaEventLength() const throw();
  22946. /** Returns true if this is a 'track' meta-event. */
  22947. bool isTrackMetaEvent() const throw();
  22948. /** Returns true if this is an 'end-of-track' meta-event. */
  22949. bool isEndOfTrackMetaEvent() const throw();
  22950. /** Creates an end-of-track meta-event.
  22951. @see isEndOfTrackMetaEvent
  22952. */
  22953. static const MidiMessage endOfTrack() throw();
  22954. /** Returns true if this is an 'track name' meta-event.
  22955. You can use the getTextFromTextMetaEvent() method to get the track's name.
  22956. */
  22957. bool isTrackNameEvent() const throw();
  22958. /** Returns true if this is a 'text' meta-event.
  22959. @see getTextFromTextMetaEvent
  22960. */
  22961. bool isTextMetaEvent() const throw();
  22962. /** Returns the text from a text meta-event.
  22963. @see isTextMetaEvent
  22964. */
  22965. const String getTextFromTextMetaEvent() const throw();
  22966. /** Returns true if this is a 'tempo' meta-event.
  22967. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  22968. */
  22969. bool isTempoMetaEvent() const throw();
  22970. /** Returns the tick length from a tempo meta-event.
  22971. @param timeFormat the 16-bit time format value from the midi file's header.
  22972. @returns the tick length (in seconds).
  22973. @see isTempoMetaEvent
  22974. */
  22975. double getTempoMetaEventTickLength (const short timeFormat) const throw();
  22976. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  22977. @see isTempoMetaEvent, getTempoMetaEventTickLength
  22978. */
  22979. double getTempoSecondsPerQuarterNote() const throw();
  22980. /** Creates a tempo meta-event.
  22981. @see isTempoMetaEvent
  22982. */
  22983. static const MidiMessage tempoMetaEvent (const int microsecondsPerQuarterNote) throw();
  22984. /** Returns true if this is a 'time-signature' meta-event.
  22985. @see getTimeSignatureInfo
  22986. */
  22987. bool isTimeSignatureMetaEvent() const throw();
  22988. /** Returns the time-signature values from a time-signature meta-event.
  22989. @see isTimeSignatureMetaEvent
  22990. */
  22991. void getTimeSignatureInfo (int& numerator,
  22992. int& denominator) const throw();
  22993. /** Creates a time-signature meta-event.
  22994. @see isTimeSignatureMetaEvent
  22995. */
  22996. static const MidiMessage timeSignatureMetaEvent (const int numerator,
  22997. const int denominator) throw();
  22998. /** Returns true if this is a 'key-signature' meta-event.
  22999. @see getKeySignatureNumberOfSharpsOrFlats
  23000. */
  23001. bool isKeySignatureMetaEvent() const throw();
  23002. /** Returns the key from a key-signature meta-event.
  23003. @see isKeySignatureMetaEvent
  23004. */
  23005. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  23006. /** Returns true if this is a 'channel' meta-event.
  23007. A channel meta-event specifies the midi channel that should be used
  23008. for subsequent meta-events.
  23009. @see getMidiChannelMetaEventChannel
  23010. */
  23011. bool isMidiChannelMetaEvent() const throw();
  23012. /** Returns the channel number from a channel meta-event.
  23013. @returns the channel, in the range 1 to 16.
  23014. @see isMidiChannelMetaEvent
  23015. */
  23016. int getMidiChannelMetaEventChannel() const throw();
  23017. /** Creates a midi channel meta-event.
  23018. @param channel the midi channel, in the range 1 to 16
  23019. @see isMidiChannelMetaEvent
  23020. */
  23021. static const MidiMessage midiChannelMetaEvent (const int channel) throw();
  23022. /** Returns true if this is an active-sense message. */
  23023. bool isActiveSense() const throw();
  23024. /** Returns true if this is a midi start event.
  23025. @see midiStart
  23026. */
  23027. bool isMidiStart() const throw();
  23028. /** Creates a midi start event. */
  23029. static const MidiMessage midiStart() throw();
  23030. /** Returns true if this is a midi continue event.
  23031. @see midiContinue
  23032. */
  23033. bool isMidiContinue() const throw();
  23034. /** Creates a midi continue event. */
  23035. static const MidiMessage midiContinue() throw();
  23036. /** Returns true if this is a midi stop event.
  23037. @see midiStop
  23038. */
  23039. bool isMidiStop() const throw();
  23040. /** Creates a midi stop event. */
  23041. static const MidiMessage midiStop() throw();
  23042. /** Returns true if this is a midi clock event.
  23043. @see midiClock, songPositionPointer
  23044. */
  23045. bool isMidiClock() const throw();
  23046. /** Creates a midi clock event. */
  23047. static const MidiMessage midiClock() throw();
  23048. /** Returns true if this is a song-position-pointer message.
  23049. @see getSongPositionPointerMidiBeat, songPositionPointer
  23050. */
  23051. bool isSongPositionPointer() const throw();
  23052. /** Returns the midi beat-number of a song-position-pointer message.
  23053. @see isSongPositionPointer, songPositionPointer
  23054. */
  23055. int getSongPositionPointerMidiBeat() const throw();
  23056. /** Creates a song-position-pointer message.
  23057. The position is a number of midi beats from the start of the song, where 1 midi
  23058. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  23059. are 4 midi beats in a quarter-note.
  23060. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  23061. */
  23062. static const MidiMessage songPositionPointer (const int positionInMidiBeats) throw();
  23063. /** Returns true if this is a quarter-frame midi timecode message.
  23064. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  23065. */
  23066. bool isQuarterFrame() const throw();
  23067. /** Returns the sequence number of a quarter-frame midi timecode message.
  23068. This will be a value between 0 and 7.
  23069. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  23070. */
  23071. int getQuarterFrameSequenceNumber() const throw();
  23072. /** Returns the value from a quarter-frame message.
  23073. This will be the lower nybble of the message's data-byte, a value
  23074. between 0 and 15
  23075. */
  23076. int getQuarterFrameValue() const throw();
  23077. /** Creates a quarter-frame MTC message.
  23078. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  23079. @param value a value 0 to 15 for the lower nybble of the message's data byte
  23080. */
  23081. static const MidiMessage quarterFrame (const int sequenceNumber,
  23082. const int value) throw();
  23083. /** SMPTE timecode types.
  23084. Used by the getFullFrameParameters() and fullFrame() methods.
  23085. */
  23086. enum SmpteTimecodeType
  23087. {
  23088. fps24 = 0,
  23089. fps25 = 1,
  23090. fps30drop = 2,
  23091. fps30 = 3
  23092. };
  23093. /** Returns true if this is a full-frame midi timecode message.
  23094. */
  23095. bool isFullFrame() const throw();
  23096. /** Extracts the timecode information from a full-frame midi timecode message.
  23097. You should only call this on messages where you've used isFullFrame() to
  23098. check that they're the right kind.
  23099. */
  23100. void getFullFrameParameters (int& hours,
  23101. int& minutes,
  23102. int& seconds,
  23103. int& frames,
  23104. SmpteTimecodeType& timecodeType) const throw();
  23105. /** Creates a full-frame MTC message.
  23106. */
  23107. static const MidiMessage fullFrame (const int hours,
  23108. const int minutes,
  23109. const int seconds,
  23110. const int frames,
  23111. SmpteTimecodeType timecodeType);
  23112. /** Types of MMC command.
  23113. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  23114. */
  23115. enum MidiMachineControlCommand
  23116. {
  23117. mmc_stop = 1,
  23118. mmc_play = 2,
  23119. mmc_deferredplay = 3,
  23120. mmc_fastforward = 4,
  23121. mmc_rewind = 5,
  23122. mmc_recordStart = 6,
  23123. mmc_recordStop = 7,
  23124. mmc_pause = 9
  23125. };
  23126. /** Checks whether this is an MMC message.
  23127. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  23128. */
  23129. bool isMidiMachineControlMessage() const throw();
  23130. /** For an MMC message, this returns its type.
  23131. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  23132. calling this method.
  23133. */
  23134. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  23135. /** Creates an MMC message.
  23136. */
  23137. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  23138. /** Checks whether this is an MMC "goto" message.
  23139. If it is, the parameters passed-in are set to the time that the message contains.
  23140. @see midiMachineControlGoto
  23141. */
  23142. bool isMidiMachineControlGoto (int& hours,
  23143. int& minutes,
  23144. int& seconds,
  23145. int& frames) const throw();
  23146. /** Creates an MMC "goto" message.
  23147. This messages tells the device to go to a specific frame.
  23148. @see isMidiMachineControlGoto
  23149. */
  23150. static const MidiMessage midiMachineControlGoto (int hours,
  23151. int minutes,
  23152. int seconds,
  23153. int frames);
  23154. /** Creates a master-volume change message.
  23155. @param volume the volume, 0 to 1.0
  23156. */
  23157. static const MidiMessage masterVolume (const float volume) throw();
  23158. /** Creates a system-exclusive message.
  23159. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  23160. */
  23161. static const MidiMessage createSysExMessage (const uint8* sysexData,
  23162. const int dataSize) throw();
  23163. /** Reads a midi variable-length integer.
  23164. @param data the data to read the number from
  23165. @param numBytesUsed on return, this will be set to the number of bytes that were read
  23166. */
  23167. static int readVariableLengthVal (const uint8* data,
  23168. int& numBytesUsed) throw();
  23169. /** Based on the first byte of a short midi message, this uses a lookup table
  23170. to return the message length (either 1, 2, or 3 bytes).
  23171. The value passed in must be 0x80 or higher.
  23172. */
  23173. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  23174. /** Returns the name of a midi note number.
  23175. E.g "C", "D#", etc.
  23176. @param noteNumber the midi note number, 0 to 127
  23177. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  23178. they'll be flattened, e.g. "Db"
  23179. @param includeOctaveNumber if true, the octave number will be appended to the string,
  23180. e.g. "C#4"
  23181. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  23182. number that will be used for middle C's octave
  23183. @see getMidiNoteInHertz
  23184. */
  23185. static const String getMidiNoteName (int noteNumber,
  23186. bool useSharps,
  23187. bool includeOctaveNumber,
  23188. int octaveNumForMiddleC) throw();
  23189. /** Returns the frequency of a midi note number.
  23190. @see getMidiNoteName
  23191. */
  23192. static const double getMidiNoteInHertz (int noteNumber) throw();
  23193. /** Returns the standard name of a GM instrument.
  23194. @param midiInstrumentNumber the program number 0 to 127
  23195. @see getProgramChangeNumber
  23196. */
  23197. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  23198. /** Returns the name of a bank of GM instruments.
  23199. @param midiBankNumber the bank, 0 to 15
  23200. */
  23201. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  23202. /** Returns the standard name of a channel 10 percussion sound.
  23203. @param midiNoteNumber the key number, 35 to 81
  23204. */
  23205. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  23206. /** Returns the name of a controller type number.
  23207. @see getControllerNumber
  23208. */
  23209. static const String getControllerName (int controllerNumber) throw();
  23210. juce_UseDebuggingNewOperator
  23211. private:
  23212. double timeStamp;
  23213. uint8* data;
  23214. int message, size;
  23215. };
  23216. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  23217. /********* End of inlined file: juce_MidiMessage.h *********/
  23218. class MidiInput;
  23219. /**
  23220. Receives midi messages from a midi input device.
  23221. This class is overridden to handle incoming midi messages. See the MidiInput
  23222. class for more details.
  23223. @see MidiInput
  23224. */
  23225. class JUCE_API MidiInputCallback
  23226. {
  23227. public:
  23228. /** Destructor. */
  23229. virtual ~MidiInputCallback() {}
  23230. /** Receives an incoming message.
  23231. A MidiInput object will call this method when a midi event arrives. It'll be
  23232. called on a high-priority system thread, so avoid doing anything time-consuming
  23233. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  23234. for queueing incoming messages for use later.
  23235. @param source the MidiInput object that generated the message
  23236. @param message the incoming message. The message's timestamp is set to a value
  23237. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  23238. time when the message arrived.
  23239. */
  23240. virtual void handleIncomingMidiMessage (MidiInput* source,
  23241. const MidiMessage& message) = 0;
  23242. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  23243. If a long sysex message is broken up into multiple packets, this callback is made
  23244. for each packet that arrives until the message is finished, at which point
  23245. the normal handleIncomingMidiMessage() callback will be made with the entire
  23246. message.
  23247. The message passed in will contain the start of a sysex, but won't be finished
  23248. with the terminating 0xf7 byte.
  23249. */
  23250. virtual void handlePartialSysexMessage (MidiInput* source,
  23251. const uint8* messageData,
  23252. const int numBytesSoFar,
  23253. const double timestamp)
  23254. {
  23255. // (this bit is just to avoid compiler warnings about unused variables)
  23256. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  23257. }
  23258. };
  23259. /**
  23260. Represents a midi input device.
  23261. To create one of these, use the static getDevices() method to find out what inputs are
  23262. available, and then use the openDevice() method to try to open one.
  23263. @see MidiOutput
  23264. */
  23265. class JUCE_API MidiInput
  23266. {
  23267. public:
  23268. /** Returns a list of the available midi input devices.
  23269. You can open one of the devices by passing its index into the
  23270. openDevice() method.
  23271. @see getDefaultDeviceIndex, openDevice
  23272. */
  23273. static const StringArray getDevices();
  23274. /** Returns the index of the default midi input device to use.
  23275. This refers to the index in the list returned by getDevices().
  23276. */
  23277. static int getDefaultDeviceIndex();
  23278. /** Tries to open one of the midi input devices.
  23279. This will return a MidiInput object if it manages to open it. You can then
  23280. call start() and stop() on this device, and delete it when no longer needed.
  23281. If the device can't be opened, this will return a null pointer.
  23282. @param deviceIndex the index of a device from the list returned by getDevices()
  23283. @param callback the object that will receive the midi messages from this device.
  23284. @see MidiInputCallback, getDevices
  23285. */
  23286. static MidiInput* openDevice (int deviceIndex,
  23287. MidiInputCallback* callback);
  23288. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  23289. /** This will try to create a new midi input device (Not available on Windows).
  23290. This will attempt to create a new midi input device with the specified name,
  23291. for other apps to connect to.
  23292. Returns 0 if a device can't be created.
  23293. @param deviceName the name to use for the new device
  23294. @param callback the object that will receive the midi messages from this device.
  23295. */
  23296. static MidiInput* createNewDevice (const String& deviceName,
  23297. MidiInputCallback* callback);
  23298. #endif
  23299. /** Destructor. */
  23300. virtual ~MidiInput();
  23301. /** Returns the name of this device.
  23302. */
  23303. virtual const String getName() const throw() { return name; }
  23304. /** Allows you to set a custom name for the device, in case you don't like the name
  23305. it was given when created.
  23306. */
  23307. virtual void setName (const String& newName) throw() { name = newName; }
  23308. /** Starts the device running.
  23309. After calling this, the device will start sending midi messages to the
  23310. MidiInputCallback object that was specified when the openDevice() method
  23311. was called.
  23312. @see stop
  23313. */
  23314. virtual void start();
  23315. /** Stops the device running.
  23316. @see start
  23317. */
  23318. virtual void stop();
  23319. juce_UseDebuggingNewOperator
  23320. protected:
  23321. String name;
  23322. void* internal;
  23323. MidiInput (const String& name);
  23324. MidiInput (const MidiInput&);
  23325. };
  23326. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  23327. /********* End of inlined file: juce_MidiInput.h *********/
  23328. /********* Start of inlined file: juce_MidiOutput.h *********/
  23329. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  23330. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  23331. /********* Start of inlined file: juce_MidiBuffer.h *********/
  23332. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  23333. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  23334. /**
  23335. Holds a sequence of time-stamped midi events.
  23336. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  23337. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  23338. @see MidiMessage
  23339. */
  23340. class JUCE_API MidiBuffer
  23341. {
  23342. public:
  23343. /** Creates an empty MidiBuffer. */
  23344. MidiBuffer() throw();
  23345. /** Creates a MidiBuffer containing a single midi message. */
  23346. MidiBuffer (const MidiMessage& message) throw();
  23347. /** Creates a copy of another MidiBuffer. */
  23348. MidiBuffer (const MidiBuffer& other) throw();
  23349. /** Makes a copy of another MidiBuffer. */
  23350. const MidiBuffer& operator= (const MidiBuffer& other) throw();
  23351. /** Destructor */
  23352. ~MidiBuffer() throw();
  23353. /** Removes all events from the buffer. */
  23354. void clear() throw();
  23355. /** Removes all events between two times from the buffer.
  23356. All events for which (start <= event position < start + numSamples) will
  23357. be removed.
  23358. */
  23359. void clear (const int start,
  23360. const int numSamples) throw();
  23361. /** Returns true if the buffer is empty.
  23362. To actually retrieve the events, use a MidiBuffer::Iterator object
  23363. */
  23364. bool isEmpty() const throw();
  23365. /** Counts the number of events in the buffer.
  23366. This is actually quite a slow operation, as it has to iterate through all
  23367. the events, so you might prefer to call isEmpty() if that's all you need
  23368. to know.
  23369. */
  23370. int getNumEvents() const throw();
  23371. /** Adds an event to the buffer.
  23372. The sample number will be used to determine the position of the event in
  23373. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  23374. ignored.
  23375. If an event is added whose sample position is the same as one or more events
  23376. already in the buffer, the new event will be placed after the existing ones.
  23377. To retrieve events, use a MidiBuffer::Iterator object
  23378. */
  23379. void addEvent (const MidiMessage& midiMessage,
  23380. const int sampleNumber) throw();
  23381. /** Adds an event to the buffer from raw midi data.
  23382. The sample number will be used to determine the position of the event in
  23383. the buffer, which is always kept sorted.
  23384. If an event is added whose sample position is the same as one or more events
  23385. already in the buffer, the new event will be placed after the existing ones.
  23386. The event data will be inspected to calculate the number of bytes in length that
  23387. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  23388. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  23389. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  23390. add an event at all.
  23391. To retrieve events, use a MidiBuffer::Iterator object
  23392. */
  23393. void addEvent (const uint8* const rawMidiData,
  23394. const int maxBytesOfMidiData,
  23395. const int sampleNumber) throw();
  23396. /** Adds some events from another buffer to this one.
  23397. @param otherBuffer the buffer containing the events you want to add
  23398. @param startSample the lowest sample number in the source buffer for which
  23399. events should be added. Any source events whose timestamp is
  23400. less than this will be ignored
  23401. @param numSamples the valid range of samples from the source buffer for which
  23402. events should be added - i.e. events in the source buffer whose
  23403. timestamp is greater than or equal to (startSample + numSamples)
  23404. will be ignored. If this value is less than 0, all events after
  23405. startSample will be taken.
  23406. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  23407. that are added to this buffer
  23408. */
  23409. void addEvents (const MidiBuffer& otherBuffer,
  23410. const int startSample,
  23411. const int numSamples,
  23412. const int sampleDeltaToAdd) throw();
  23413. /** Returns the sample number of the first event in the buffer.
  23414. If the buffer's empty, this will just return 0.
  23415. */
  23416. int getFirstEventTime() const throw();
  23417. /** Returns the sample number of the last event in the buffer.
  23418. If the buffer's empty, this will just return 0.
  23419. */
  23420. int getLastEventTime() const throw();
  23421. /** Exchanges the contents of this buffer with another one.
  23422. This is a quick operation, because no memory allocating or copying is done, it
  23423. just swaps the internal state of the two buffers.
  23424. */
  23425. void swap (MidiBuffer& other);
  23426. /**
  23427. Used to iterate through the events in a MidiBuffer.
  23428. Note that altering the buffer while an iterator is using it isn't a
  23429. safe operation.
  23430. @see MidiBuffer
  23431. */
  23432. class Iterator
  23433. {
  23434. public:
  23435. /** Creates an Iterator for this MidiBuffer. */
  23436. Iterator (const MidiBuffer& buffer) throw();
  23437. /** Destructor. */
  23438. ~Iterator() throw();
  23439. /** Repositions the iterator so that the next event retrieved will be the first
  23440. one whose sample position is at greater than or equal to the given position.
  23441. */
  23442. void setNextSamplePosition (const int samplePosition) throw();
  23443. /** Retrieves a copy of the next event from the buffer.
  23444. @param result on return, this will be the message (the MidiMessage's timestamp
  23445. is not set)
  23446. @param samplePosition on return, this will be the position of the event
  23447. @returns true if an event was found, or false if the iterator has reached
  23448. the end of the buffer
  23449. */
  23450. bool getNextEvent (MidiMessage& result,
  23451. int& samplePosition) throw();
  23452. /** Retrieves the next event from the buffer.
  23453. @param midiData on return, this pointer will be set to a block of data containing
  23454. the midi message. Note that to make it fast, this is a pointer
  23455. directly into the MidiBuffer's internal data, so is only valid
  23456. temporarily until the MidiBuffer is altered.
  23457. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  23458. midi message
  23459. @param samplePosition on return, this will be the position of the event
  23460. @returns true if an event was found, or false if the iterator has reached
  23461. the end of the buffer
  23462. */
  23463. bool getNextEvent (const uint8* &midiData,
  23464. int& numBytesOfMidiData,
  23465. int& samplePosition) throw();
  23466. juce_UseDebuggingNewOperator
  23467. private:
  23468. const MidiBuffer& buffer;
  23469. const uint8* data;
  23470. Iterator (const Iterator&);
  23471. const Iterator& operator= (const Iterator&);
  23472. };
  23473. juce_UseDebuggingNewOperator
  23474. private:
  23475. friend class MidiBuffer::Iterator;
  23476. ArrayAllocationBase <uint8> data;
  23477. int bytesUsed;
  23478. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  23479. };
  23480. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  23481. /********* End of inlined file: juce_MidiBuffer.h *********/
  23482. /**
  23483. Represents a midi output device.
  23484. To create one of these, use the static getDevices() method to find out what
  23485. outputs are available, then use the openDevice() method to try to open one.
  23486. @see MidiInput
  23487. */
  23488. class JUCE_API MidiOutput : private Thread
  23489. {
  23490. public:
  23491. /** Returns a list of the available midi output devices.
  23492. You can open one of the devices by passing its index into the
  23493. openDevice() method.
  23494. @see getDefaultDeviceIndex, openDevice
  23495. */
  23496. static const StringArray getDevices();
  23497. /** Returns the index of the default midi output device to use.
  23498. This refers to the index in the list returned by getDevices().
  23499. */
  23500. static int getDefaultDeviceIndex();
  23501. /** Tries to open one of the midi output devices.
  23502. This will return a MidiOutput object if it manages to open it. You can then
  23503. send messages to this device, and delete it when no longer needed.
  23504. If the device can't be opened, this will return a null pointer.
  23505. @param deviceIndex the index of a device from the list returned by getDevices()
  23506. @see getDevices
  23507. */
  23508. static MidiOutput* openDevice (int deviceIndex);
  23509. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  23510. /** This will try to create a new midi output device (Not available on Windows).
  23511. This will attempt to create a new midi output device that other apps can connect
  23512. to and use as their midi input.
  23513. Returns 0 if a device can't be created.
  23514. @param deviceName the name to use for the new device
  23515. */
  23516. static MidiOutput* createNewDevice (const String& deviceName);
  23517. #endif
  23518. /** Destructor. */
  23519. virtual ~MidiOutput();
  23520. /** Makes this device output a midi message.
  23521. @see MidiMessage
  23522. */
  23523. virtual void sendMessageNow (const MidiMessage& message);
  23524. /** Sends a midi reset to the device. */
  23525. virtual void reset();
  23526. /** Returns the current volume setting for this device. */
  23527. virtual bool getVolume (float& leftVol,
  23528. float& rightVol);
  23529. /** Changes the overall volume for this device. */
  23530. virtual void setVolume (float leftVol,
  23531. float rightVol);
  23532. /** This lets you supply a block of messages that will be sent out at some point
  23533. in the future.
  23534. The MidiOutput class has an internal thread that can send out timestamped
  23535. messages - this appends a set of messages to its internal buffer, ready for
  23536. sending.
  23537. This will only work if you've already started the thread with startBackgroundThread().
  23538. A time is supplied, at which the block of messages should be sent. This time uses
  23539. the same time base as Time::getMillisecondCounter(), and must be in the future.
  23540. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  23541. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  23542. samplesPerSecondForBuffer value is needed to convert this sample position to a
  23543. real time.
  23544. */
  23545. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  23546. const double millisecondCounterToStartAt,
  23547. double samplesPerSecondForBuffer) throw();
  23548. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  23549. */
  23550. virtual void clearAllPendingMessages() throw();
  23551. /** Starts up a background thread so that the device can send blocks of data.
  23552. Call this to get the device ready, before using sendBlockOfMessages().
  23553. */
  23554. virtual void startBackgroundThread() throw();
  23555. /** Stops the background thread, and clears any pending midi events.
  23556. @see startBackgroundThread
  23557. */
  23558. virtual void stopBackgroundThread() throw();
  23559. juce_UseDebuggingNewOperator
  23560. protected:
  23561. void* internal;
  23562. struct PendingMessage
  23563. {
  23564. PendingMessage (const uint8* const data, const int len, const double sampleNumber) throw();
  23565. MidiMessage message;
  23566. PendingMessage* next;
  23567. juce_UseDebuggingNewOperator
  23568. };
  23569. CriticalSection lock;
  23570. PendingMessage* firstMessage;
  23571. MidiOutput() throw();
  23572. MidiOutput (const MidiOutput&);
  23573. void run();
  23574. };
  23575. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  23576. /********* End of inlined file: juce_MidiOutput.h *********/
  23577. /********* Start of inlined file: juce_ComboBox.h *********/
  23578. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  23579. #define __JUCE_COMBOBOX_JUCEHEADER__
  23580. /********* Start of inlined file: juce_Label.h *********/
  23581. #ifndef __JUCE_LABEL_JUCEHEADER__
  23582. #define __JUCE_LABEL_JUCEHEADER__
  23583. /********* Start of inlined file: juce_ComponentDeletionWatcher.h *********/
  23584. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23585. #define __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23586. /**
  23587. Object for monitoring a component, and later testing whether it's still valid.
  23588. Slightly obscure, this one, but it's used internally for making sure that
  23589. after some callbacks, a component hasn't been deleted. It's more reliable than
  23590. just using isValidComponent(), which can provide false-positives if a new
  23591. component is created at the same memory location as an old one.
  23592. */
  23593. class JUCE_API ComponentDeletionWatcher
  23594. {
  23595. public:
  23596. /** Creates a watcher for a given component.
  23597. The component must be valid at the time it's passed in.
  23598. */
  23599. ComponentDeletionWatcher (const Component* const componentToWatch) throw();
  23600. /** Destructor. */
  23601. ~ComponentDeletionWatcher() throw();
  23602. /** Returns true if the component has been deleted since the time that this
  23603. object was created.
  23604. */
  23605. bool hasBeenDeleted() const throw();
  23606. /** Returns the component that's being watched, or null if it has been deleted. */
  23607. const Component* getComponent() const throw();
  23608. juce_UseDebuggingNewOperator
  23609. private:
  23610. const Component* const componentToWatch;
  23611. const uint32 componentUID;
  23612. ComponentDeletionWatcher (const ComponentDeletionWatcher&);
  23613. const ComponentDeletionWatcher& operator= (const ComponentDeletionWatcher&);
  23614. };
  23615. #endif // __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  23616. /********* End of inlined file: juce_ComponentDeletionWatcher.h *********/
  23617. /********* Start of inlined file: juce_TextEditor.h *********/
  23618. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  23619. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  23620. /********* Start of inlined file: juce_Viewport.h *********/
  23621. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  23622. #define __JUCE_VIEWPORT_JUCEHEADER__
  23623. /********* Start of inlined file: juce_ScrollBar.h *********/
  23624. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  23625. #define __JUCE_SCROLLBAR_JUCEHEADER__
  23626. /********* Start of inlined file: juce_Button.h *********/
  23627. #ifndef __JUCE_BUTTON_JUCEHEADER__
  23628. #define __JUCE_BUTTON_JUCEHEADER__
  23629. /********* Start of inlined file: juce_TooltipWindow.h *********/
  23630. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23631. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23632. /********* Start of inlined file: juce_TooltipClient.h *********/
  23633. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23634. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23635. /**
  23636. Components that want to use pop-up tooltips should implement this interface.
  23637. A TooltipWindow will wait for the mouse to hover over a component that
  23638. implements the TooltipClient interface, and when it finds one, it will display
  23639. the tooltip returned by its getTooltip() method.
  23640. @see TooltipWindow, SettableTooltipClient
  23641. */
  23642. class JUCE_API TooltipClient
  23643. {
  23644. public:
  23645. /** Destructor. */
  23646. virtual ~TooltipClient() {}
  23647. /** Returns the string that this object wants to show as its tooltip. */
  23648. virtual const String getTooltip() = 0;
  23649. };
  23650. /**
  23651. An implementation of TooltipClient that stores the tooltip string and a method
  23652. for changing it.
  23653. This makes it easy to add a tooltip to a custom component, by simply adding this
  23654. as a base class and calling setTooltip().
  23655. Many of the Juce widgets already use this as a base class to implement their
  23656. tooltips.
  23657. @see TooltipClient, TooltipWindow
  23658. */
  23659. class JUCE_API SettableTooltipClient : public TooltipClient
  23660. {
  23661. public:
  23662. /** Destructor. */
  23663. virtual ~SettableTooltipClient() {}
  23664. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  23665. virtual const String getTooltip() { return tooltipString; }
  23666. juce_UseDebuggingNewOperator
  23667. protected:
  23668. String tooltipString;
  23669. };
  23670. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  23671. /********* End of inlined file: juce_TooltipClient.h *********/
  23672. /**
  23673. A window that displays a pop-up tooltip when the mouse hovers over another component.
  23674. To enable tooltips in your app, just create a single instance of a TooltipWindow
  23675. object.
  23676. The TooltipWindow object will then stay invisible, waiting until the mouse
  23677. hovers for the specified length of time - it will then see if it's currently
  23678. over a component which implements the TooltipClient interface, and if so,
  23679. it will make itself visible to show the tooltip in the appropriate place.
  23680. @see TooltipClient, SettableTooltipClient
  23681. */
  23682. class JUCE_API TooltipWindow : public Component,
  23683. private Timer
  23684. {
  23685. public:
  23686. /** Creates a tooltip window.
  23687. Make sure your app only creates one instance of this class, otherwise you'll
  23688. get multiple overlaid tooltips appearing. The window will initially be invisible
  23689. and will make itself visible when it needs to display a tip.
  23690. To change the style of tooltips, see the LookAndFeel class for its tooltip
  23691. methods.
  23692. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  23693. otherwise the tooltip will be added to the given parent
  23694. component.
  23695. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  23696. before a tooltip will be shown
  23697. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  23698. */
  23699. TooltipWindow (Component* parentComponent = 0,
  23700. const int millisecondsBeforeTipAppears = 700);
  23701. /** Destructor. */
  23702. ~TooltipWindow();
  23703. /** Changes the time before the tip appears.
  23704. This lets you change the value that was set in the constructor.
  23705. */
  23706. void setMillisecondsBeforeTipAppears (const int newTimeMs = 700) throw();
  23707. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  23708. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  23709. methods.
  23710. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  23711. */
  23712. enum ColourIds
  23713. {
  23714. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  23715. textColourId = 0x1001c00, /**< The colour to use for the text. */
  23716. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  23717. };
  23718. juce_UseDebuggingNewOperator
  23719. private:
  23720. int millisecondsBeforeTipAppears;
  23721. int mouseX, mouseY, mouseClicks;
  23722. unsigned int lastCompChangeTime, lastHideTime;
  23723. Component* lastComponentUnderMouse;
  23724. bool changedCompsSinceShown;
  23725. String tipShowing, lastTipUnderMouse;
  23726. void paint (Graphics& g);
  23727. void mouseEnter (const MouseEvent& e);
  23728. void timerCallback();
  23729. static const String getTipFor (Component* const c);
  23730. void showFor (Component* const c, const String& tip);
  23731. void hide();
  23732. TooltipWindow (const TooltipWindow&);
  23733. const TooltipWindow& operator= (const TooltipWindow&);
  23734. };
  23735. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  23736. /********* End of inlined file: juce_TooltipWindow.h *********/
  23737. class Button;
  23738. /**
  23739. Used to receive callbacks when a button is clicked.
  23740. @see Button::addButtonListener, Button::removeButtonListener
  23741. */
  23742. class JUCE_API ButtonListener
  23743. {
  23744. public:
  23745. /** Destructor. */
  23746. virtual ~ButtonListener() {}
  23747. /** Called when the button is clicked. */
  23748. virtual void buttonClicked (Button* button) = 0;
  23749. /** Called when the button's state changes. */
  23750. virtual void buttonStateChanged (Button*) {}
  23751. };
  23752. /**
  23753. A base class for buttons.
  23754. This contains all the logic for button behaviours such as enabling/disabling,
  23755. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  23756. and radio groups, etc.
  23757. @see TextButton, DrawableButton, ToggleButton
  23758. */
  23759. class JUCE_API Button : public Component,
  23760. public SettableTooltipClient,
  23761. public ApplicationCommandManagerListener,
  23762. private KeyListener
  23763. {
  23764. protected:
  23765. /** Creates a button.
  23766. @param buttonName the text to put in the button (the component's name is also
  23767. initially set to this string, but these can be changed later
  23768. using the setName() and setButtonText() methods)
  23769. */
  23770. Button (const String& buttonName);
  23771. public:
  23772. /** Destructor. */
  23773. virtual ~Button();
  23774. /** Changes the button's text.
  23775. @see getButtonText
  23776. */
  23777. void setButtonText (const String& newText) throw();
  23778. /** Returns the text displayed in the button.
  23779. @see setButtonText
  23780. */
  23781. const String getButtonText() const throw() { return text; }
  23782. /** Returns true if the button is currently being held down by the mouse.
  23783. @see isOver
  23784. */
  23785. bool isDown() const throw();
  23786. /** Returns true if the mouse is currently over the button.
  23787. This will be also be true if the mouse is being held down.
  23788. @see isDown
  23789. */
  23790. bool isOver() const throw();
  23791. /** A button has an on/off state associated with it, and this changes that.
  23792. By default buttons are 'off' and for simple buttons that you click to perform
  23793. an action you won't change this. Toggle buttons, however will want to
  23794. change their state when turned on or off.
  23795. @param shouldBeOn whether to set the button's toggle state to be on or
  23796. off. If it's a member of a button group, this will
  23797. always try to turn it on, and to turn off any other
  23798. buttons in the group
  23799. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  23800. the button will be repainted but no notification will
  23801. be sent
  23802. @see getToggleState, setRadioGroupId
  23803. */
  23804. void setToggleState (const bool shouldBeOn,
  23805. const bool sendChangeNotification);
  23806. /** Returns true if the button in 'on'.
  23807. By default buttons are 'off' and for simple buttons that you click to perform
  23808. an action you won't change this. Toggle buttons, however will want to
  23809. change their state when turned on or off.
  23810. @see setToggleState
  23811. */
  23812. bool getToggleState() const throw() { return isOn; }
  23813. /** This tells the button to automatically flip the toggle state when
  23814. the button is clicked.
  23815. If set to true, then before the clicked() callback occurs, the toggle-state
  23816. of the button is flipped.
  23817. */
  23818. void setClickingTogglesState (const bool shouldToggle) throw();
  23819. /** Returns true if this button is set to be an automatic toggle-button.
  23820. This returns the last value that was passed to setClickingTogglesState().
  23821. */
  23822. bool getClickingTogglesState() const throw();
  23823. /** Enables the button to act as a member of a mutually-exclusive group
  23824. of 'radio buttons'.
  23825. If the group ID is set to a non-zero number, then this button will
  23826. act as part of a group of buttons with the same ID, only one of
  23827. which can be 'on' at the same time. Note that when it's part of
  23828. a group, clicking a toggle-button that's 'on' won't turn it off.
  23829. To find other buttons with the same ID, this button will search through
  23830. its sibling components for ToggleButtons, so all the buttons for a
  23831. particular group must be placed inside the same parent component.
  23832. Set the group ID back to zero if you want it to act as a normal toggle
  23833. button again.
  23834. @see getRadioGroupId
  23835. */
  23836. void setRadioGroupId (const int newGroupId);
  23837. /** Returns the ID of the group to which this button belongs.
  23838. (See setRadioGroupId() for an explanation of this).
  23839. */
  23840. int getRadioGroupId() const throw() { return radioGroupId; }
  23841. /** Registers a listener to receive events when this button's state changes.
  23842. If the listener is already registered, this will not register it again.
  23843. @see removeButtonListener
  23844. */
  23845. void addButtonListener (ButtonListener* const newListener) throw();
  23846. /** Removes a previously-registered button listener
  23847. @see addButtonListener
  23848. */
  23849. void removeButtonListener (ButtonListener* const listener) throw();
  23850. /** Causes the button to act as if it's been clicked.
  23851. This will asynchronously make the button draw itself going down and up, and
  23852. will then call back the clicked() method as if mouse was clicked on it.
  23853. @see clicked
  23854. */
  23855. virtual void triggerClick();
  23856. /** Sets a command ID for this button to automatically invoke when it's clicked.
  23857. When the button is pressed, it will use the given manager to trigger the
  23858. command ID.
  23859. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  23860. before this button is. To disable the command triggering, call this method and
  23861. pass 0 for the parameters.
  23862. If generateTooltip is true, then the button's tooltip will be automatically
  23863. generated based on the name of this command and its current shortcut key.
  23864. @see addShortcut, getCommandID
  23865. */
  23866. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  23867. const int commandID,
  23868. const bool generateTooltip);
  23869. /** Returns the command ID that was set by setCommandToTrigger().
  23870. */
  23871. int getCommandID() const throw() { return commandID; }
  23872. /** Assigns a shortcut key to trigger the button.
  23873. The button registers itself with its top-level parent component for keypresses.
  23874. Note that a different way of linking buttons to keypresses is by using the
  23875. setCommandToTrigger() method to invoke a command.
  23876. @see clearShortcuts
  23877. */
  23878. void addShortcut (const KeyPress& key);
  23879. /** Removes all key shortcuts that had been set for this button.
  23880. @see addShortcut
  23881. */
  23882. void clearShortcuts();
  23883. /** Returns true if the given keypress is a shortcut for this button.
  23884. @see addShortcut
  23885. */
  23886. bool isRegisteredForShortcut (const KeyPress& key) const throw();
  23887. /** Sets an auto-repeat speed for the button when it is held down.
  23888. (Auto-repeat is disabled by default).
  23889. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  23890. triggering the next click. If this is zero, auto-repeat
  23891. is disabled
  23892. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  23893. triggered
  23894. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  23895. get faster, the longer the button is held down, up to the
  23896. minimum interval specified here
  23897. */
  23898. void setRepeatSpeed (const int initialDelayInMillisecs,
  23899. const int repeatDelayInMillisecs,
  23900. const int minimumDelayInMillisecs = -1) throw();
  23901. /** Sets whether the button click should happen when the mouse is pressed or released.
  23902. By default the button is only considered to have been clicked when the mouse is
  23903. released, but setting this to true will make it call the clicked() method as soon
  23904. as the button is pressed.
  23905. This is useful if the button is being used to show a pop-up menu, as it allows
  23906. the click to be used as a drag onto the menu.
  23907. */
  23908. void setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw();
  23909. /** Returns the number of milliseconds since the last time the button
  23910. went into the 'down' state.
  23911. */
  23912. uint32 getMillisecondsSinceButtonDown() const throw();
  23913. /** (overridden from Component to do special stuff). */
  23914. void setVisible (bool shouldBeVisible);
  23915. /** Sets the tooltip for this button.
  23916. @see TooltipClient, TooltipWindow
  23917. */
  23918. void setTooltip (const String& newTooltip);
  23919. // (implementation of the TooltipClient method)
  23920. const String getTooltip();
  23921. /** A combination of these flags are used by setConnectedEdges().
  23922. */
  23923. enum ConnectedEdgeFlags
  23924. {
  23925. ConnectedOnLeft = 1,
  23926. ConnectedOnRight = 2,
  23927. ConnectedOnTop = 4,
  23928. ConnectedOnBottom = 8
  23929. };
  23930. /** Hints about which edges of the button might be connected to adjoining buttons.
  23931. The value passed in is a bitwise combination of any of the values in the
  23932. ConnectedEdgeFlags enum.
  23933. E.g. if you are placing two buttons adjacent to each other, you could use this to
  23934. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  23935. without rounded corners on the edges that connect. It's only a hint, so the
  23936. LookAndFeel can choose to ignore it if it's not relevent for this type of
  23937. button.
  23938. */
  23939. void setConnectedEdges (const int connectedEdgeFlags) throw();
  23940. /** Returns the set of flags passed into setConnectedEdges(). */
  23941. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  23942. /** Indicates whether the button adjoins another one on its left edge.
  23943. @see setConnectedEdges
  23944. */
  23945. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  23946. /** Indicates whether the button adjoins another one on its right edge.
  23947. @see setConnectedEdges
  23948. */
  23949. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  23950. /** Indicates whether the button adjoins another one on its top edge.
  23951. @see setConnectedEdges
  23952. */
  23953. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  23954. /** Indicates whether the button adjoins another one on its bottom edge.
  23955. @see setConnectedEdges
  23956. */
  23957. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  23958. /** Used by setState(). */
  23959. enum ButtonState
  23960. {
  23961. buttonNormal,
  23962. buttonOver,
  23963. buttonDown
  23964. };
  23965. /** Can be used to force the button into a particular state.
  23966. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  23967. from happening.
  23968. The state that you set here will only last until it is automatically changed when the mouse
  23969. enters or exits the button, or the mouse-button is pressed or released.
  23970. */
  23971. void setState (const ButtonState newState);
  23972. juce_UseDebuggingNewOperator
  23973. protected:
  23974. /** This method is called when the button has been clicked.
  23975. Subclasses can override this to perform whatever they actions they need
  23976. to do.
  23977. Alternatively, a ButtonListener can be added to the button, and these listeners
  23978. will be called when the click occurs.
  23979. @see triggerClick
  23980. */
  23981. virtual void clicked();
  23982. /** This method is called when the button has been clicked.
  23983. By default it just calls clicked(), but you might want to override it to handle
  23984. things like clicking when a modifier key is pressed, etc.
  23985. @see ModifierKeys
  23986. */
  23987. virtual void clicked (const ModifierKeys& modifiers);
  23988. /** Subclasses should override this to actually paint the button's contents.
  23989. It's better to use this than the paint method, because it gives you information
  23990. about the over/down state of the button.
  23991. @param g the graphics context to use
  23992. @param isMouseOverButton true if the button is either in the 'over' or
  23993. 'down' state
  23994. @param isButtonDown true if the button should be drawn in the 'down' position
  23995. */
  23996. virtual void paintButton (Graphics& g,
  23997. bool isMouseOverButton,
  23998. bool isButtonDown) = 0;
  23999. /** Called when the button's up/down/over state changes.
  24000. Subclasses can override this if they need to do something special when the button
  24001. goes up or down.
  24002. @see isDown, isOver
  24003. */
  24004. virtual void buttonStateChanged();
  24005. /** @internal */
  24006. virtual void internalClickCallback (const ModifierKeys& modifiers);
  24007. /** @internal */
  24008. void handleCommandMessage (int commandId);
  24009. /** @internal */
  24010. void mouseEnter (const MouseEvent& e);
  24011. /** @internal */
  24012. void mouseExit (const MouseEvent& e);
  24013. /** @internal */
  24014. void mouseDown (const MouseEvent& e);
  24015. /** @internal */
  24016. void mouseDrag (const MouseEvent& e);
  24017. /** @internal */
  24018. void mouseUp (const MouseEvent& e);
  24019. /** @internal */
  24020. bool keyPressed (const KeyPress& key);
  24021. /** @internal */
  24022. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  24023. /** @internal */
  24024. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  24025. /** @internal */
  24026. void paint (Graphics& g);
  24027. /** @internal */
  24028. void parentHierarchyChanged();
  24029. /** @internal */
  24030. void focusGained (FocusChangeType cause);
  24031. /** @internal */
  24032. void focusLost (FocusChangeType cause);
  24033. /** @internal */
  24034. void enablementChanged();
  24035. /** @internal */
  24036. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  24037. /** @internal */
  24038. void applicationCommandListChanged();
  24039. private:
  24040. Array <KeyPress> shortcuts;
  24041. Component* keySource;
  24042. String text;
  24043. SortedSet <void*> buttonListeners;
  24044. friend class InternalButtonRepeatTimer;
  24045. ScopedPointer <Timer> repeatTimer;
  24046. uint32 buttonPressTime, lastTimeCallbackTime;
  24047. ApplicationCommandManager* commandManagerToUse;
  24048. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  24049. int radioGroupId, commandID, connectedEdgeFlags;
  24050. ButtonState buttonState;
  24051. bool isOn : 1;
  24052. bool clickTogglesState : 1;
  24053. bool needsToRelease : 1;
  24054. bool needsRepainting : 1;
  24055. bool isKeyDown : 1;
  24056. bool triggerOnMouseDown : 1;
  24057. bool generateTooltip : 1;
  24058. void repeatTimerCallback() throw();
  24059. Timer& getRepeatTimer() throw();
  24060. ButtonState updateState (const MouseEvent* const e) throw();
  24061. bool isShortcutPressed() const throw();
  24062. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  24063. void flashButtonState() throw();
  24064. void sendClickMessage (const ModifierKeys& modifiers);
  24065. void sendStateMessage();
  24066. Button (const Button&);
  24067. const Button& operator= (const Button&);
  24068. };
  24069. #endif // __JUCE_BUTTON_JUCEHEADER__
  24070. /********* End of inlined file: juce_Button.h *********/
  24071. class ScrollBar;
  24072. /**
  24073. A class for receiving events from a ScrollBar.
  24074. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  24075. method, and it will be called when the bar's position changes.
  24076. @see ScrollBar::addListener, ScrollBar::removeListener
  24077. */
  24078. class JUCE_API ScrollBarListener
  24079. {
  24080. public:
  24081. /** Destructor. */
  24082. virtual ~ScrollBarListener() {}
  24083. /** Called when a ScrollBar is moved.
  24084. @param scrollBarThatHasMoved the bar that has moved
  24085. @param newRangeStart the new range start of this bar
  24086. */
  24087. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  24088. const double newRangeStart) = 0;
  24089. };
  24090. /**
  24091. A scrollbar component.
  24092. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  24093. sets the range of values it can represent. Then you can use setCurrentRange() to
  24094. change the position and size of the scrollbar's 'thumb'.
  24095. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  24096. the user moves it, and you can use the getCurrentRangeStart() to find out where
  24097. they moved it to.
  24098. The scrollbar will adjust its own visibility according to whether its thumb size
  24099. allows it to actually be scrolled.
  24100. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  24101. instead of handling a scrollbar directly.
  24102. @see ScrollBarListener
  24103. */
  24104. class JUCE_API ScrollBar : public Component,
  24105. public AsyncUpdater,
  24106. private Timer
  24107. {
  24108. public:
  24109. /** Creates a Scrollbar.
  24110. @param isVertical whether it should be a vertical or horizontal bar
  24111. @param buttonsAreVisible whether to show the up/down or left/right buttons
  24112. */
  24113. ScrollBar (const bool isVertical,
  24114. const bool buttonsAreVisible = true);
  24115. /** Destructor. */
  24116. ~ScrollBar();
  24117. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  24118. bool isVertical() const throw() { return vertical; }
  24119. /** Changes the scrollbar's direction.
  24120. You'll also need to resize the bar appropriately - this just changes its internal
  24121. layout.
  24122. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  24123. */
  24124. void setOrientation (const bool shouldBeVertical) throw();
  24125. /** Shows or hides the scrollbar's buttons. */
  24126. void setButtonVisibility (const bool buttonsAreVisible);
  24127. /** Tells the scrollbar whether to make itself invisible when not needed.
  24128. The default behaviour is for a scrollbar to become invisible when the thumb
  24129. fills the whole of its range (i.e. when it can't be moved). Setting this
  24130. value to false forces the bar to always be visible.
  24131. */
  24132. void setAutoHide (const bool shouldHideWhenFullRange);
  24133. /** Sets the minimum and maximum values that the bar will move between.
  24134. The bar's thumb will always be constrained so that the top of the thumb
  24135. will be >= minimum, and the bottom of the thumb <= maximum.
  24136. @see setCurrentRange
  24137. */
  24138. void setRangeLimits (const double minimum,
  24139. const double maximum) throw();
  24140. /** Returns the lower value that the thumb can be set to.
  24141. This is the value set by setRangeLimits().
  24142. */
  24143. double getMinimumRangeLimit() const throw() { return minimum; }
  24144. /** Returns the upper value that the thumb can be set to.
  24145. This is the value set by setRangeLimits().
  24146. */
  24147. double getMaximumRangeLimit() const throw() { return maximum; }
  24148. /** Changes the position of the scrollbar's 'thumb'.
  24149. This sets both the position and size of the thumb - to just set the position without
  24150. changing the size, you can use setCurrentRangeStart().
  24151. If this method call actually changes the scrollbar's position, it will trigger an
  24152. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  24153. are registered.
  24154. @param newStart the top (or left) of the thumb, in the range
  24155. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  24156. value is beyond these limits, it will be clipped.
  24157. @param newSize the size of the thumb, such that
  24158. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  24159. size is beyond these limits, it will be clipped.
  24160. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  24161. */
  24162. void setCurrentRange (double newStart,
  24163. double newSize) throw();
  24164. /** Moves the bar's thumb position.
  24165. This will move the thumb position without changing the thumb size. Note
  24166. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  24167. If this method call actually changes the scrollbar's position, it will trigger an
  24168. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  24169. are registered.
  24170. @see setCurrentRange
  24171. */
  24172. void setCurrentRangeStart (double newStart) throw();
  24173. /** Returns the position of the top of the thumb.
  24174. @see setCurrentRangeStart
  24175. */
  24176. double getCurrentRangeStart() const throw() { return rangeStart; }
  24177. /** Returns the current size of the thumb.
  24178. @see setCurrentRange
  24179. */
  24180. double getCurrentRangeSize() const throw() { return rangeSize; }
  24181. /** Sets the amount by which the up and down buttons will move the bar.
  24182. The value here is in terms of the total range, and is added or subtracted
  24183. from the thumb position when the user clicks an up/down (or left/right) button.
  24184. */
  24185. void setSingleStepSize (const double newSingleStepSize) throw();
  24186. /** Moves the scrollbar by a number of single-steps.
  24187. This will move the bar by a multiple of its single-step interval (as
  24188. specified using the setSingleStepSize() method).
  24189. A positive value here will move the bar down or to the right, a negative
  24190. value moves it up or to the left.
  24191. */
  24192. void moveScrollbarInSteps (const int howManySteps) throw();
  24193. /** Moves the scroll bar up or down in pages.
  24194. This will move the bar by a multiple of its current thumb size, effectively
  24195. doing a page-up or down.
  24196. A positive value here will move the bar down or to the right, a negative
  24197. value moves it up or to the left.
  24198. */
  24199. void moveScrollbarInPages (const int howManyPages) throw();
  24200. /** Scrolls to the top (or left).
  24201. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  24202. */
  24203. void scrollToTop() throw();
  24204. /** Scrolls to the bottom (or right).
  24205. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  24206. */
  24207. void scrollToBottom() throw();
  24208. /** Changes the delay before the up and down buttons autorepeat when they are held
  24209. down.
  24210. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  24211. @see Button::setRepeatSpeed
  24212. */
  24213. void setButtonRepeatSpeed (const int initialDelayInMillisecs,
  24214. const int repeatDelayInMillisecs,
  24215. const int minimumDelayInMillisecs = -1) throw();
  24216. /** A set of colour IDs to use to change the colour of various aspects of the component.
  24217. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24218. methods.
  24219. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24220. */
  24221. enum ColourIds
  24222. {
  24223. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  24224. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  24225. 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. */
  24226. };
  24227. /** Registers a listener that will be called when the scrollbar is moved. */
  24228. void addListener (ScrollBarListener* const listener) throw();
  24229. /** Deregisters a previously-registered listener. */
  24230. void removeListener (ScrollBarListener* const listener) throw();
  24231. /** @internal */
  24232. bool keyPressed (const KeyPress& key);
  24233. /** @internal */
  24234. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24235. /** @internal */
  24236. void lookAndFeelChanged();
  24237. /** @internal */
  24238. void handleAsyncUpdate();
  24239. /** @internal */
  24240. void mouseDown (const MouseEvent& e);
  24241. /** @internal */
  24242. void mouseDrag (const MouseEvent& e);
  24243. /** @internal */
  24244. void mouseUp (const MouseEvent& e);
  24245. /** @internal */
  24246. void paint (Graphics& g);
  24247. /** @internal */
  24248. void resized();
  24249. juce_UseDebuggingNewOperator
  24250. private:
  24251. double minimum, maximum;
  24252. double rangeStart, rangeSize;
  24253. double singleStepSize, dragStartRange;
  24254. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  24255. int dragStartMousePos, lastMousePos;
  24256. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  24257. bool vertical, isDraggingThumb, alwaysVisible;
  24258. Button* upButton;
  24259. Button* downButton;
  24260. SortedSet <void*> listeners;
  24261. void updateThumbPosition() throw();
  24262. void timerCallback();
  24263. ScrollBar (const ScrollBar&);
  24264. const ScrollBar& operator= (const ScrollBar&);
  24265. };
  24266. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  24267. /********* End of inlined file: juce_ScrollBar.h *********/
  24268. /**
  24269. A Viewport is used to contain a larger child component, and allows the child
  24270. to be automatically scrolled around.
  24271. To use a Viewport, just create one and set the component that goes inside it
  24272. using the setViewedComponent() method. When the child component changes size,
  24273. the Viewport will adjust its scrollbars accordingly.
  24274. A subclass of the viewport can be created which will receive calls to its
  24275. visibleAreaChanged() method when the subcomponent changes position or size.
  24276. */
  24277. class JUCE_API Viewport : public Component,
  24278. private ComponentListener,
  24279. private ScrollBarListener
  24280. {
  24281. public:
  24282. /** Creates a Viewport.
  24283. The viewport is initially empty - use the setViewedComponent() method to
  24284. add a child component for it to manage.
  24285. */
  24286. Viewport (const String& componentName = String::empty);
  24287. /** Destructor. */
  24288. ~Viewport();
  24289. /** Sets the component that this viewport will contain and scroll around.
  24290. This will add the given component to this Viewport and position it at
  24291. (0, 0).
  24292. (Don't add or remove any child components directly using the normal
  24293. Component::addChildComponent() methods).
  24294. @param newViewedComponent the component to add to this viewport (this pointer
  24295. may be null). The component passed in will be deleted
  24296. by the Viewport when it's no longer needed
  24297. @see getViewedComponent
  24298. */
  24299. void setViewedComponent (Component* const newViewedComponent);
  24300. /** Returns the component that's currently being used inside the Viewport.
  24301. @see setViewedComponent
  24302. */
  24303. Component* getViewedComponent() const throw() { return contentComp; }
  24304. /** Changes the position of the viewed component.
  24305. The inner component will be moved so that the pixel at the top left of
  24306. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  24307. within the inner component.
  24308. This will update the scrollbars and might cause a call to visibleAreaChanged().
  24309. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  24310. */
  24311. void setViewPosition (const int xPixelsOffset,
  24312. const int yPixelsOffset);
  24313. /** Changes the view position as a proportion of the distance it can move.
  24314. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  24315. visible area in the top-left, and (1, 1) would put it as far down and
  24316. to the right as it's possible to go whilst keeping the child component
  24317. on-screen.
  24318. */
  24319. void setViewPositionProportionately (const double proportionX,
  24320. const double proportionY);
  24321. /** If the specified position is at the edges of the viewport, this method scrolls
  24322. the viewport to bring that position nearer to the centre.
  24323. Call this if you're dragging an object inside a viewport and want to make it scroll
  24324. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  24325. useful when auto-scrolling.
  24326. @param mouseX the x position, relative to the Viewport's top-left
  24327. @param mouseY the y position, relative to the Viewport's top-left
  24328. @param distanceFromEdge specifies how close to an edge the position needs to be
  24329. before the viewport should scroll in that direction
  24330. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  24331. to scroll by.
  24332. @returns true if the viewport was scrolled
  24333. */
  24334. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  24335. /** Returns the position within the child component of the top-left of its visible area.
  24336. @see getViewWidth, setViewPosition
  24337. */
  24338. int getViewPositionX() const throw() { return lastVX; }
  24339. /** Returns the position within the child component of the top-left of its visible area.
  24340. @see getViewHeight, setViewPosition
  24341. */
  24342. int getViewPositionY() const throw() { return lastVY; }
  24343. /** Returns the width of the visible area of the child component.
  24344. This may be less than the width of this Viewport if there's a vertical scrollbar
  24345. or if the child component is itself smaller.
  24346. */
  24347. int getViewWidth() const throw() { return lastVW; }
  24348. /** Returns the height of the visible area of the child component.
  24349. This may be less than the height of this Viewport if there's a horizontal scrollbar
  24350. or if the child component is itself smaller.
  24351. */
  24352. int getViewHeight() const throw() { return lastVH; }
  24353. /** Returns the width available within this component for the contents.
  24354. This will be the width of the viewport component minus the width of a
  24355. vertical scrollbar (if visible).
  24356. */
  24357. int getMaximumVisibleWidth() const throw();
  24358. /** Returns the height available within this component for the contents.
  24359. This will be the height of the viewport component minus the space taken up
  24360. by a horizontal scrollbar (if visible).
  24361. */
  24362. int getMaximumVisibleHeight() const throw();
  24363. /** Callback method that is called when the visible area changes.
  24364. This will be called when the visible area is moved either be scrolling or
  24365. by calls to setViewPosition(), etc.
  24366. */
  24367. virtual void visibleAreaChanged (int visibleX, int visibleY,
  24368. int visibleW, int visibleH);
  24369. /** Turns scrollbars on or off.
  24370. If set to false, the scrollbars won't ever appear. When true (the default)
  24371. they will appear only when needed.
  24372. */
  24373. void setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  24374. const bool showHorizontalScrollbarIfNeeded);
  24375. /** True if the vertical scrollbar is enabled.
  24376. @see setScrollBarsShown
  24377. */
  24378. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  24379. /** True if the horizontal scrollbar is enabled.
  24380. @see setScrollBarsShown
  24381. */
  24382. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  24383. /** Changes the width of the scrollbars.
  24384. If this isn't specified, the default width from the LookAndFeel class will be used.
  24385. @see LookAndFeel::getDefaultScrollbarWidth
  24386. */
  24387. void setScrollBarThickness (const int thickness);
  24388. /** Returns the thickness of the scrollbars.
  24389. @see setScrollBarThickness
  24390. */
  24391. int getScrollBarThickness() const throw();
  24392. /** Changes the distance that a single-step click on a scrollbar button
  24393. will move the viewport.
  24394. */
  24395. void setSingleStepSizes (const int stepX, const int stepY);
  24396. /** Shows or hides the buttons on any scrollbars that are used.
  24397. @see ScrollBar::setButtonVisibility
  24398. */
  24399. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24400. /** Returns a pointer to the scrollbar component being used.
  24401. Handy if you need to customise the bar somehow.
  24402. */
  24403. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  24404. /** Returns a pointer to the scrollbar component being used.
  24405. Handy if you need to customise the bar somehow.
  24406. */
  24407. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  24408. juce_UseDebuggingNewOperator
  24409. /** @internal */
  24410. void resized();
  24411. /** @internal */
  24412. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  24413. /** @internal */
  24414. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24415. /** @internal */
  24416. bool keyPressed (const KeyPress& key);
  24417. /** @internal */
  24418. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  24419. /** @internal */
  24420. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  24421. private:
  24422. Component* contentComp;
  24423. int lastVX, lastVY, lastVW, lastVH;
  24424. int scrollBarThickness;
  24425. int singleStepX, singleStepY;
  24426. bool showHScrollbar, showVScrollbar;
  24427. Component* contentHolder;
  24428. ScrollBar* verticalScrollBar;
  24429. ScrollBar* horizontalScrollBar;
  24430. void updateVisibleRegion();
  24431. Viewport (const Viewport&);
  24432. const Viewport& operator= (const Viewport&);
  24433. };
  24434. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  24435. /********* End of inlined file: juce_Viewport.h *********/
  24436. /********* Start of inlined file: juce_PopupMenu.h *********/
  24437. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  24438. #define __JUCE_POPUPMENU_JUCEHEADER__
  24439. /********* Start of inlined file: juce_PopupMenuCustomComponent.h *********/
  24440. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  24441. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  24442. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  24443. @see PopupMenu::addCustomItem
  24444. */
  24445. class JUCE_API PopupMenuCustomComponent : public Component
  24446. {
  24447. public:
  24448. /** Destructor. */
  24449. ~PopupMenuCustomComponent();
  24450. /** Chooses the size that this component would like to have.
  24451. Note that the size which this method returns isn't necessarily the one that
  24452. the menu will give it, as it will be stretched to fit the other items in
  24453. the menu.
  24454. */
  24455. virtual void getIdealSize (int& idealWidth,
  24456. int& idealHeight) = 0;
  24457. /** Dismisses the menu indicating that this item has been chosen.
  24458. This will cause the menu to exit from its modal state, returning
  24459. this item's id as the result.
  24460. */
  24461. void triggerMenuItem();
  24462. /** Returns true if this item should be highlighted because the mouse is
  24463. over it.
  24464. You can call this method in your paint() method to find out whether
  24465. to draw a highlight.
  24466. */
  24467. bool isItemHighlighted() const throw() { return isHighlighted; }
  24468. protected:
  24469. /** Constructor.
  24470. If isTriggeredAutomatically is true, then the menu will automatically detect
  24471. a click on this component and use that to trigger it. If it's false, then it's
  24472. up to your class to manually trigger the item if it wants to.
  24473. */
  24474. PopupMenuCustomComponent (const bool isTriggeredAutomatically = true);
  24475. private:
  24476. friend class MenuItemInfo;
  24477. friend class MenuItemComponent;
  24478. friend class PopupMenuWindow;
  24479. int refCount_;
  24480. bool isHighlighted, isTriggeredAutomatically;
  24481. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  24482. const PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  24483. };
  24484. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  24485. /********* End of inlined file: juce_PopupMenuCustomComponent.h *********/
  24486. /** Creates and displays a popup-menu.
  24487. To show a popup-menu, you create one of these, add some items to it, then
  24488. call its show() method, which returns the id of the item the user selects.
  24489. E.g. @code
  24490. void MyWidget::mouseDown (const MouseEvent& e)
  24491. {
  24492. PopupMenu m;
  24493. m.addItem (1, "item 1");
  24494. m.addItem (2, "item 2");
  24495. const int result = m.show();
  24496. if (result == 0)
  24497. {
  24498. // user dismissed the menu without picking anything
  24499. }
  24500. else if (result == 1)
  24501. {
  24502. // user picked item 1
  24503. }
  24504. else if (result == 2)
  24505. {
  24506. // user picked item 2
  24507. }
  24508. }
  24509. @endcode
  24510. Submenus are easy too: @code
  24511. void MyWidget::mouseDown (const MouseEvent& e)
  24512. {
  24513. PopupMenu subMenu;
  24514. subMenu.addItem (1, "item 1");
  24515. subMenu.addItem (2, "item 2");
  24516. PopupMenu mainMenu;
  24517. mainMenu.addItem (3, "item 3");
  24518. mainMenu.addSubMenu ("other choices", subMenu);
  24519. const int result = m.show();
  24520. ...etc
  24521. }
  24522. @endcode
  24523. */
  24524. class JUCE_API PopupMenu
  24525. {
  24526. public:
  24527. /** Creates an empty popup menu. */
  24528. PopupMenu() throw();
  24529. /** Creates a copy of another menu. */
  24530. PopupMenu (const PopupMenu& other) throw();
  24531. /** Destructor. */
  24532. ~PopupMenu() throw();
  24533. /** Copies this menu from another one. */
  24534. const PopupMenu& operator= (const PopupMenu& other) throw();
  24535. /** Resets the menu, removing all its items. */
  24536. void clear() throw();
  24537. /** Appends a new text item for this menu to show.
  24538. @param itemResultId the number that will be returned from the show() method
  24539. if the user picks this item. The value should never be
  24540. zero, because that's used to indicate that the user didn't
  24541. select anything.
  24542. @param itemText the text to show.
  24543. @param isActive if false, the item will be shown 'greyed-out' and can't be
  24544. picked
  24545. @param isTicked if true, the item will be shown with a tick next to it
  24546. @param iconToUse if this is non-zero, it should be an image that will be
  24547. displayed to the left of the item. This method will take its
  24548. own copy of the image passed-in, so there's no need to keep
  24549. it hanging around.
  24550. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  24551. */
  24552. void addItem (const int itemResultId,
  24553. const String& itemText,
  24554. const bool isActive = true,
  24555. const bool isTicked = false,
  24556. const Image* const iconToUse = 0) throw();
  24557. /** Adds an item that represents one of the commands in a command manager object.
  24558. @param commandManager the manager to use to trigger the command and get information
  24559. about it
  24560. @param commandID the ID of the command
  24561. @param displayName if this is non-empty, then this string will be used instead of
  24562. the command's registered name
  24563. */
  24564. void addCommandItem (ApplicationCommandManager* commandManager,
  24565. const int commandID,
  24566. const String& displayName = String::empty) throw();
  24567. /** Appends a text item with a special colour.
  24568. This is the same as addItem(), but specifies a colour to use for the
  24569. text, which will override the default colours that are used by the
  24570. current look-and-feel. See addItem() for a description of the parameters.
  24571. */
  24572. void addColouredItem (const int itemResultId,
  24573. const String& itemText,
  24574. const Colour& itemTextColour,
  24575. const bool isActive = true,
  24576. const bool isTicked = false,
  24577. const Image* const iconToUse = 0) throw();
  24578. /** Appends a custom menu item.
  24579. This will add a user-defined component to use as a menu item. The component
  24580. passed in will be deleted by this menu when it's no longer needed.
  24581. @see PopupMenuCustomComponent
  24582. */
  24583. void addCustomItem (const int itemResultId,
  24584. PopupMenuCustomComponent* const customComponent) throw();
  24585. /** Appends a custom menu item that can't be used to trigger a result.
  24586. This will add a user-defined component to use as a menu item. Unlike the
  24587. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  24588. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  24589. delete the component when it's finished, so it's the caller's responsibility
  24590. to manage the component that is passed-in.
  24591. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  24592. detection of a mouse-click on your component, and use that to trigger the
  24593. menu ID specified in itemResultId. If this is false, the menu item can't
  24594. be triggered, so itemResultId is not used.
  24595. @see PopupMenuCustomComponent
  24596. */
  24597. void addCustomItem (const int itemResultId,
  24598. Component* customComponent,
  24599. int idealWidth, int idealHeight,
  24600. const bool triggerMenuItemAutomaticallyWhenClicked) throw();
  24601. /** Appends a sub-menu.
  24602. If the menu that's passed in is empty, it will appear as an inactive item.
  24603. */
  24604. void addSubMenu (const String& subMenuName,
  24605. const PopupMenu& subMenu,
  24606. const bool isActive = true,
  24607. Image* const iconToUse = 0,
  24608. const bool isTicked = false) throw();
  24609. /** Appends a separator to the menu, to help break it up into sections.
  24610. The menu class is smart enough not to display separators at the top or bottom
  24611. of the menu, and it will replace mutliple adjacent separators with a single
  24612. one, so your code can be quite free and easy about adding these, and it'll
  24613. always look ok.
  24614. */
  24615. void addSeparator() throw();
  24616. /** Adds a non-clickable text item to the menu.
  24617. This is a bold-font items which can be used as a header to separate the items
  24618. into named groups.
  24619. */
  24620. void addSectionHeader (const String& title) throw();
  24621. /** Returns the number of items that the menu currently contains.
  24622. (This doesn't count separators).
  24623. */
  24624. int getNumItems() const throw();
  24625. /** Returns true if the menu contains a command item that triggers the given command. */
  24626. bool containsCommandItem (const int commandID) const throw();
  24627. /** Returns true if the menu contains any items that can be used. */
  24628. bool containsAnyActiveItems() const throw();
  24629. /** Displays the menu and waits for the user to pick something.
  24630. This will display the menu modally, and return the ID of the item that the
  24631. user picks. If they click somewhere off the menu to get rid of it without
  24632. choosing anything, this will return 0.
  24633. The current location of the mouse will be used as the position to show the
  24634. menu - to explicitly set the menu's position, use showAt() instead. Depending
  24635. on where this point is on the screen, the menu will appear above, below or
  24636. to the side of the point.
  24637. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  24638. then when the menu first appears, it will make sure
  24639. that this item is visible. So if the menu has too many
  24640. items to fit on the screen, it will be scrolled to a
  24641. position where this item is visible.
  24642. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  24643. than this if some items are too long to fit.
  24644. @param maximumNumColumns if there are too many items to fit on-screen in a single
  24645. vertical column, the menu may be laid out as a series of
  24646. columns - this is the maximum number allowed. To use the
  24647. default value for this (probably about 7), you can pass
  24648. in zero.
  24649. @param standardItemHeight if this is non-zero, it will be used as the standard
  24650. height for menu items (apart from custom items)
  24651. @see showAt
  24652. */
  24653. int show (const int itemIdThatMustBeVisible = 0,
  24654. const int minimumWidth = 0,
  24655. const int maximumNumColumns = 0,
  24656. const int standardItemHeight = 0);
  24657. /** Displays the menu at a specific location.
  24658. This is the same as show(), but uses a specific location (in global screen
  24659. co-ordinates) rather than the current mouse position.
  24660. Note that the co-ordinates don't specify the top-left of the menu - they
  24661. indicate a point of interest, and the menu will position itself nearby to
  24662. this point, trying to keep it fully on-screen.
  24663. @see show()
  24664. */
  24665. int showAt (const int screenX,
  24666. const int screenY,
  24667. const int itemIdThatMustBeVisible = 0,
  24668. const int minimumWidth = 0,
  24669. const int maximumNumColumns = 0,
  24670. const int standardItemHeight = 0);
  24671. /** Displays the menu as if it's attached to a component such as a button.
  24672. This is similar to showAt(), but will position it next to the given component, e.g.
  24673. so that the menu's edge is aligned with that of the component. This is intended for
  24674. things like buttons that trigger a pop-up menu.
  24675. */
  24676. int showAt (Component* componentToAttachTo,
  24677. const int itemIdThatMustBeVisible = 0,
  24678. const int minimumWidth = 0,
  24679. const int maximumNumColumns = 0,
  24680. const int standardItemHeight = 0);
  24681. /** Closes any menus that are currently open.
  24682. This might be useful if you have a situation where your window is being closed
  24683. by some means other than a user action, and you'd like to make sure that menus
  24684. aren't left hanging around.
  24685. */
  24686. static void JUCE_CALLTYPE dismissAllActiveMenus() throw();
  24687. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  24688. This can be called before show() if you need a customised menu. Be careful
  24689. not to delete the LookAndFeel object before the menu has been deleted.
  24690. */
  24691. void setLookAndFeel (LookAndFeel* const newLookAndFeel) throw();
  24692. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  24693. These constants can be used either via the LookAndFeel::setColour()
  24694. method for the look and feel that is set for this menu with setLookAndFeel()
  24695. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  24696. */
  24697. enum ColourIds
  24698. {
  24699. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  24700. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  24701. colour is specified when the item is added). */
  24702. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  24703. addSectionHeader() method). */
  24704. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  24705. highlighted menu item. */
  24706. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  24707. highlighted item. */
  24708. };
  24709. /**
  24710. Allows you to iterate through the items in a pop-up menu, and examine
  24711. their properties.
  24712. To use this, just create one and repeatedly call its next() method. When this
  24713. returns true, all the member variables of the iterator are filled-out with
  24714. information describing the menu item. When it returns false, the end of the
  24715. list has been reached.
  24716. */
  24717. class JUCE_API MenuItemIterator
  24718. {
  24719. public:
  24720. /** Creates an iterator that will scan through the items in the specified
  24721. menu.
  24722. Be careful not to add any items to a menu while it is being iterated,
  24723. or things could get out of step.
  24724. */
  24725. MenuItemIterator (const PopupMenu& menu) throw();
  24726. /** Destructor. */
  24727. ~MenuItemIterator() throw();
  24728. /** Returns true if there is another item, and sets up all this object's
  24729. member variables to reflect that item's properties.
  24730. */
  24731. bool next() throw();
  24732. String itemName;
  24733. const PopupMenu* subMenu;
  24734. int itemId;
  24735. bool isSeparator;
  24736. bool isTicked;
  24737. bool isEnabled;
  24738. bool isCustomComponent;
  24739. bool isSectionHeader;
  24740. const Colour* customColour;
  24741. const Image* customImage;
  24742. ApplicationCommandManager* commandManager;
  24743. juce_UseDebuggingNewOperator
  24744. private:
  24745. const PopupMenu& menu;
  24746. int index;
  24747. MenuItemIterator (const MenuItemIterator&);
  24748. const MenuItemIterator& operator= (const MenuItemIterator&);
  24749. };
  24750. juce_UseDebuggingNewOperator
  24751. private:
  24752. friend class PopupMenuWindow;
  24753. friend class MenuItemIterator;
  24754. VoidArray items;
  24755. LookAndFeel* lookAndFeel;
  24756. bool separatorPending;
  24757. void addSeparatorIfPending();
  24758. int showMenu (const int x, const int y, const int w, const int h,
  24759. const int itemIdThatMustBeVisible,
  24760. const int minimumWidth,
  24761. const int maximumNumColumns,
  24762. const int standardItemHeight,
  24763. const bool alignToRectangle,
  24764. Component* const componentAttachedTo) throw();
  24765. friend class MenuBarComponent;
  24766. Component* createMenuComponent (const int x, const int y, const int w, const int h,
  24767. const int itemIdThatMustBeVisible,
  24768. const int minimumWidth,
  24769. const int maximumNumColumns,
  24770. const int standardItemHeight,
  24771. const bool alignToRectangle,
  24772. Component* menuBarComponent,
  24773. ApplicationCommandManager** managerOfChosenCommand,
  24774. Component* const componentAttachedTo) throw();
  24775. };
  24776. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  24777. /********* End of inlined file: juce_PopupMenu.h *********/
  24778. class TextEditor;
  24779. class TextHolderComponent;
  24780. /**
  24781. Receives callbacks from a TextEditor component when it changes.
  24782. @see TextEditor::addListener
  24783. */
  24784. class JUCE_API TextEditorListener
  24785. {
  24786. public:
  24787. /** Destructor. */
  24788. virtual ~TextEditorListener() {}
  24789. /** Called when the user changes the text in some way. */
  24790. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  24791. /** Called when the user presses the return key. */
  24792. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  24793. /** Called when the user presses the escape key. */
  24794. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  24795. /** Called when the text editor loses focus. */
  24796. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  24797. };
  24798. /**
  24799. A component containing text that can be edited.
  24800. A TextEditor can either be in single- or multi-line mode, and supports mixed
  24801. fonts and colours.
  24802. @see TextEditorListener, Label
  24803. */
  24804. class JUCE_API TextEditor : public Component,
  24805. public SettableTooltipClient
  24806. {
  24807. public:
  24808. /** Creates a new, empty text editor.
  24809. @param componentName the name to pass to the component for it to use as its name
  24810. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24811. for all characters that are drawn on screen - e.g. to create
  24812. a password-style textbox containing circular blobs instead of text,
  24813. you could set this value to 0x25cf, which is the unicode character
  24814. for a black splodge (not all fonts include this, though), or 0x2022,
  24815. which is a bullet (probably the best choice for linux).
  24816. */
  24817. TextEditor (const String& componentName = String::empty,
  24818. const tchar passwordCharacter = 0);
  24819. /** Destructor. */
  24820. virtual ~TextEditor();
  24821. /** Puts the editor into either multi- or single-line mode.
  24822. By default, the editor will be in single-line mode, so use this if you need a multi-line
  24823. editor.
  24824. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  24825. on if you want a multi-line editor with line-breaks.
  24826. @see isMultiLine, setReturnKeyStartsNewLine
  24827. */
  24828. void setMultiLine (const bool shouldBeMultiLine,
  24829. const bool shouldWordWrap = true);
  24830. /** Returns true if the editor is in multi-line mode.
  24831. */
  24832. bool isMultiLine() const throw();
  24833. /** Changes the behaviour of the return key.
  24834. If set to true, the return key will insert a new-line into the text; if false
  24835. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  24836. method. By default this is set to false, and when true it will only insert
  24837. new-lines when in multi-line mode (see setMultiLine()).
  24838. */
  24839. void setReturnKeyStartsNewLine (const bool shouldStartNewLine);
  24840. /** Returns the value set by setReturnKeyStartsNewLine().
  24841. See setReturnKeyStartsNewLine() for more info.
  24842. */
  24843. bool getReturnKeyStartsNewLine() const throw() { return returnKeyStartsNewLine; }
  24844. /** Indicates whether the tab key should be accepted and used to input a tab character,
  24845. or whether it gets ignored.
  24846. By default the tab key is ignored, so that it can be used to switch keyboard focus
  24847. between components.
  24848. */
  24849. void setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw();
  24850. /** Returns true if the tab key is being used for input.
  24851. @see setTabKeyUsedAsCharacter
  24852. */
  24853. bool isTabKeyUsedAsCharacter() const throw() { return tabKeyUsed; }
  24854. /** Changes the editor to read-only mode.
  24855. By default, the text editor is not read-only. If you're making it read-only, you
  24856. might also want to call setCaretVisible (false) to get rid of the caret.
  24857. The text can still be highlighted and copied when in read-only mode.
  24858. @see isReadOnly, setCaretVisible
  24859. */
  24860. void setReadOnly (const bool shouldBeReadOnly);
  24861. /** Returns true if the editor is in read-only mode.
  24862. */
  24863. bool isReadOnly() const throw();
  24864. /** Makes the caret visible or invisible.
  24865. By default the caret is visible.
  24866. @see setCaretColour, setCaretPosition
  24867. */
  24868. void setCaretVisible (const bool shouldBeVisible) throw();
  24869. /** Returns true if the caret is enabled.
  24870. @see setCaretVisible
  24871. */
  24872. bool isCaretVisible() const throw() { return caretVisible; }
  24873. /** Enables/disables a vertical scrollbar.
  24874. (This only applies when in multi-line mode). When the text gets too long to fit
  24875. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  24876. this is enabled, the scrollbar will be hidden unless it's needed.
  24877. By default the scrollbar is enabled.
  24878. */
  24879. void setScrollbarsShown (bool shouldBeEnabled) throw();
  24880. /** Returns true if scrollbars are enabled.
  24881. @see setScrollbarsShown
  24882. */
  24883. bool areScrollbarsShown() const throw() { return scrollbarVisible; }
  24884. /** Changes the password character used to disguise the text.
  24885. @param passwordCharacter if this is not zero, this character will be used as a replacement
  24886. for all characters that are drawn on screen - e.g. to create
  24887. a password-style textbox containing circular blobs instead of text,
  24888. you could set this value to 0x25cf, which is the unicode character
  24889. for a black splodge (not all fonts include this, though), or 0x2022,
  24890. which is a bullet (probably the best choice for linux).
  24891. */
  24892. void setPasswordCharacter (const tchar passwordCharacter) throw();
  24893. /** Returns the current password character.
  24894. @see setPasswordCharacter
  24895. l */
  24896. tchar getPasswordCharacter() const throw() { return passwordCharacter; }
  24897. /** Allows a right-click menu to appear for the editor.
  24898. (This defaults to being enabled).
  24899. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  24900. of options such as cut/copy/paste, undo/redo, etc.
  24901. */
  24902. void setPopupMenuEnabled (const bool menuEnabled) throw();
  24903. /** Returns true if the right-click menu is enabled.
  24904. @see setPopupMenuEnabled
  24905. */
  24906. bool isPopupMenuEnabled() const throw() { return popupMenuEnabled; }
  24907. /** Returns true if a popup-menu is currently being displayed.
  24908. */
  24909. bool isPopupMenuCurrentlyActive() const throw() { return menuActive; }
  24910. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  24911. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24912. methods.
  24913. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24914. */
  24915. enum ColourIds
  24916. {
  24917. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  24918. transparent if necessary. */
  24919. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  24920. that because the editor can contain multiple colours, calling this
  24921. method won't change the colour of existing text - to do that, call
  24922. applyFontToAllText() after calling this method.*/
  24923. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  24924. the text - this can be transparent if you don't want to show any
  24925. highlighting.*/
  24926. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  24927. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  24928. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  24929. the edge of the component. */
  24930. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  24931. the edge of the component when it has focus. */
  24932. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  24933. around the edge of the editor. */
  24934. };
  24935. /** Sets the font to use for newly added text.
  24936. This will change the font that will be used next time any text is added or entered
  24937. into the editor. It won't change the font of any existing text - to do that, use
  24938. applyFontToAllText() instead.
  24939. @see applyFontToAllText
  24940. */
  24941. void setFont (const Font& newFont) throw();
  24942. /** Applies a font to all the text in the editor.
  24943. This will also set the current font to use for any new text that's added.
  24944. @see setFont
  24945. */
  24946. void applyFontToAllText (const Font& newFont);
  24947. /** Returns the font that's currently being used for new text.
  24948. @see setFont
  24949. */
  24950. const Font getFont() const throw();
  24951. /** If set to true, focusing on the editor will highlight all its text.
  24952. (Set to false by default).
  24953. This is useful for boxes where you expect the user to re-enter all the
  24954. text when they focus on the component, rather than editing what's already there.
  24955. */
  24956. void setSelectAllWhenFocused (const bool b) throw();
  24957. /** Sets limits on the characters that can be entered.
  24958. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  24959. limit is set
  24960. @param allowedCharacters if this is non-empty, then only characters that occur in
  24961. this string are allowed to be entered into the editor.
  24962. */
  24963. void setInputRestrictions (const int maxTextLength,
  24964. const String& allowedCharacters = String::empty) throw();
  24965. /** When the text editor is empty, it can be set to display a message.
  24966. This is handy for things like telling the user what to type in the box - the
  24967. string is only displayed, it's not taken to actually be the contents of
  24968. the editor.
  24969. */
  24970. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw();
  24971. /** Changes the size of the scrollbars that are used.
  24972. Handy if you need smaller scrollbars for a small text box.
  24973. */
  24974. void setScrollBarThickness (const int newThicknessPixels);
  24975. /** Shows or hides the buttons on any scrollbars that are used.
  24976. @see ScrollBar::setButtonVisibility
  24977. */
  24978. void setScrollBarButtonVisibility (const bool buttonsVisible);
  24979. /** Registers a listener to be told when things happen to the text.
  24980. @see removeListener
  24981. */
  24982. void addListener (TextEditorListener* const newListener) throw();
  24983. /** Deregisters a listener.
  24984. @see addListener
  24985. */
  24986. void removeListener (TextEditorListener* const listenerToRemove) throw();
  24987. /** Returns the entire contents of the editor. */
  24988. const String getText() const throw();
  24989. /** Returns a section of the contents of the editor. */
  24990. const String getTextSubstring (const int startCharacter, const int endCharacter) const throw();
  24991. /** Returns true if there are no characters in the editor.
  24992. This is more efficient than calling getText().isEmpty().
  24993. */
  24994. bool isEmpty() const throw();
  24995. /** Sets the entire content of the editor.
  24996. This will clear the editor and insert the given text (using the current text colour
  24997. and font). You can set the current text colour using
  24998. @code setColour (TextEditor::textColourId, ...);
  24999. @endcode
  25000. @param newText the text to add
  25001. @param sendTextChangeMessage if true, this will cause a change message to
  25002. be sent to all the listeners.
  25003. @see insertText
  25004. */
  25005. void setText (const String& newText,
  25006. const bool sendTextChangeMessage = true);
  25007. /** Inserts some text at the current cursor position.
  25008. If a section of the text is highlighted, it will be replaced by
  25009. this string, otherwise it will be inserted.
  25010. To delete a section of text, you can use setHighlightedRegion() to
  25011. highlight it, and call insertTextAtCursor (String::empty).
  25012. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  25013. */
  25014. void insertTextAtCursor (String textToInsert);
  25015. /** Deletes all the text from the editor. */
  25016. void clear();
  25017. /** Deletes the currently selected region, and puts it on the clipboard.
  25018. @see copy, paste, SystemClipboard
  25019. */
  25020. void cut();
  25021. /** Copies any currently selected region to the clipboard.
  25022. @see cut, paste, SystemClipboard
  25023. */
  25024. void copy();
  25025. /** Pastes the contents of the clipboard into the editor at the cursor position.
  25026. @see cut, copy, SystemClipboard
  25027. */
  25028. void paste();
  25029. /** Moves the caret to be in front of a given character.
  25030. @see getCaretPosition
  25031. */
  25032. void setCaretPosition (const int newIndex) throw();
  25033. /** Returns the current index of the caret.
  25034. @see setCaretPosition
  25035. */
  25036. int getCaretPosition() const throw();
  25037. /** Attempts to scroll the text editor so that the caret ends up at
  25038. a specified position.
  25039. This won't affect the caret's position within the text, it tries to scroll
  25040. the entire editor vertically and horizontally so that the caret is sitting
  25041. at the given position (relative to the top-left of this component).
  25042. Depending on the amount of text available, it might not be possible to
  25043. scroll far enough for the caret to reach this exact position, but it
  25044. will go as far as it can in that direction.
  25045. */
  25046. void scrollEditorToPositionCaret (const int desiredCaretX,
  25047. const int desiredCaretY) throw();
  25048. /** Get the graphical position of the caret.
  25049. The rectangle returned is relative to the component's top-left corner.
  25050. @see scrollEditorToPositionCaret
  25051. */
  25052. const Rectangle getCaretRectangle() throw();
  25053. /** Selects a section of the text.
  25054. */
  25055. void setHighlightedRegion (int startIndex,
  25056. int numberOfCharactersToHighlight) throw();
  25057. /** Returns the first character that is selected.
  25058. If nothing is selected, this will still return a character index, but getHighlightedRegionLength()
  25059. will return 0.
  25060. @see setHighlightedRegion, getHighlightedRegionLength
  25061. */
  25062. int getHighlightedRegionStart() const throw() { return selectionStart; }
  25063. /** Returns the number of characters that are selected.
  25064. @see setHighlightedRegion, getHighlightedRegionStart
  25065. */
  25066. int getHighlightedRegionLength() const throw() { return jmax (0, selectionEnd - selectionStart); }
  25067. /** Returns the section of text that is currently selected. */
  25068. const String getHighlightedText() const throw();
  25069. /** Finds the index of the character at a given position.
  25070. The co-ordinates are relative to the component's top-left.
  25071. */
  25072. int getTextIndexAt (const int x, const int y) throw();
  25073. /** Counts the number of characters in the text.
  25074. This is quicker than getting the text as a string if you just need to know
  25075. the length.
  25076. */
  25077. int getTotalNumChars() throw();
  25078. /** Returns the total width of the text, as it is currently laid-out.
  25079. This may be larger than the size of the TextEditor, and can change when
  25080. the TextEditor is resized or the text changes.
  25081. */
  25082. int getTextWidth() const throw();
  25083. /** Returns the maximum height of the text, as it is currently laid-out.
  25084. This may be larger than the size of the TextEditor, and can change when
  25085. the TextEditor is resized or the text changes.
  25086. */
  25087. int getTextHeight() const throw();
  25088. /** Changes the size of the gap at the top and left-edge of the editor.
  25089. By default there's a gap of 4 pixels.
  25090. */
  25091. void setIndents (const int newLeftIndent, const int newTopIndent) throw();
  25092. /** Changes the size of border left around the edge of the component.
  25093. @see getBorder
  25094. */
  25095. void setBorder (const BorderSize& border) throw();
  25096. /** Returns the size of border around the edge of the component.
  25097. @see setBorder
  25098. */
  25099. const BorderSize getBorder() const throw();
  25100. /** Used to disable the auto-scrolling which keeps the cursor visible.
  25101. If true (the default), the editor will scroll when the cursor moves offscreen. If
  25102. set to false, it won't.
  25103. */
  25104. void setScrollToShowCursor (const bool shouldScrollToShowCursor) throw();
  25105. /** @internal */
  25106. void paint (Graphics& g);
  25107. /** @internal */
  25108. void paintOverChildren (Graphics& g);
  25109. /** @internal */
  25110. void mouseDown (const MouseEvent& e);
  25111. /** @internal */
  25112. void mouseUp (const MouseEvent& e);
  25113. /** @internal */
  25114. void mouseDrag (const MouseEvent& e);
  25115. /** @internal */
  25116. void mouseDoubleClick (const MouseEvent& e);
  25117. /** @internal */
  25118. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25119. /** @internal */
  25120. bool keyPressed (const KeyPress& key);
  25121. /** @internal */
  25122. bool keyStateChanged (const bool isKeyDown);
  25123. /** @internal */
  25124. void focusGained (FocusChangeType cause);
  25125. /** @internal */
  25126. void focusLost (FocusChangeType cause);
  25127. /** @internal */
  25128. void resized();
  25129. /** @internal */
  25130. void enablementChanged();
  25131. /** @internal */
  25132. void colourChanged();
  25133. juce_UseDebuggingNewOperator
  25134. protected:
  25135. /** This adds the items to the popup menu.
  25136. By default it adds the cut/copy/paste items, but you can override this if
  25137. you need to replace these with your own items.
  25138. If you want to add your own items to the existing ones, you can override this,
  25139. call the base class's addPopupMenuItems() method, then append your own items.
  25140. When the menu has been shown, performPopupMenuAction() will be called to
  25141. perform the item that the user has chosen.
  25142. The default menu items will be added using item IDs in the range
  25143. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  25144. menu IDs.
  25145. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  25146. a pointer to the info about it, or may be null if the menu is being triggered
  25147. by some other means.
  25148. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  25149. */
  25150. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  25151. const MouseEvent* mouseClickEvent);
  25152. /** This is called to perform one of the items that was shown on the popup menu.
  25153. If you've overridden addPopupMenuItems(), you should also override this
  25154. to perform the actions that you've added.
  25155. If you've overridden addPopupMenuItems() but have still left the default items
  25156. on the menu, remember to call the superclass's performPopupMenuAction()
  25157. so that it can perform the default actions if that's what the user clicked on.
  25158. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  25159. */
  25160. virtual void performPopupMenuAction (const int menuItemID);
  25161. /** Scrolls the minimum distance needed to get the caret into view. */
  25162. void scrollToMakeSureCursorIsVisible() throw();
  25163. /** @internal */
  25164. void moveCaret (int newCaretPos) throw();
  25165. /** @internal */
  25166. void moveCursorTo (const int newPosition, const bool isSelecting) throw();
  25167. /** Used internally to dispatch a text-change message. */
  25168. void textChanged() throw();
  25169. /** Begins a new transaction in the UndoManager.
  25170. */
  25171. void newTransaction() throw();
  25172. /** Used internally to trigger an undo or redo. */
  25173. void doUndoRedo (const bool isRedo);
  25174. /** Can be overridden to intercept return key presses directly */
  25175. virtual void returnPressed();
  25176. /** Can be overridden to intercept escape key presses directly */
  25177. virtual void escapePressed();
  25178. /** @internal */
  25179. void handleCommandMessage (int commandId);
  25180. private:
  25181. Viewport* viewport;
  25182. TextHolderComponent* textHolder;
  25183. BorderSize borderSize;
  25184. bool readOnly : 1;
  25185. bool multiline : 1;
  25186. bool wordWrap : 1;
  25187. bool returnKeyStartsNewLine : 1;
  25188. bool caretVisible : 1;
  25189. bool popupMenuEnabled : 1;
  25190. bool selectAllTextWhenFocused : 1;
  25191. bool scrollbarVisible : 1;
  25192. bool wasFocused : 1;
  25193. bool caretFlashState : 1;
  25194. bool keepCursorOnScreen : 1;
  25195. bool tabKeyUsed : 1;
  25196. bool menuActive : 1;
  25197. UndoManager undoManager;
  25198. float cursorX, cursorY, cursorHeight;
  25199. int maxTextLength;
  25200. int selectionStart, selectionEnd;
  25201. int leftIndent, topIndent;
  25202. unsigned int lastTransactionTime;
  25203. Font currentFont;
  25204. int totalNumChars, caretPosition;
  25205. VoidArray sections;
  25206. String textToShowWhenEmpty;
  25207. Colour colourForTextWhenEmpty;
  25208. tchar passwordCharacter;
  25209. enum
  25210. {
  25211. notDragging,
  25212. draggingSelectionStart,
  25213. draggingSelectionEnd
  25214. } dragType;
  25215. String allowedCharacters;
  25216. SortedSet <void*> listeners;
  25217. friend class TextEditorInsertAction;
  25218. friend class TextEditorRemoveAction;
  25219. void coalesceSimilarSections() throw();
  25220. void splitSection (const int sectionIndex, const int charToSplitAt) throw();
  25221. void clearInternal (UndoManager* const um) throw();
  25222. void insert (const String& text,
  25223. const int insertIndex,
  25224. const Font& font,
  25225. const Colour& colour,
  25226. UndoManager* const um,
  25227. const int caretPositionToMoveTo) throw();
  25228. void reinsert (const int insertIndex,
  25229. const VoidArray& sections) throw();
  25230. void remove (const int startIndex,
  25231. int endIndex,
  25232. UndoManager* const um,
  25233. const int caretPositionToMoveTo) throw();
  25234. void getCharPosition (const int index,
  25235. float& x, float& y,
  25236. float& lineHeight) const throw();
  25237. void updateCaretPosition() throw();
  25238. int indexAtPosition (const float x,
  25239. const float y) throw();
  25240. int findWordBreakAfter (const int position) const throw();
  25241. int findWordBreakBefore (const int position) const throw();
  25242. friend class TextHolderComponent;
  25243. friend class TextEditorViewport;
  25244. void drawContent (Graphics& g);
  25245. void updateTextHolderSize() throw();
  25246. float getWordWrapWidth() const throw();
  25247. void timerCallbackInt();
  25248. void repaintCaret();
  25249. void repaintText (int textStartIndex, int textEndIndex);
  25250. TextEditor (const TextEditor&);
  25251. const TextEditor& operator= (const TextEditor&);
  25252. };
  25253. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  25254. /********* End of inlined file: juce_TextEditor.h *********/
  25255. class Label;
  25256. /**
  25257. A class for receiving events from a Label.
  25258. You can register a LabelListener with a Label using the Label::addListener()
  25259. method, and it will be called when the text of the label changes, either because
  25260. of a call to Label::setText() or by the user editing the text (if the label is
  25261. editable).
  25262. @see Label::addListener, Label::removeListener
  25263. */
  25264. class JUCE_API LabelListener
  25265. {
  25266. public:
  25267. /** Destructor. */
  25268. virtual ~LabelListener() {}
  25269. /** Called when a Label's text has changed.
  25270. */
  25271. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  25272. };
  25273. /**
  25274. A component that displays a text string, and can optionally become a text
  25275. editor when clicked.
  25276. */
  25277. class JUCE_API Label : public Component,
  25278. public SettableTooltipClient,
  25279. protected TextEditorListener,
  25280. private ComponentListener
  25281. {
  25282. public:
  25283. /** Creates a Label.
  25284. @param componentName the name to give the component
  25285. @param labelText the text to show in the label
  25286. */
  25287. Label (const String& componentName,
  25288. const String& labelText);
  25289. /** Destructor. */
  25290. ~Label();
  25291. /** Changes the label text.
  25292. If broadcastChangeMessage is true and the new text is different to the current
  25293. text, then the class will broadcast a change message to any LabelListeners that
  25294. are registered.
  25295. */
  25296. void setText (const String& newText,
  25297. const bool broadcastChangeMessage);
  25298. /** Returns the label's current text.
  25299. @param returnActiveEditorContents if this is true and the label is currently
  25300. being edited, then this method will return the
  25301. text as it's being shown in the editor. If false,
  25302. then the value returned here won't be updated until
  25303. the user has finished typing and pressed the return
  25304. key.
  25305. */
  25306. const String getText (const bool returnActiveEditorContents = false) const throw();
  25307. /** Changes the font to use to draw the text.
  25308. @see getFont
  25309. */
  25310. void setFont (const Font& newFont) throw();
  25311. /** Returns the font currently being used.
  25312. @see setFont
  25313. */
  25314. const Font& getFont() const throw();
  25315. /** A set of colour IDs to use to change the colour of various aspects of the label.
  25316. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25317. methods.
  25318. Note that you can also use the constants from TextEditor::ColourIds to change the
  25319. colour of the text editor that is opened when a label is editable.
  25320. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25321. */
  25322. enum ColourIds
  25323. {
  25324. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  25325. textColourId = 0x1000281, /**< The colour for the text. */
  25326. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  25327. Leave this transparent to not have an outline. */
  25328. };
  25329. /** Sets the style of justification to be used for positioning the text.
  25330. (The default is Justification::centredLeft)
  25331. */
  25332. void setJustificationType (const Justification& justification) throw();
  25333. /** Returns the type of justification, as set in setJustificationType(). */
  25334. const Justification getJustificationType() const throw() { return justification; }
  25335. /** Changes the gap that is left between the edge of the component and the text.
  25336. By default there's a small gap left at the sides of the component to allow for
  25337. the drawing of the border, but you can change this if necessary.
  25338. */
  25339. void setBorderSize (int horizontalBorder, int verticalBorder);
  25340. /** Returns the size of the horizontal gap being left around the text.
  25341. */
  25342. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  25343. /** Returns the size of the vertical gap being left around the text.
  25344. */
  25345. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  25346. /** Makes this label "stick to" another component.
  25347. This will cause the label to follow another component around, staying
  25348. either to its left or above it.
  25349. @param owner the component to follow
  25350. @param onLeft if true, the label will stay on the left of its component; if
  25351. false, it will stay above it.
  25352. */
  25353. void attachToComponent (Component* owner,
  25354. const bool onLeft);
  25355. /** If this label has been attached to another component using attachToComponent, this
  25356. returns the other component.
  25357. Returns 0 if the label is not attached.
  25358. */
  25359. Component* getAttachedComponent() const throw() { return ownerComponent; }
  25360. /** If the label is attached to the left of another component, this returns true.
  25361. Returns false if the label is above the other component. This is only relevent if
  25362. attachToComponent() has been called.
  25363. */
  25364. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  25365. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  25366. using ellipsis.
  25367. @see Graphics::drawFittedText
  25368. */
  25369. void setMinimumHorizontalScale (const float newScale);
  25370. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  25371. /** Registers a listener that will be called when the label's text changes. */
  25372. void addListener (LabelListener* const listener) throw();
  25373. /** Deregisters a previously-registered listener. */
  25374. void removeListener (LabelListener* const listener) throw();
  25375. /** Makes the label turn into a TextEditor when clicked.
  25376. By default this is turned off.
  25377. If turned on, then single- or double-clicking will turn the label into
  25378. an editor. If the user then changes the text, then the ChangeBroadcaster
  25379. base class will be used to send change messages to any listeners that
  25380. have registered.
  25381. If the user changes the text, the textWasEdited() method will be called
  25382. afterwards, and subclasses can override this if they need to do anything
  25383. special.
  25384. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  25385. @param editOnDoubleClick if true, a double-click is needed to start editing
  25386. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  25387. edited will discard any changes; if false, then this will
  25388. commit the changes.
  25389. @see showEditor, setEditorColours, TextEditor
  25390. */
  25391. void setEditable (const bool editOnSingleClick,
  25392. const bool editOnDoubleClick = false,
  25393. const bool lossOfFocusDiscardsChanges = false) throw();
  25394. /** Returns true if this option was set using setEditable(). */
  25395. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  25396. /** Returns true if this option was set using setEditable(). */
  25397. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  25398. /** Returns true if this option has been set in a call to setEditable(). */
  25399. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  25400. /** Returns true if the user can edit this label's text. */
  25401. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  25402. /** Makes the editor appear as if the label had been clicked by the user.
  25403. @see textWasEdited, setEditable
  25404. */
  25405. void showEditor();
  25406. /** Hides the editor if it was being shown.
  25407. @param discardCurrentEditorContents if true, the label's text will be
  25408. reset to whatever it was before the editor
  25409. was shown; if false, the current contents of the
  25410. editor will be used to set the label's text
  25411. before it is hidden.
  25412. */
  25413. void hideEditor (const bool discardCurrentEditorContents);
  25414. /** Returns true if the editor is currently focused and active. */
  25415. bool isBeingEdited() const throw();
  25416. juce_UseDebuggingNewOperator
  25417. protected:
  25418. /** @internal */
  25419. void paint (Graphics& g);
  25420. /** @internal */
  25421. void resized();
  25422. /** @internal */
  25423. void mouseUp (const MouseEvent& e);
  25424. /** @internal */
  25425. void mouseDoubleClick (const MouseEvent& e);
  25426. /** @internal */
  25427. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  25428. /** @internal */
  25429. void componentParentHierarchyChanged (Component& component);
  25430. /** @internal */
  25431. void componentVisibilityChanged (Component& component);
  25432. /** @internal */
  25433. void inputAttemptWhenModal();
  25434. /** @internal */
  25435. void focusGained (FocusChangeType);
  25436. /** @internal */
  25437. void enablementChanged();
  25438. /** @internal */
  25439. KeyboardFocusTraverser* createFocusTraverser();
  25440. /** @internal */
  25441. void textEditorTextChanged (TextEditor& editor);
  25442. /** @internal */
  25443. void textEditorReturnKeyPressed (TextEditor& editor);
  25444. /** @internal */
  25445. void textEditorEscapeKeyPressed (TextEditor& editor);
  25446. /** @internal */
  25447. void textEditorFocusLost (TextEditor& editor);
  25448. /** @internal */
  25449. void colourChanged();
  25450. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  25451. Subclasses can override this if they need to customise this component in some way.
  25452. */
  25453. virtual TextEditor* createEditorComponent();
  25454. /** Called after the user changes the text.
  25455. */
  25456. virtual void textWasEdited();
  25457. /** Called when the text has been altered.
  25458. */
  25459. virtual void textWasChanged();
  25460. /** Called when the text editor has just appeared, due to a user click or other
  25461. focus change.
  25462. */
  25463. virtual void editorShown (TextEditor* editorComponent);
  25464. /** Called when the text editor is going to be deleted, after editing has finished.
  25465. */
  25466. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  25467. private:
  25468. String text;
  25469. Font font;
  25470. Justification justification;
  25471. ScopedPointer <TextEditor> editor;
  25472. SortedSet <void*> listeners;
  25473. Component* ownerComponent;
  25474. ScopedPointer <ComponentDeletionWatcher> deletionWatcher;
  25475. int horizontalBorderSize, verticalBorderSize;
  25476. float minimumHorizontalScale;
  25477. bool editSingleClick : 1;
  25478. bool editDoubleClick : 1;
  25479. bool lossOfFocusDiscardsChanges : 1;
  25480. bool leftOfOwnerComp : 1;
  25481. bool updateFromTextEditorContents();
  25482. void callChangeListeners();
  25483. Label (const Label&);
  25484. const Label& operator= (const Label&);
  25485. };
  25486. #endif // __JUCE_LABEL_JUCEHEADER__
  25487. /********* End of inlined file: juce_Label.h *********/
  25488. class ComboBox;
  25489. /**
  25490. A class for receiving events from a ComboBox.
  25491. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  25492. method, and it will be called when the selected item in the box changes.
  25493. @see ComboBox::addListener, ComboBox::removeListener
  25494. */
  25495. class JUCE_API ComboBoxListener
  25496. {
  25497. public:
  25498. /** Destructor. */
  25499. virtual ~ComboBoxListener() {}
  25500. /** Called when a ComboBox has its selected item changed.
  25501. */
  25502. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  25503. };
  25504. /**
  25505. A component that lets the user choose from a drop-down list of choices.
  25506. The combo-box has a list of text strings, each with an associated id number,
  25507. that will be shown in the drop-down list when the user clicks on the component.
  25508. The currently selected choice is displayed in the combo-box, and this can
  25509. either be read-only text, or editable.
  25510. To find out when the user selects a different item or edits the text, you
  25511. can register a ComboBoxListener to receive callbacks.
  25512. @see ComboBoxListener
  25513. */
  25514. class JUCE_API ComboBox : public Component,
  25515. public SettableTooltipClient,
  25516. private LabelListener,
  25517. private AsyncUpdater
  25518. {
  25519. public:
  25520. /** Creates a combo-box.
  25521. On construction, the text field will be empty, so you should call the
  25522. setSelectedId() or setText() method to choose the initial value before
  25523. displaying it.
  25524. @param componentName the name to set for the component (see Component::setName())
  25525. */
  25526. ComboBox (const String& componentName);
  25527. /** Destructor. */
  25528. ~ComboBox();
  25529. /** Sets whether the test in the combo-box is editable.
  25530. The default state for a new ComboBox is non-editable, and can only be changed
  25531. by choosing from the drop-down list.
  25532. */
  25533. void setEditableText (const bool isEditable);
  25534. /** Returns true if the text is directly editable.
  25535. @see setEditableText
  25536. */
  25537. bool isTextEditable() const throw();
  25538. /** Sets the style of justification to be used for positioning the text.
  25539. The default is Justification::centredLeft. The text is displayed using a
  25540. Label component inside the ComboBox.
  25541. */
  25542. void setJustificationType (const Justification& justification) throw();
  25543. /** Returns the current justification for the text box.
  25544. @see setJustificationType
  25545. */
  25546. const Justification getJustificationType() const throw();
  25547. /** Adds an item to be shown in the drop-down list.
  25548. @param newItemText the text of the item to show in the list
  25549. @param newItemId an associated ID number that can be set or retrieved - see
  25550. getSelectedId() and setSelectedId()
  25551. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  25552. */
  25553. void addItem (const String& newItemText,
  25554. const int newItemId) throw();
  25555. /** Adds a separator line to the drop-down list.
  25556. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  25557. */
  25558. void addSeparator() throw();
  25559. /** Adds a heading to the drop-down list, so that you can group the items into
  25560. different sections.
  25561. The headings are indented slightly differently to set them apart from the
  25562. items on the list, and obviously can't be selected. You might want to add
  25563. separators between your sections too.
  25564. @see addItem, addSeparator
  25565. */
  25566. void addSectionHeading (const String& headingName) throw();
  25567. /** This allows items in the drop-down list to be selectively disabled.
  25568. When you add an item, it's enabled by default, but you can call this
  25569. method to change its status.
  25570. If you disable an item which is already selected, this won't change the
  25571. current selection - it just stops the user choosing that item from the list.
  25572. */
  25573. void setItemEnabled (const int itemId,
  25574. const bool shouldBeEnabled) throw();
  25575. /** Changes the text for an existing item.
  25576. */
  25577. void changeItemText (const int itemId,
  25578. const String& newText) throw();
  25579. /** Removes all the items from the drop-down list.
  25580. If this call causes the content to be cleared, then a change-message
  25581. will be broadcast unless dontSendChangeMessage is true.
  25582. @see addItem, removeItem, getNumItems
  25583. */
  25584. void clear (const bool dontSendChangeMessage = false);
  25585. /** Returns the number of items that have been added to the list.
  25586. Note that this doesn't include headers or separators.
  25587. */
  25588. int getNumItems() const throw();
  25589. /** Returns the text for one of the items in the list.
  25590. Note that this doesn't include headers or separators.
  25591. @param index the item's index from 0 to (getNumItems() - 1)
  25592. */
  25593. const String getItemText (const int index) const throw();
  25594. /** Returns the ID for one of the items in the list.
  25595. Note that this doesn't include headers or separators.
  25596. @param index the item's index from 0 to (getNumItems() - 1)
  25597. */
  25598. int getItemId (const int index) const throw();
  25599. /** Returns the ID of the item that's currently shown in the box.
  25600. If no item is selected, or if the text is editable and the user
  25601. has entered something which isn't one of the items in the list, then
  25602. this will return 0.
  25603. @see setSelectedId, getSelectedItemIndex, getText
  25604. */
  25605. int getSelectedId() const throw();
  25606. /** Sets one of the items to be the current selection.
  25607. This will set the ComboBox's text to that of the item that matches
  25608. this ID.
  25609. @param newItemId the new item to select
  25610. @param dontSendChangeMessage if set to true, this method won't trigger a
  25611. change notification
  25612. @see getSelectedId, setSelectedItemIndex, setText
  25613. */
  25614. void setSelectedId (const int newItemId,
  25615. const bool dontSendChangeMessage = false) throw();
  25616. /** Returns the index of the item that's currently shown in the box.
  25617. If no item is selected, or if the text is editable and the user
  25618. has entered something which isn't one of the items in the list, then
  25619. this will return -1.
  25620. @see setSelectedItemIndex, getSelectedId, getText
  25621. */
  25622. int getSelectedItemIndex() const throw();
  25623. /** Sets one of the items to be the current selection.
  25624. This will set the ComboBox's text to that of the item at the given
  25625. index in the list.
  25626. @param newItemIndex the new item to select
  25627. @param dontSendChangeMessage if set to true, this method won't trigger a
  25628. change notification
  25629. @see getSelectedItemIndex, setSelectedId, setText
  25630. */
  25631. void setSelectedItemIndex (const int newItemIndex,
  25632. const bool dontSendChangeMessage = false) throw();
  25633. /** Returns the text that is currently shown in the combo-box's text field.
  25634. If the ComboBox has editable text, then this text may have been edited
  25635. by the user; otherwise it will be one of the items from the list, or
  25636. possibly an empty string if nothing was selected.
  25637. @see setText, getSelectedId, getSelectedItemIndex
  25638. */
  25639. const String getText() const throw();
  25640. /** Sets the contents of the combo-box's text field.
  25641. The text passed-in will be set as the current text regardless of whether
  25642. it is one of the items in the list. If the current text isn't one of the
  25643. items, then getSelectedId() will return -1, otherwise it wil return
  25644. the approriate ID.
  25645. @param newText the text to select
  25646. @param dontSendChangeMessage if set to true, this method won't trigger a
  25647. change notification
  25648. @see getText
  25649. */
  25650. void setText (const String& newText,
  25651. const bool dontSendChangeMessage = false) throw();
  25652. /** Programmatically opens the text editor to allow the user to edit the current item.
  25653. This is the same effect as when the box is clicked-on.
  25654. @see Label::showEditor();
  25655. */
  25656. void showEditor();
  25657. /** Registers a listener that will be called when the box's content changes. */
  25658. void addListener (ComboBoxListener* const listener) throw();
  25659. /** Deregisters a previously-registered listener. */
  25660. void removeListener (ComboBoxListener* const listener) throw();
  25661. /** Sets a message to display when there is no item currently selected.
  25662. @see getTextWhenNothingSelected
  25663. */
  25664. void setTextWhenNothingSelected (const String& newMessage) throw();
  25665. /** Returns the text that is shown when no item is selected.
  25666. @see setTextWhenNothingSelected
  25667. */
  25668. const String getTextWhenNothingSelected() const throw();
  25669. /** Sets the message to show when there are no items in the list, and the user clicks
  25670. on the drop-down box.
  25671. By default it just says "no choices", but this lets you change it to something more
  25672. meaningful.
  25673. */
  25674. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  25675. /** Returns the text shown when no items have been added to the list.
  25676. @see setTextWhenNoChoicesAvailable
  25677. */
  25678. const String getTextWhenNoChoicesAvailable() const throw();
  25679. /** Gives the ComboBox a tooltip. */
  25680. void setTooltip (const String& newTooltip);
  25681. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  25682. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25683. methods.
  25684. To change the colours of the menu that pops up
  25685. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25686. */
  25687. enum ColourIds
  25688. {
  25689. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  25690. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  25691. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  25692. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  25693. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  25694. };
  25695. /** @internal */
  25696. void labelTextChanged (Label*);
  25697. /** @internal */
  25698. void enablementChanged();
  25699. /** @internal */
  25700. void colourChanged();
  25701. /** @internal */
  25702. void focusGained (Component::FocusChangeType cause);
  25703. /** @internal */
  25704. void focusLost (Component::FocusChangeType cause);
  25705. /** @internal */
  25706. void handleAsyncUpdate();
  25707. /** @internal */
  25708. const String getTooltip() { return label->getTooltip(); }
  25709. /** @internal */
  25710. void mouseDown (const MouseEvent&);
  25711. /** @internal */
  25712. void mouseDrag (const MouseEvent&);
  25713. /** @internal */
  25714. void mouseUp (const MouseEvent&);
  25715. /** @internal */
  25716. void lookAndFeelChanged();
  25717. /** @internal */
  25718. void paint (Graphics&);
  25719. /** @internal */
  25720. void resized();
  25721. /** @internal */
  25722. bool keyStateChanged (const bool isKeyDown);
  25723. /** @internal */
  25724. bool keyPressed (const KeyPress&);
  25725. juce_UseDebuggingNewOperator
  25726. private:
  25727. struct ItemInfo
  25728. {
  25729. String name;
  25730. int itemId;
  25731. bool isEnabled : 1, isHeading : 1;
  25732. bool isSeparator() const throw();
  25733. bool isRealItem() const throw();
  25734. };
  25735. OwnedArray <ItemInfo> items;
  25736. int currentIndex;
  25737. bool isButtonDown;
  25738. bool separatorPending;
  25739. bool menuActive;
  25740. SortedSet <void*> listeners;
  25741. Label* label;
  25742. String textWhenNothingSelected, noChoicesMessage;
  25743. void showPopup();
  25744. ItemInfo* getItemForId (const int itemId) const throw();
  25745. ItemInfo* getItemForIndex (const int index) const throw();
  25746. ComboBox (const ComboBox&);
  25747. const ComboBox& operator= (const ComboBox&);
  25748. };
  25749. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  25750. /********* End of inlined file: juce_ComboBox.h *********/
  25751. /**
  25752. Manages the state of some audio and midi i/o devices.
  25753. This class keeps tracks of a currently-selected audio device, through
  25754. with which it continuously streams data from an audio callback, as well as
  25755. one or more midi inputs.
  25756. The idea is that your application will create one global instance of this object,
  25757. and let it take care of creating and deleting specific types of audio devices
  25758. internally. So when the device is changed, your callbacks will just keep running
  25759. without having to worry about this.
  25760. The manager can save and reload all of its device settings as XML, which
  25761. makes it very easy for you to save and reload the audio setup of your
  25762. application.
  25763. And to make it easy to let the user change its settings, there's a component
  25764. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  25765. device selection/sample-rate/latency controls.
  25766. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  25767. call addAudioCallback() to register your audio callback with it, and use that to process
  25768. your audio data.
  25769. The manager also acts as a handy hub for incoming midi messages, allowing a
  25770. listener to register for messages from either a specific midi device, or from whatever
  25771. the current default midi input device is. The listener then doesn't have to worry about
  25772. re-registering with different midi devices if they are changed or deleted.
  25773. And yet another neat trick is that amount of CPU time being used is measured and
  25774. available with the getCpuUsage() method.
  25775. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  25776. listeners whenever one of its settings is changed.
  25777. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  25778. */
  25779. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  25780. {
  25781. public:
  25782. /** Creates a default AudioDeviceManager.
  25783. Initially no audio device will be selected. You should call the initialise() method
  25784. and register an audio callback with setAudioCallback() before it'll be able to
  25785. actually make any noise.
  25786. */
  25787. AudioDeviceManager();
  25788. /** Destructor. */
  25789. ~AudioDeviceManager();
  25790. /**
  25791. This structure holds a set of properties describing the current audio setup.
  25792. @see AudioDeviceManager::setAudioDeviceSetup()
  25793. */
  25794. struct JUCE_API AudioDeviceSetup
  25795. {
  25796. AudioDeviceSetup();
  25797. bool operator== (const AudioDeviceSetup& other) const;
  25798. /** The name of the audio device used for output.
  25799. The name has to be one of the ones listed by the AudioDeviceManager's currently
  25800. selected device type.
  25801. This may be the same as the input device.
  25802. */
  25803. String outputDeviceName;
  25804. /** The name of the audio device used for input.
  25805. This may be the same as the output device.
  25806. */
  25807. String inputDeviceName;
  25808. /** The current sample rate.
  25809. This rate is used for both the input and output devices.
  25810. */
  25811. double sampleRate;
  25812. /** The buffer size, in samples.
  25813. This buffer size is used for both the input and output devices.
  25814. */
  25815. int bufferSize;
  25816. /** The set of active input channels.
  25817. The bits that are set in this array indicate the channels of the
  25818. input device that are active.
  25819. */
  25820. BitArray inputChannels;
  25821. /** If this is true, it indicates that the inputChannels array
  25822. should be ignored, and instead, the device's default channels
  25823. should be used.
  25824. */
  25825. bool useDefaultInputChannels;
  25826. /** The set of active output channels.
  25827. The bits that are set in this array indicate the channels of the
  25828. input device that are active.
  25829. */
  25830. BitArray outputChannels;
  25831. /** If this is true, it indicates that the outputChannels array
  25832. should be ignored, and instead, the device's default channels
  25833. should be used.
  25834. */
  25835. bool useDefaultOutputChannels;
  25836. };
  25837. /** Opens a set of audio devices ready for use.
  25838. This will attempt to open either a default audio device, or one that was
  25839. previously saved as XML.
  25840. @param numInputChannelsNeeded a minimum number of input channels needed
  25841. by your app.
  25842. @param numOutputChannelsNeeded a minimum number of output channels to open
  25843. @param savedState either a previously-saved state that was produced
  25844. by createStateXml(), or 0 if you want the manager
  25845. to choose the best device to open.
  25846. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  25847. fails to open, then a default device will be used
  25848. instead. If false, then on failure, no device is
  25849. opened.
  25850. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  25851. name, then that will be used as the default device
  25852. (assuming that there wasn't one specified in the XML).
  25853. The string can actually be a simple wildcard, containing "*"
  25854. and "?" characters
  25855. @param preferredSetupOptions if this is non-null, the structure will be used as the
  25856. set of preferred settings when opening the device. If you
  25857. use this parameter, the preferredDefaultDeviceName
  25858. field will be ignored
  25859. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25860. */
  25861. const String initialise (const int numInputChannelsNeeded,
  25862. const int numOutputChannelsNeeded,
  25863. const XmlElement* const savedState,
  25864. const bool selectDefaultDeviceOnFailure,
  25865. const String& preferredDefaultDeviceName = String::empty,
  25866. const AudioDeviceSetup* preferredSetupOptions = 0);
  25867. /** Returns some XML representing the current state of the manager.
  25868. This stores the current device, its samplerate, block size, etc, and
  25869. can be restored later with initialise().
  25870. */
  25871. XmlElement* createStateXml() const;
  25872. /** Returns the current device properties that are in use.
  25873. @see setAudioDeviceSetup
  25874. */
  25875. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  25876. /** Changes the current device or its settings.
  25877. If you want to change a device property, like the current sample rate or
  25878. block size, you can call getAudioDeviceSetup() to retrieve the current
  25879. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  25880. and pass it back into this method to apply the new settings.
  25881. @param newSetup the settings that you'd like to use
  25882. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  25883. settings will be taken as having been explicitly chosen by the
  25884. user, and the next time createStateXml() is called, these settings
  25885. will be returned. If it's false, then the device is treated as a
  25886. temporary or default device, and a call to createStateXml() will
  25887. return either the last settings that were made with treatAsChosenDevice
  25888. as true, or the last XML settings that were passed into initialise().
  25889. @returns an error message if anything went wrong, or an empty string if it worked ok.
  25890. @see getAudioDeviceSetup
  25891. */
  25892. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  25893. const bool treatAsChosenDevice);
  25894. /** Returns the currently-active audio device. */
  25895. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  25896. /** Returns the type of audio device currently in use.
  25897. @see setCurrentAudioDeviceType
  25898. */
  25899. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  25900. /** Returns the currently active audio device type object.
  25901. Don't keep a copy of this pointer - it's owned by the device manager and could
  25902. change at any time.
  25903. */
  25904. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  25905. /** Changes the class of audio device being used.
  25906. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  25907. this because there's only one type: CoreAudio.
  25908. For a list of types, see getAvailableDeviceTypes().
  25909. */
  25910. void setCurrentAudioDeviceType (const String& type,
  25911. const bool treatAsChosenDevice);
  25912. /** Closes the currently-open device.
  25913. You can call restartLastAudioDevice() later to reopen it in the same state
  25914. that it was just in.
  25915. */
  25916. void closeAudioDevice();
  25917. /** Tries to reload the last audio device that was running.
  25918. Note that this only reloads the last device that was running before
  25919. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  25920. and can only be called after a device has been opened with SetAudioDevice().
  25921. If a device is already open, this call will do nothing.
  25922. */
  25923. void restartLastAudioDevice();
  25924. /** Registers an audio callback to be used.
  25925. The manager will redirect callbacks from whatever audio device is currently
  25926. in use to all registered callback objects. If more than one callback is
  25927. active, they will all be given the same input data, and their outputs will
  25928. be summed.
  25929. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  25930. object before returning.
  25931. To remove a callback, use removeAudioCallback().
  25932. */
  25933. void addAudioCallback (AudioIODeviceCallback* newCallback);
  25934. /** Deregisters a previously added callback.
  25935. If necessary, this method will invoke audioDeviceStopped() on the callback
  25936. object before returning.
  25937. @see addAudioCallback
  25938. */
  25939. void removeAudioCallback (AudioIODeviceCallback* callback);
  25940. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  25941. Returns a value between 0 and 1.0
  25942. */
  25943. double getCpuUsage() const;
  25944. /** Enables or disables a midi input device.
  25945. The list of devices can be obtained with the MidiInput::getDevices() method.
  25946. Any incoming messages from enabled input devices will be forwarded on to all the
  25947. listeners that have been registered with the addMidiInputCallback() method. They
  25948. can either register for messages from a particular device, or from just the
  25949. "default" midi input.
  25950. Routing the midi input via an AudioDeviceManager means that when a listener
  25951. registers for the default midi input, this default device can be changed by the
  25952. manager without the listeners having to know about it or re-register.
  25953. It also means that a listener can stay registered for a midi input that is disabled
  25954. or not present, so that when the input is re-enabled, the listener will start
  25955. receiving messages again.
  25956. @see addMidiInputCallback, isMidiInputEnabled
  25957. */
  25958. void setMidiInputEnabled (const String& midiInputDeviceName,
  25959. const bool enabled);
  25960. /** Returns true if a given midi input device is being used.
  25961. @see setMidiInputEnabled
  25962. */
  25963. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  25964. /** Registers a listener for callbacks when midi events arrive from a midi input.
  25965. The device name can be empty to indicate that it wants events from whatever the
  25966. current "default" device is. Or it can be the name of one of the midi input devices
  25967. (see MidiInput::getDevices() for the names).
  25968. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  25969. events forwarded on to listeners.
  25970. */
  25971. void addMidiInputCallback (const String& midiInputDeviceName,
  25972. MidiInputCallback* callback);
  25973. /** Removes a listener that was previously registered with addMidiInputCallback().
  25974. */
  25975. void removeMidiInputCallback (const String& midiInputDeviceName,
  25976. MidiInputCallback* callback);
  25977. /** Sets a midi output device to use as the default.
  25978. The list of devices can be obtained with the MidiOutput::getDevices() method.
  25979. The specified device will be opened automatically and can be retrieved with the
  25980. getDefaultMidiOutput() method.
  25981. Pass in an empty string to deselect all devices. For the default device, you
  25982. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  25983. @see getDefaultMidiOutput, getDefaultMidiOutputName
  25984. */
  25985. void setDefaultMidiOutput (const String& deviceName);
  25986. /** Returns the name of the default midi output.
  25987. @see setDefaultMidiOutput, getDefaultMidiOutput
  25988. */
  25989. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  25990. /** Returns the current default midi output device.
  25991. If no device has been selected, or the device can't be opened, this will
  25992. return 0.
  25993. @see getDefaultMidiOutputName
  25994. */
  25995. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  25996. /** Returns a list of the types of device supported.
  25997. */
  25998. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  25999. /** Creates a list of available types.
  26000. This will add a set of new AudioIODeviceType objects to the specified list, to
  26001. represent each available types of device.
  26002. You can override this if your app needs to do something specific, like avoid
  26003. using DirectSound devices, etc.
  26004. */
  26005. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  26006. /** Plays a beep through the current audio device.
  26007. This is here to allow the audio setup UI panels to easily include a "test"
  26008. button so that the user can check where the audio is coming from.
  26009. */
  26010. void playTestSound();
  26011. /** Turns on level-measuring.
  26012. When enabled, the device manager will measure the peak input level
  26013. across all channels, and you can get this level by calling getCurrentInputLevel().
  26014. This is mainly intended for audio setup UI panels to use to create a mic
  26015. level display, so that the user can check that they've selected the right
  26016. device.
  26017. A simple filter is used to make the level decay smoothly, but this is
  26018. only intended for giving rough feedback, and not for any kind of accurate
  26019. measurement.
  26020. */
  26021. void enableInputLevelMeasurement (const bool enableMeasurement);
  26022. /** Returns the current input level.
  26023. To use this, you must first enable it by calling enableInputLevelMeasurement().
  26024. See enableInputLevelMeasurement() for more info.
  26025. */
  26026. double getCurrentInputLevel() const;
  26027. juce_UseDebuggingNewOperator
  26028. private:
  26029. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  26030. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  26031. AudioDeviceSetup currentSetup;
  26032. ScopedPointer <AudioIODevice> currentAudioDevice;
  26033. SortedSet <AudioIODeviceCallback*> callbacks;
  26034. int numInputChansNeeded, numOutputChansNeeded;
  26035. String currentDeviceType;
  26036. BitArray inputChannels, outputChannels;
  26037. ScopedPointer <XmlElement> lastExplicitSettings;
  26038. mutable bool listNeedsScanning;
  26039. bool useInputNames;
  26040. int inputLevelMeasurementEnabledCount;
  26041. double inputLevel;
  26042. ScopedPointer <AudioSampleBuffer> testSound;
  26043. int testSoundPosition;
  26044. AudioSampleBuffer tempBuffer;
  26045. StringArray midiInsFromXml;
  26046. OwnedArray <MidiInput> enabledMidiInputs;
  26047. Array <MidiInputCallback*> midiCallbacks;
  26048. Array <MidiInput*> midiCallbackDevices;
  26049. String defaultMidiOutputName;
  26050. ScopedPointer <MidiOutput> defaultMidiOutput;
  26051. CriticalSection audioCallbackLock, midiCallbackLock;
  26052. double cpuUsageMs, timeToCpuScale;
  26053. class CallbackHandler : public AudioIODeviceCallback,
  26054. public MidiInputCallback
  26055. {
  26056. public:
  26057. AudioDeviceManager* owner;
  26058. void audioDeviceIOCallback (const float** inputChannelData,
  26059. int totalNumInputChannels,
  26060. float** outputChannelData,
  26061. int totalNumOutputChannels,
  26062. int numSamples);
  26063. void audioDeviceAboutToStart (AudioIODevice*);
  26064. void audioDeviceStopped();
  26065. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  26066. };
  26067. CallbackHandler callbackHandler;
  26068. friend class CallbackHandler;
  26069. void audioDeviceIOCallbackInt (const float** inputChannelData,
  26070. int totalNumInputChannels,
  26071. float** outputChannelData,
  26072. int totalNumOutputChannels,
  26073. int numSamples);
  26074. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  26075. void audioDeviceStoppedInt();
  26076. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  26077. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  26078. const BitArray& ins, const BitArray& outs);
  26079. void stopDevice();
  26080. void updateXml();
  26081. void createDeviceTypesIfNeeded();
  26082. void scanDevicesIfNeeded();
  26083. void deleteCurrentDevice();
  26084. double chooseBestSampleRate (double preferred) const;
  26085. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  26086. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  26087. AudioDeviceManager (const AudioDeviceManager&);
  26088. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  26089. };
  26090. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  26091. /********* End of inlined file: juce_AudioDeviceManager.h *********/
  26092. #endif
  26093. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  26094. #endif
  26095. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  26096. #endif
  26097. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  26098. #endif
  26099. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  26100. #endif
  26101. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26102. /********* Start of inlined file: juce_AudioDataConverters.h *********/
  26103. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26104. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26105. /**
  26106. A set of routines to convert buffers of 32-bit floating point data to and from
  26107. various integer formats.
  26108. */
  26109. class JUCE_API AudioDataConverters
  26110. {
  26111. public:
  26112. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  26113. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 2);
  26114. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  26115. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 3);
  26116. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  26117. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  26118. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  26119. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample = 4);
  26120. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  26121. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 2);
  26122. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  26123. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 3);
  26124. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  26125. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  26126. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  26127. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, const int srcBytesPerSample = 4);
  26128. enum DataFormat
  26129. {
  26130. int16LE,
  26131. int16BE,
  26132. int24LE,
  26133. int24BE,
  26134. int32LE,
  26135. int32BE,
  26136. float32LE,
  26137. float32BE,
  26138. };
  26139. static void convertFloatToFormat (const DataFormat destFormat,
  26140. const float* source, void* dest, int numSamples);
  26141. static void convertFormatToFloat (const DataFormat sourceFormat,
  26142. const void* source, float* dest, int numSamples);
  26143. static void interleaveSamples (const float** source, float* dest,
  26144. const int numSamples, const int numChannels);
  26145. static void deinterleaveSamples (const float* source, float** dest,
  26146. const int numSamples, const int numChannels);
  26147. };
  26148. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  26149. /********* End of inlined file: juce_AudioDataConverters.h *********/
  26150. #endif
  26151. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  26152. #endif
  26153. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  26154. #endif
  26155. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  26156. #endif
  26157. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  26158. /********* Start of inlined file: juce_MidiFile.h *********/
  26159. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  26160. #define __JUCE_MIDIFILE_JUCEHEADER__
  26161. /********* Start of inlined file: juce_MidiMessageSequence.h *********/
  26162. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  26163. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  26164. /**
  26165. A sequence of timestamped midi messages.
  26166. This allows the sequence to be manipulated, and also to be read from and
  26167. written to a standard midi file.
  26168. @see MidiMessage, MidiFile
  26169. */
  26170. class JUCE_API MidiMessageSequence
  26171. {
  26172. public:
  26173. /** Creates an empty midi sequence object. */
  26174. MidiMessageSequence();
  26175. /** Creates a copy of another sequence. */
  26176. MidiMessageSequence (const MidiMessageSequence& other);
  26177. /** Replaces this sequence with another one. */
  26178. const MidiMessageSequence& operator= (const MidiMessageSequence& other);
  26179. /** Destructor. */
  26180. ~MidiMessageSequence();
  26181. /** Structure used to hold midi events in the sequence.
  26182. These structures act as 'handles' on the events as they are moved about in
  26183. the list, and make it quick to find the matching note-offs for note-on events.
  26184. @see MidiMessageSequence::getEventPointer
  26185. */
  26186. class MidiEventHolder
  26187. {
  26188. public:
  26189. /** Destructor. */
  26190. ~MidiEventHolder();
  26191. /** The message itself, whose timestamp is used to specify the event's time.
  26192. */
  26193. MidiMessage message;
  26194. /** The matching note-off event (if this is a note-on event).
  26195. If this isn't a note-on, this pointer will be null.
  26196. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  26197. note-offs up-to-date after events have been moved around in the sequence
  26198. or deleted.
  26199. */
  26200. MidiEventHolder* noteOffObject;
  26201. juce_UseDebuggingNewOperator
  26202. private:
  26203. friend class MidiMessageSequence;
  26204. MidiEventHolder (const MidiMessage& message);
  26205. };
  26206. /** Clears the sequence. */
  26207. void clear();
  26208. /** Returns the number of events in the sequence. */
  26209. int getNumEvents() const;
  26210. /** Returns a pointer to one of the events. */
  26211. MidiEventHolder* getEventPointer (const int index) const;
  26212. /** Returns the time of the note-up that matches the note-on at this index.
  26213. If the event at this index isn't a note-on, it'll just return 0.
  26214. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  26215. */
  26216. double getTimeOfMatchingKeyUp (const int index) const;
  26217. /** Returns the index of the note-up that matches the note-on at this index.
  26218. If the event at this index isn't a note-on, it'll just return -1.
  26219. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  26220. */
  26221. int getIndexOfMatchingKeyUp (const int index) const;
  26222. /** Returns the index of an event. */
  26223. int getIndexOf (MidiEventHolder* const event) const;
  26224. /** Returns the index of the first event on or after the given timestamp.
  26225. If the time is beyond the end of the sequence, this will return the
  26226. number of events.
  26227. */
  26228. int getNextIndexAtTime (const double timeStamp) const;
  26229. /** Returns the timestamp of the first event in the sequence.
  26230. @see getEndTime
  26231. */
  26232. double getStartTime() const;
  26233. /** Returns the timestamp of the last event in the sequence.
  26234. @see getStartTime
  26235. */
  26236. double getEndTime() const;
  26237. /** Returns the timestamp of the event at a given index.
  26238. If the index is out-of-range, this will return 0.0
  26239. */
  26240. double getEventTime (const int index) const;
  26241. /** Inserts a midi message into the sequence.
  26242. The index at which the new message gets inserted will depend on its timestamp,
  26243. because the sequence is kept sorted.
  26244. Remember to call updateMatchedPairs() after adding note-on events.
  26245. @param newMessage the new message to add (an internal copy will be made)
  26246. @param timeAdjustment an optional value to add to the timestamp of the message
  26247. that will be inserted
  26248. @see updateMatchedPairs
  26249. */
  26250. void addEvent (const MidiMessage& newMessage,
  26251. double timeAdjustment = 0);
  26252. /** Deletes one of the events in the sequence.
  26253. Remember to call updateMatchedPairs() after removing events.
  26254. @param index the index of the event to delete
  26255. @param deleteMatchingNoteUp whether to also remove the matching note-off
  26256. if the event you're removing is a note-on
  26257. */
  26258. void deleteEvent (const int index,
  26259. const bool deleteMatchingNoteUp);
  26260. /** Merges another sequence into this one.
  26261. Remember to call updateMatchedPairs() after using this method.
  26262. @param other the sequence to add from
  26263. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  26264. as they are read from the other sequence
  26265. @param firstAllowableDestTime events will not be added if their time is earlier
  26266. than this time. (This is after their time has been adjusted
  26267. by the timeAdjustmentDelta)
  26268. @param endOfAllowableDestTimes events will not be added if their time is equal to
  26269. or greater than this time. (This is after their time has
  26270. been adjusted by the timeAdjustmentDelta)
  26271. */
  26272. void addSequence (const MidiMessageSequence& other,
  26273. double timeAdjustmentDelta,
  26274. double firstAllowableDestTime,
  26275. double endOfAllowableDestTimes);
  26276. /** Makes sure all the note-on and note-off pairs are up-to-date.
  26277. Call this after moving messages about or deleting/adding messages, and it
  26278. will scan the list and make sure all the note-offs in the MidiEventHolder
  26279. structures are pointing at the correct ones.
  26280. */
  26281. void updateMatchedPairs();
  26282. /** Copies all the messages for a particular midi channel to another sequence.
  26283. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  26284. @param destSequence the sequence that the chosen events should be copied to
  26285. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  26286. channel) will also be copied across.
  26287. @see extractSysExMessages
  26288. */
  26289. void extractMidiChannelMessages (const int channelNumberToExtract,
  26290. MidiMessageSequence& destSequence,
  26291. const bool alsoIncludeMetaEvents) const;
  26292. /** Copies all midi sys-ex messages to another sequence.
  26293. @param destSequence this is the sequence to which any sys-exes in this sequence
  26294. will be added
  26295. @see extractMidiChannelMessages
  26296. */
  26297. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  26298. /** Removes any messages in this sequence that have a specific midi channel.
  26299. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  26300. */
  26301. void deleteMidiChannelMessages (const int channelNumberToRemove);
  26302. /** Removes any sys-ex messages from this sequence.
  26303. */
  26304. void deleteSysExMessages();
  26305. /** Adds an offset to the timestamps of all events in the sequence.
  26306. @param deltaTime the amount to add to each timestamp.
  26307. */
  26308. void addTimeToMessages (const double deltaTime);
  26309. /** Scans through the sequence to determine the state of any midi controllers at
  26310. a given time.
  26311. This will create a sequence of midi controller changes that can be
  26312. used to set all midi controllers to the state they would be in at the
  26313. specified time within this sequence.
  26314. As well as controllers, it will also recreate the midi program number
  26315. and pitch bend position.
  26316. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  26317. for other channels will be ignored.
  26318. @param time the time at which you want to find out the state - there are
  26319. no explicit units for this time measurement, it's the same units
  26320. as used for the timestamps of the messages
  26321. @param resultMessages an array to which midi controller-change messages will be added. This
  26322. will be the minimum number of controller changes to recreate the
  26323. state at the required time.
  26324. */
  26325. void createControllerUpdatesForTime (const int channelNumber,
  26326. const double time,
  26327. OwnedArray<MidiMessage>& resultMessages);
  26328. juce_UseDebuggingNewOperator
  26329. /** @internal */
  26330. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  26331. const MidiMessageSequence::MidiEventHolder* const second) throw();
  26332. private:
  26333. friend class MidiComparator;
  26334. friend class MidiFile;
  26335. OwnedArray <MidiEventHolder> list;
  26336. void sort();
  26337. };
  26338. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  26339. /********* End of inlined file: juce_MidiMessageSequence.h *********/
  26340. /**
  26341. Reads/writes standard midi format files.
  26342. To read a midi file, create a MidiFile object and call its readFrom() method. You
  26343. can then get the individual midi tracks from it using the getTrack() method.
  26344. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  26345. to it using the addTrack() method, and then call its writeTo() method to stream
  26346. it out.
  26347. @see MidiMessageSequence
  26348. */
  26349. class JUCE_API MidiFile
  26350. {
  26351. public:
  26352. /** Creates an empty MidiFile object.
  26353. */
  26354. MidiFile() throw();
  26355. /** Destructor. */
  26356. ~MidiFile() throw();
  26357. /** Returns the number of tracks in the file.
  26358. @see getTrack, addTrack
  26359. */
  26360. int getNumTracks() const throw();
  26361. /** Returns a pointer to one of the tracks in the file.
  26362. @returns a pointer to the track, or 0 if the index is out-of-range
  26363. @see getNumTracks, addTrack
  26364. */
  26365. const MidiMessageSequence* getTrack (const int index) const throw();
  26366. /** Adds a midi track to the file.
  26367. This will make its own internal copy of the sequence that is passed-in.
  26368. @see getNumTracks, getTrack
  26369. */
  26370. void addTrack (const MidiMessageSequence& trackSequence) throw();
  26371. /** Removes all midi tracks from the file.
  26372. @see getNumTracks
  26373. */
  26374. void clear() throw();
  26375. /** Returns the raw time format code that will be written to a stream.
  26376. After reading a midi file, this method will return the time-format that
  26377. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  26378. or setSmpteTimeFormat() methods.
  26379. If the value returned is positive, it indicates the number of midi ticks
  26380. per quarter-note - see setTicksPerQuarterNote().
  26381. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  26382. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  26383. */
  26384. short getTimeFormat() const throw();
  26385. /** Sets the time format to use when this file is written to a stream.
  26386. If this is called, the file will be written as bars/beats using the
  26387. specified resolution, rather than SMPTE absolute times, as would be
  26388. used if setSmpteTimeFormat() had been called instead.
  26389. @param ticksPerQuarterNote e.g. 96, 960
  26390. @see setSmpteTimeFormat
  26391. */
  26392. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  26393. /** Sets the time format to use when this file is written to a stream.
  26394. If this is called, the file will be written using absolute times, rather
  26395. than bars/beats as would be the case if setTicksPerBeat() had been called
  26396. instead.
  26397. @param framesPerSecond must be 24, 25, 29 or 30
  26398. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  26399. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  26400. timing, setSmpteTimeFormat (25, 40)
  26401. @see setTicksPerBeat
  26402. */
  26403. void setSmpteTimeFormat (const int framesPerSecond,
  26404. const int subframeResolution) throw();
  26405. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  26406. Useful for finding the positions of all the tempo changes in a file.
  26407. @param tempoChangeEvents a list to which all the events will be added
  26408. */
  26409. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  26410. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  26411. Useful for finding the positions of all the tempo changes in a file.
  26412. @param timeSigEvents a list to which all the events will be added
  26413. */
  26414. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  26415. /** Returns the latest timestamp in any of the tracks.
  26416. (Useful for finding the length of the file).
  26417. */
  26418. double getLastTimestamp() const;
  26419. /** Reads a midi file format stream.
  26420. After calling this, you can get the tracks that were read from the file by using the
  26421. getNumTracks() and getTrack() methods.
  26422. The timestamps of the midi events in the tracks will represent their positions in
  26423. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  26424. method.
  26425. @returns true if the stream was read successfully
  26426. */
  26427. bool readFrom (InputStream& sourceStream);
  26428. /** Writes the midi tracks as a standard midi file.
  26429. @returns true if the operation succeeded.
  26430. */
  26431. bool writeTo (OutputStream& destStream);
  26432. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  26433. This will use the midi time format and tempo/time signature info in the
  26434. tracks to convert all the timestamps to absolute values in seconds.
  26435. */
  26436. void convertTimestampTicksToSeconds();
  26437. juce_UseDebuggingNewOperator
  26438. /** @internal */
  26439. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  26440. const MidiMessageSequence::MidiEventHolder* const second) throw();
  26441. private:
  26442. OwnedArray <MidiMessageSequence> tracks;
  26443. short timeFormat;
  26444. MidiFile (const MidiFile&);
  26445. const MidiFile& operator= (const MidiFile&);
  26446. void readNextTrack (const char* data, int size);
  26447. void writeTrack (OutputStream& mainOut, const int trackNum);
  26448. };
  26449. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  26450. /********* End of inlined file: juce_MidiFile.h *********/
  26451. #endif
  26452. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  26453. /********* Start of inlined file: juce_MidiKeyboardState.h *********/
  26454. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  26455. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  26456. class MidiKeyboardState;
  26457. /**
  26458. Receives events from a MidiKeyboardState object.
  26459. @see MidiKeyboardState
  26460. */
  26461. class JUCE_API MidiKeyboardStateListener
  26462. {
  26463. public:
  26464. MidiKeyboardStateListener() throw() {}
  26465. virtual ~MidiKeyboardStateListener() {}
  26466. /** Called when one of the MidiKeyboardState's keys is pressed.
  26467. This will be called synchronously when the state is either processing a
  26468. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  26469. when a note is being played with its MidiKeyboardState::noteOn() method.
  26470. Note that this callback could happen from an audio callback thread, so be
  26471. careful not to block, and avoid any UI activity in the callback.
  26472. */
  26473. virtual void handleNoteOn (MidiKeyboardState* source,
  26474. int midiChannel, int midiNoteNumber, float velocity) = 0;
  26475. /** Called when one of the MidiKeyboardState's keys is released.
  26476. This will be called synchronously when the state is either processing a
  26477. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  26478. when a note is being played with its MidiKeyboardState::noteOff() method.
  26479. Note that this callback could happen from an audio callback thread, so be
  26480. careful not to block, and avoid any UI activity in the callback.
  26481. */
  26482. virtual void handleNoteOff (MidiKeyboardState* source,
  26483. int midiChannel, int midiNoteNumber) = 0;
  26484. };
  26485. /**
  26486. Represents a piano keyboard, keeping track of which keys are currently pressed.
  26487. This object can parse a stream of midi events, using them to update its idea
  26488. of which keys are pressed for each individiual midi channel.
  26489. When keys go up or down, it can broadcast these events to listener objects.
  26490. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  26491. methods, and midi messages for these events will be merged into the
  26492. midi stream that gets processed by processNextMidiBuffer().
  26493. */
  26494. class JUCE_API MidiKeyboardState
  26495. {
  26496. public:
  26497. MidiKeyboardState();
  26498. ~MidiKeyboardState();
  26499. /** Resets the state of the object.
  26500. All internal data for all the channels is reset, but no events are sent as a
  26501. result.
  26502. If you want to release any keys that are currently down, and to send out note-up
  26503. midi messages for this, use the allNotesOff() method instead.
  26504. */
  26505. void reset();
  26506. /** Returns true if the given midi key is currently held down for the given midi channel.
  26507. The channel number must be between 1 and 16. If you want to see if any notes are
  26508. on for a range of channels, use the isNoteOnForChannels() method.
  26509. */
  26510. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  26511. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  26512. The channel mask has a bit set for each midi channel you want to test for - bit
  26513. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  26514. If a note is on for at least one of the specified channels, this returns true.
  26515. */
  26516. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  26517. /** Turns a specified note on.
  26518. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  26519. next call to processNextMidiBuffer().
  26520. It will also trigger a synchronous callback to the listeners to tell them that the key has
  26521. gone down.
  26522. */
  26523. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  26524. /** Turns a specified note off.
  26525. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  26526. next call to processNextMidiBuffer().
  26527. It will also trigger a synchronous callback to the listeners to tell them that the key has
  26528. gone up.
  26529. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  26530. */
  26531. void noteOff (const int midiChannel, const int midiNoteNumber);
  26532. /** This will turn off any currently-down notes for the given midi channel.
  26533. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  26534. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  26535. and events being added to the midi stream.
  26536. */
  26537. void allNotesOff (const int midiChannel);
  26538. /** Looks at a key-up/down event and uses it to update the state of this object.
  26539. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  26540. instead.
  26541. */
  26542. void processNextMidiEvent (const MidiMessage& message);
  26543. /** Scans a midi stream for up/down events and adds its own events to it.
  26544. This will look for any up/down events and use them to update the internal state,
  26545. synchronously making suitable callbacks to the listeners.
  26546. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  26547. and noteOff() calls will be added into the buffer.
  26548. Only the section of the buffer whose timestamps are between startSample and
  26549. (startSample + numSamples) will be affected, and any events added will be placed
  26550. between these times.
  26551. If you're going to use this method, you'll need to keep calling it regularly for
  26552. it to work satisfactorily.
  26553. To process a single midi event at a time, use the processNextMidiEvent() method
  26554. instead.
  26555. */
  26556. void processNextMidiBuffer (MidiBuffer& buffer,
  26557. const int startSample,
  26558. const int numSamples,
  26559. const bool injectIndirectEvents);
  26560. /** Registers a listener for callbacks when keys go up or down.
  26561. @see removeListener
  26562. */
  26563. void addListener (MidiKeyboardStateListener* const listener) throw();
  26564. /** Deregisters a listener.
  26565. @see addListener
  26566. */
  26567. void removeListener (MidiKeyboardStateListener* const listener) throw();
  26568. juce_UseDebuggingNewOperator
  26569. private:
  26570. CriticalSection lock;
  26571. uint16 noteStates [128];
  26572. MidiBuffer eventsToAdd;
  26573. VoidArray listeners;
  26574. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  26575. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  26576. MidiKeyboardState (const MidiKeyboardState&);
  26577. const MidiKeyboardState& operator= (const MidiKeyboardState&);
  26578. };
  26579. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  26580. /********* End of inlined file: juce_MidiKeyboardState.h *********/
  26581. #endif
  26582. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  26583. #endif
  26584. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  26585. /********* Start of inlined file: juce_MidiMessageCollector.h *********/
  26586. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  26587. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  26588. /**
  26589. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  26590. processing by a block-based audio callback.
  26591. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  26592. so it can easily use a midi input or keyboard component as its source.
  26593. @see MidiMessage, MidiInput
  26594. */
  26595. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  26596. public MidiInputCallback
  26597. {
  26598. public:
  26599. /** Creates a MidiMessageCollector. */
  26600. MidiMessageCollector();
  26601. /** Destructor. */
  26602. ~MidiMessageCollector();
  26603. /** Clears any messages from the queue.
  26604. You need to call this method before starting to use the collector, so that
  26605. it knows the correct sample rate to use.
  26606. */
  26607. void reset (const double sampleRate);
  26608. /** Takes an incoming real-time message and adds it to the queue.
  26609. The message's timestamp is taken, and it will be ready for retrieval as part
  26610. of the block returned by the next call to removeNextBlockOfMessages().
  26611. This method is fully thread-safe when overlapping calls are made with
  26612. removeNextBlockOfMessages().
  26613. */
  26614. void addMessageToQueue (const MidiMessage& message);
  26615. /** Removes all the pending messages from the queue as a buffer.
  26616. This will also correct the messages' timestamps to make sure they're in
  26617. the range 0 to numSamples - 1.
  26618. This call should be made regularly by something like an audio processing
  26619. callback, because the time that it happens is used in calculating the
  26620. midi event positions.
  26621. This method is fully thread-safe when overlapping calls are made with
  26622. addMessageToQueue().
  26623. */
  26624. void removeNextBlockOfMessages (MidiBuffer& destBuffer,
  26625. const int numSamples);
  26626. /** @internal */
  26627. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  26628. /** @internal */
  26629. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  26630. /** @internal */
  26631. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  26632. juce_UseDebuggingNewOperator
  26633. private:
  26634. double lastCallbackTime;
  26635. CriticalSection midiCallbackLock;
  26636. MidiBuffer incomingMessages;
  26637. double sampleRate;
  26638. MidiMessageCollector (const MidiMessageCollector&);
  26639. const MidiMessageCollector& operator= (const MidiMessageCollector&);
  26640. };
  26641. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  26642. /********* End of inlined file: juce_MidiMessageCollector.h *********/
  26643. #endif
  26644. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  26645. #endif
  26646. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26647. /********* Start of inlined file: juce_AudioUnitPluginFormat.h *********/
  26648. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26649. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  26650. /********* Start of inlined file: juce_AudioPluginFormat.h *********/
  26651. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26652. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  26653. /********* Start of inlined file: juce_AudioPluginInstance.h *********/
  26654. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26655. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  26656. /********* Start of inlined file: juce_AudioProcessor.h *********/
  26657. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  26658. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  26659. /********* Start of inlined file: juce_AudioProcessorEditor.h *********/
  26660. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  26661. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  26662. class AudioProcessor;
  26663. /**
  26664. Base class for the component that acts as the GUI for an AudioProcessor.
  26665. Derive your editor component from this class, and create an instance of it
  26666. by overriding the AudioProcessor::createEditor() method.
  26667. @see AudioProcessor, GenericAudioProcessorEditor
  26668. */
  26669. class JUCE_API AudioProcessorEditor : public Component
  26670. {
  26671. protected:
  26672. /** Creates an editor for the specified processor.
  26673. */
  26674. AudioProcessorEditor (AudioProcessor* const owner);
  26675. public:
  26676. /** Destructor. */
  26677. ~AudioProcessorEditor();
  26678. /** Returns a pointer to the processor that this editor represents. */
  26679. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  26680. private:
  26681. AudioProcessor* const owner;
  26682. };
  26683. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  26684. /********* End of inlined file: juce_AudioProcessorEditor.h *********/
  26685. /********* Start of inlined file: juce_AudioProcessorListener.h *********/
  26686. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  26687. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  26688. class AudioProcessor;
  26689. /**
  26690. Base class for listeners that want to know about changes to an AudioProcessor.
  26691. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  26692. @see AudioProcessor
  26693. */
  26694. class JUCE_API AudioProcessorListener
  26695. {
  26696. public:
  26697. /** Destructor. */
  26698. virtual ~AudioProcessorListener() {}
  26699. /** Receives a callback when a parameter is changed.
  26700. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  26701. many audio processors will change their parameter during their audio callback.
  26702. This means that not only has your handler code got to be completely thread-safe,
  26703. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  26704. this event on your message thread, use this callback to trigger an AsyncUpdater
  26705. or ChangeBroadcaster which you can respond to on the message thread.
  26706. */
  26707. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  26708. int parameterIndex,
  26709. float newValue) = 0;
  26710. /** Called to indicate that something else in the plugin has changed, like its
  26711. program, number of parameters, etc.
  26712. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  26713. call it during their audio callback. This means that not only has your handler code
  26714. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  26715. blocking. If you need to handle this event on your message thread, use this callback
  26716. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  26717. message thread.
  26718. */
  26719. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  26720. /** Indicates that a parameter change gesture has started.
  26721. E.g. if the user is dragging a slider, this would be called when they first
  26722. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  26723. called when they release it.
  26724. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  26725. call it during their audio callback. This means that not only has your handler code
  26726. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  26727. blocking. If you need to handle this event on your message thread, use this callback
  26728. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  26729. message thread.
  26730. @see audioProcessorParameterChangeGestureEnd
  26731. */
  26732. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  26733. int parameterIndex);
  26734. /** Indicates that a parameter change gesture has finished.
  26735. E.g. if the user is dragging a slider, this would be called when they release
  26736. the mouse button.
  26737. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  26738. call it during their audio callback. This means that not only has your handler code
  26739. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  26740. blocking. If you need to handle this event on your message thread, use this callback
  26741. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  26742. message thread.
  26743. @see audioPluginParameterChangeGestureStart
  26744. */
  26745. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  26746. int parameterIndex);
  26747. };
  26748. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  26749. /********* End of inlined file: juce_AudioProcessorListener.h *********/
  26750. /********* Start of inlined file: juce_AudioPlayHead.h *********/
  26751. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  26752. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  26753. /**
  26754. A subclass of AudioPlayHead can supply information about the position and
  26755. status of a moving play head during audio playback.
  26756. One of these can be supplied to an AudioProcessor object so that it can find
  26757. out about the position of the audio that it is rendering.
  26758. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  26759. */
  26760. class JUCE_API AudioPlayHead
  26761. {
  26762. protected:
  26763. AudioPlayHead() {}
  26764. public:
  26765. virtual ~AudioPlayHead() {}
  26766. /** Frame rate types. */
  26767. enum FrameRateType
  26768. {
  26769. fps24 = 0,
  26770. fps25 = 1,
  26771. fps2997 = 2,
  26772. fps30 = 3,
  26773. fps2997drop = 4,
  26774. fps30drop = 5,
  26775. fpsUnknown = 99
  26776. };
  26777. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  26778. */
  26779. struct CurrentPositionInfo
  26780. {
  26781. /** The tempo in BPM */
  26782. double bpm;
  26783. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  26784. int timeSigNumerator;
  26785. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  26786. int timeSigDenominator;
  26787. /** The current play position, in seconds from the start of the edit. */
  26788. double timeInSeconds;
  26789. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  26790. double editOriginTime;
  26791. /** The current play position in pulses-per-quarter-note.
  26792. This is the number of quarter notes since the edit start.
  26793. */
  26794. double ppqPosition;
  26795. /** The position of the start of the last bar, in pulses-per-quarter-note.
  26796. This is the number of quarter notes from the start of the edit to the
  26797. start of the current bar.
  26798. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  26799. it's not available, the value will be 0.
  26800. */
  26801. double ppqPositionOfLastBarStart;
  26802. /** The video frame rate, if applicable. */
  26803. FrameRateType frameRate;
  26804. /** True if the transport is currently playing. */
  26805. bool isPlaying;
  26806. /** True if the transport is currently recording.
  26807. (When isRecording is true, then isPlaying will also be true).
  26808. */
  26809. bool isRecording;
  26810. };
  26811. /** Fills-in the given structure with details about the transport's
  26812. position at the start of the current processing block.
  26813. */
  26814. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  26815. };
  26816. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  26817. /********* End of inlined file: juce_AudioPlayHead.h *********/
  26818. /**
  26819. Base class for audio processing filters or plugins.
  26820. This is intended to act as a base class of audio filter that is general enough to
  26821. be wrapped as a VST, AU, RTAS, etc, or used internally.
  26822. It is also used by the plugin hosting code as the wrapper around an instance
  26823. of a loaded plugin.
  26824. Derive your filter class from this base class, and if you're building a plugin,
  26825. you should implement a global function called createPluginFilter() which creates
  26826. and returns a new instance of your subclass.
  26827. */
  26828. class JUCE_API AudioProcessor
  26829. {
  26830. protected:
  26831. /** Constructor.
  26832. You can also do your initialisation tasks in the initialiseFilterInfo()
  26833. call, which will be made after this object has been created.
  26834. */
  26835. AudioProcessor();
  26836. public:
  26837. /** Destructor. */
  26838. virtual ~AudioProcessor();
  26839. /** Returns the name of this processor.
  26840. */
  26841. virtual const String getName() const = 0;
  26842. /** Called before playback starts, to let the filter prepare itself.
  26843. The sample rate is the target sample rate, and will remain constant until
  26844. playback stops.
  26845. The estimatedSamplesPerBlock value is a HINT about the typical number of
  26846. samples that will be processed for each callback, but isn't any kind
  26847. of guarantee. The actual block sizes that the host uses may be different
  26848. each time the callback happens, and may be more or less than this value.
  26849. */
  26850. virtual void prepareToPlay (double sampleRate,
  26851. int estimatedSamplesPerBlock) = 0;
  26852. /** Called after playback has stopped, to let the filter free up any resources it
  26853. no longer needs.
  26854. */
  26855. virtual void releaseResources() = 0;
  26856. /** Renders the next block.
  26857. When this method is called, the buffer contains a number of channels which is
  26858. at least as great as the maximum number of input and output channels that
  26859. this filter is using. It will be filled with the filter's input data and
  26860. should be replaced with the filter's output.
  26861. So for example if your filter has 2 input channels and 4 output channels, then
  26862. the buffer will contain 4 channels, the first two being filled with the
  26863. input data. Your filter should read these, do its processing, and replace
  26864. the contents of all 4 channels with its output.
  26865. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  26866. all filled with data, and your filter should overwrite the first 2 of these
  26867. with its output. But be VERY careful not to write anything to the last 3
  26868. channels, as these might be mapped to memory that the host assumes is read-only!
  26869. Note that if you have more outputs than inputs, then only those channels that
  26870. correspond to an input channel are guaranteed to contain sensible data - e.g.
  26871. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  26872. but the last two channels may contain garbage, so you should be careful not to
  26873. let this pass through without being overwritten or cleared.
  26874. Also note that the buffer may have more channels than are strictly necessary,
  26875. but your should only read/write from the ones that your filter is supposed to
  26876. be using.
  26877. The number of samples in these buffers is NOT guaranteed to be the same for every
  26878. callback, and may be more or less than the estimated value given to prepareToPlay().
  26879. Your code must be able to cope with variable-sized blocks, or you're going to get
  26880. clicks and crashes!
  26881. If the filter is receiving a midi input, then the midiMessages array will be filled
  26882. with the midi messages for this block. Each message's timestamp will indicate the
  26883. message's time, as a number of samples from the start of the block.
  26884. Any messages left in the midi buffer when this method has finished are assumed to
  26885. be the filter's midi output. This means that your filter should be careful to
  26886. clear any incoming messages from the array if it doesn't want them to be passed-on.
  26887. Be very careful about what you do in this callback - it's going to be called by
  26888. the audio thread, so any kind of interaction with the UI is absolutely
  26889. out of the question. If you change a parameter in here and need to tell your UI to
  26890. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  26891. the UI components register as listeners, and then call sendChangeMessage() inside the
  26892. processBlock() method to send out an asynchronous message. You could also use
  26893. the AsyncUpdater class in a similar way.
  26894. */
  26895. virtual void processBlock (AudioSampleBuffer& buffer,
  26896. MidiBuffer& midiMessages) = 0;
  26897. /** Returns the current AudioPlayHead object that should be used to find
  26898. out the state and position of the playhead.
  26899. You can call this from your processBlock() method, and use the AudioPlayHead
  26900. object to get the details about the time of the start of the block currently
  26901. being processed.
  26902. If the host hasn't supplied a playhead object, this will return 0.
  26903. */
  26904. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  26905. /** Returns the current sample rate.
  26906. This can be called from your processBlock() method - it's not guaranteed
  26907. to be valid at any other time, and may return 0 if it's unknown.
  26908. */
  26909. double getSampleRate() const throw() { return sampleRate; }
  26910. /** Returns the current typical block size that is being used.
  26911. This can be called from your processBlock() method - it's not guaranteed
  26912. to be valid at any other time.
  26913. Remember it's not the ONLY block size that may be used when calling
  26914. processBlock, it's just the normal one. The actual block sizes used may be
  26915. larger or smaller than this, and will vary between successive calls.
  26916. */
  26917. int getBlockSize() const throw() { return blockSize; }
  26918. /** Returns the number of input channels that the host will be sending the filter.
  26919. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  26920. number of channels that your filter would prefer to have, and this method lets
  26921. you know how many the host is actually using.
  26922. Note that this method is only valid during or after the prepareToPlay()
  26923. method call. Until that point, the number of channels will be unknown.
  26924. */
  26925. int getNumInputChannels() const throw() { return numInputChannels; }
  26926. /** Returns the number of output channels that the host will be sending the filter.
  26927. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  26928. number of channels that your filter would prefer to have, and this method lets
  26929. you know how many the host is actually using.
  26930. Note that this method is only valid during or after the prepareToPlay()
  26931. method call. Until that point, the number of channels will be unknown.
  26932. */
  26933. int getNumOutputChannels() const throw() { return numOutputChannels; }
  26934. /** Returns the name of one of the input channels, as returned by the host.
  26935. The host might not supply very useful names for channels, and this might be
  26936. something like "1", "2", "left", "right", etc.
  26937. */
  26938. virtual const String getInputChannelName (const int channelIndex) const = 0;
  26939. /** Returns the name of one of the output channels, as returned by the host.
  26940. The host might not supply very useful names for channels, and this might be
  26941. something like "1", "2", "left", "right", etc.
  26942. */
  26943. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  26944. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  26945. virtual bool isInputChannelStereoPair (int index) const = 0;
  26946. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  26947. virtual bool isOutputChannelStereoPair (int index) const = 0;
  26948. /** This returns the number of samples delay that the filter imposes on the audio
  26949. passing through it.
  26950. The host will call this to find the latency - the filter itself should set this value
  26951. by calling setLatencySamples() as soon as it can during its initialisation.
  26952. */
  26953. int getLatencySamples() const throw() { return latencySamples; }
  26954. /** The filter should call this to set the number of samples delay that it introduces.
  26955. The filter should call this as soon as it can during initialisation, and can call it
  26956. later if the value changes.
  26957. */
  26958. void setLatencySamples (const int newLatency);
  26959. /** Returns true if the processor wants midi messages. */
  26960. virtual bool acceptsMidi() const = 0;
  26961. /** Returns true if the processor produces midi messages. */
  26962. virtual bool producesMidi() const = 0;
  26963. /** This returns a critical section that will automatically be locked while the host
  26964. is calling the processBlock() method.
  26965. Use it from your UI or other threads to lock access to variables that are used
  26966. by the process callback, but obviously be careful not to keep it locked for
  26967. too long, because that could cause stuttering playback. If you need to do something
  26968. that'll take a long time and need the processing to stop while it happens, use the
  26969. suspendProcessing() method instead.
  26970. @see suspendProcessing
  26971. */
  26972. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  26973. /** Enables and disables the processing callback.
  26974. If you need to do something time-consuming on a thread and would like to make sure
  26975. the audio processing callback doesn't happen until you've finished, use this
  26976. to disable the callback and re-enable it again afterwards.
  26977. E.g.
  26978. @code
  26979. void loadNewPatch()
  26980. {
  26981. suspendProcessing (true);
  26982. ..do something that takes ages..
  26983. suspendProcessing (false);
  26984. }
  26985. @endcode
  26986. If the host tries to make an audio callback while processing is suspended, the
  26987. filter will return an empty buffer, but won't block the audio thread like it would
  26988. do if you use the getCallbackLock() critical section to synchronise access.
  26989. If you're going to use this, your processBlock() method must call isSuspended() and
  26990. check whether it's suspended or not. If it is, then it should skip doing any real
  26991. processing, either emitting silence or passing the input through unchanged.
  26992. @see getCallbackLock
  26993. */
  26994. void suspendProcessing (const bool shouldBeSuspended);
  26995. /** Returns true if processing is currently suspended.
  26996. @see suspendProcessing
  26997. */
  26998. bool isSuspended() const throw() { return suspended; }
  26999. /** A plugin can override this to be told when it should reset any playing voices.
  27000. The default implementation does nothing, but a host may call this to tell the
  27001. plugin that it should stop any tails or sounds that have been left running.
  27002. */
  27003. virtual void reset();
  27004. /** Returns true if the processor is being run in an offline mode for rendering.
  27005. If the processor is being run live on realtime signals, this returns false.
  27006. If the mode is unknown, this will assume it's realtime and return false.
  27007. This value may be unreliable until the prepareToPlay() method has been called,
  27008. and could change each time prepareToPlay() is called.
  27009. @see setNonRealtime()
  27010. */
  27011. bool isNonRealtime() const throw() { return nonRealtime; }
  27012. /** Called by the host to tell this processor whether it's being used in a non-realime
  27013. capacity for offline rendering or bouncing.
  27014. Whatever value is passed-in will be
  27015. */
  27016. void setNonRealtime (const bool isNonRealtime) throw();
  27017. /** Creates the filter's UI.
  27018. This can return 0 if you want a UI-less filter, in which case the host may create
  27019. a generic UI that lets the user twiddle the parameters directly.
  27020. If you do want to pass back a component, the component should be created and set to
  27021. the correct size before returning it.
  27022. Remember not to do anything silly like allowing your filter to keep a pointer to
  27023. the component that gets created - it could be deleted later without any warning, which
  27024. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  27025. The correct way to handle the connection between an editor component and its
  27026. filter is to use something like a ChangeBroadcaster so that the editor can
  27027. register itself as a listener, and be told when a change occurs. This lets them
  27028. safely unregister themselves when they are deleted.
  27029. Here are a few things to bear in mind when writing an editor:
  27030. - Initially there won't be an editor, until the user opens one, or they might
  27031. not open one at all. Your filter mustn't rely on it being there.
  27032. - An editor object may be deleted and a replacement one created again at any time.
  27033. - It's safe to assume that an editor will be deleted before its filter.
  27034. */
  27035. virtual AudioProcessorEditor* createEditor() = 0;
  27036. /** Returns the active editor, if there is one.
  27037. Bear in mind this can return 0, even if an editor has previously been
  27038. opened.
  27039. */
  27040. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  27041. /** Returns the active editor, or if there isn't one, it will create one.
  27042. This may call createEditor() internally to create the component.
  27043. */
  27044. AudioProcessorEditor* createEditorIfNeeded();
  27045. /** This must return the correct value immediately after the object has been
  27046. created, and mustn't change the number of parameters later.
  27047. */
  27048. virtual int getNumParameters() = 0;
  27049. /** Returns the name of a particular parameter. */
  27050. virtual const String getParameterName (int parameterIndex) = 0;
  27051. /** Called by the host to find out the value of one of the filter's parameters.
  27052. The host will expect the value returned to be between 0 and 1.0.
  27053. This could be called quite frequently, so try to make your code efficient.
  27054. It's also likely to be called by non-UI threads, so the code in here should
  27055. be thread-aware.
  27056. */
  27057. virtual float getParameter (int parameterIndex) = 0;
  27058. /** Returns the value of a parameter as a text string. */
  27059. virtual const String getParameterText (int parameterIndex) = 0;
  27060. /** The host will call this method to change the value of one of the filter's parameters.
  27061. The host may call this at any time, including during the audio processing
  27062. callback, so the filter has to process this very fast and avoid blocking.
  27063. If you want to set the value of a parameter internally, e.g. from your
  27064. editor component, then don't call this directly - instead, use the
  27065. setParameterNotifyingHost() method, which will also send a message to
  27066. the host telling it about the change. If the message isn't sent, the host
  27067. won't be able to automate your parameters properly.
  27068. The value passed will be between 0 and 1.0.
  27069. */
  27070. virtual void setParameter (int parameterIndex,
  27071. float newValue) = 0;
  27072. /** Your filter can call this when it needs to change one of its parameters.
  27073. This could happen when the editor or some other internal operation changes
  27074. a parameter. This method will call the setParameter() method to change the
  27075. value, and will then send a message to the host telling it about the change.
  27076. Note that to make sure the host correctly handles automation, you should call
  27077. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  27078. tell the host when the user has started and stopped changing the parameter.
  27079. */
  27080. void setParameterNotifyingHost (int parameterIndex,
  27081. float newValue);
  27082. /** Returns true if the host can automate this parameter.
  27083. By default, this returns true for all parameters.
  27084. */
  27085. virtual bool isParameterAutomatable (int parameterIndex) const;
  27086. /** Should return true if this parameter is a "meta" parameter.
  27087. A meta-parameter is a parameter that changes other params. It is used
  27088. by some hosts (e.g. AudioUnit hosts).
  27089. By default this returns false.
  27090. */
  27091. virtual bool isMetaParameter (int parameterIndex) const;
  27092. /** Sends a signal to the host to tell it that the user is about to start changing this
  27093. parameter.
  27094. This allows the host to know when a parameter is actively being held by the user, and
  27095. it may use this information to help it record automation.
  27096. If you call this, it must be matched by a later call to endParameterChangeGesture().
  27097. */
  27098. void beginParameterChangeGesture (int parameterIndex);
  27099. /** Tells the host that the user has finished changing this parameter.
  27100. This allows the host to know when a parameter is actively being held by the user, and
  27101. it may use this information to help it record automation.
  27102. A call to this method must follow a call to beginParameterChangeGesture().
  27103. */
  27104. void endParameterChangeGesture (int parameterIndex);
  27105. /** The filter can call this when something (apart from a parameter value) has changed.
  27106. It sends a hint to the host that something like the program, number of parameters,
  27107. etc, has changed, and that it should update itself.
  27108. */
  27109. void updateHostDisplay();
  27110. /** Returns the number of preset programs the filter supports.
  27111. The value returned must be valid as soon as this object is created, and
  27112. must not change over its lifetime.
  27113. This value shouldn't be less than 1.
  27114. */
  27115. virtual int getNumPrograms() = 0;
  27116. /** Returns the number of the currently active program.
  27117. */
  27118. virtual int getCurrentProgram() = 0;
  27119. /** Called by the host to change the current program.
  27120. */
  27121. virtual void setCurrentProgram (int index) = 0;
  27122. /** Must return the name of a given program. */
  27123. virtual const String getProgramName (int index) = 0;
  27124. /** Called by the host to rename a program.
  27125. */
  27126. virtual void changeProgramName (int index, const String& newName) = 0;
  27127. /** The host will call this method when it wants to save the filter's internal state.
  27128. This must copy any info about the filter's state into the block of memory provided,
  27129. so that the host can store this and later restore it using setStateInformation().
  27130. Note that there's also a getCurrentProgramStateInformation() method, which only
  27131. stores the current program, not the state of the entire filter.
  27132. See also the helper function copyXmlToBinary() for storing settings as XML.
  27133. @see getCurrentProgramStateInformation
  27134. */
  27135. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  27136. /** The host will call this method if it wants to save the state of just the filter's
  27137. current program.
  27138. Unlike getStateInformation, this should only return the current program's state.
  27139. Not all hosts support this, and if you don't implement it, the base class
  27140. method just calls getStateInformation() instead. If you do implement it, be
  27141. sure to also implement getCurrentProgramStateInformation.
  27142. @see getStateInformation, setCurrentProgramStateInformation
  27143. */
  27144. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  27145. /** This must restore the filter's state from a block of data previously created
  27146. using getStateInformation().
  27147. Note that there's also a setCurrentProgramStateInformation() method, which tries
  27148. to restore just the current program, not the state of the entire filter.
  27149. See also the helper function getXmlFromBinary() for loading settings as XML.
  27150. @see setCurrentProgramStateInformation
  27151. */
  27152. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  27153. /** The host will call this method if it wants to restore the state of just the filter's
  27154. current program.
  27155. Not all hosts support this, and if you don't implement it, the base class
  27156. method just calls setStateInformation() instead. If you do implement it, be
  27157. sure to also implement getCurrentProgramStateInformation.
  27158. @see setStateInformation, getCurrentProgramStateInformation
  27159. */
  27160. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27161. /** Adds a listener that will be called when an aspect of this processor changes. */
  27162. void addListener (AudioProcessorListener* const newListener) throw();
  27163. /** Removes a previously added listener. */
  27164. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  27165. /** Not for public use - this is called before deleting an editor component. */
  27166. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  27167. /** Not for public use - this is called to initialise the processor. */
  27168. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  27169. /** Not for public use - this is called to initialise the processor before playing. */
  27170. void setPlayConfigDetails (const int numIns, const int numOuts,
  27171. const double sampleRate,
  27172. const int blockSize) throw();
  27173. juce_UseDebuggingNewOperator
  27174. protected:
  27175. /** Helper function that just converts an xml element into a binary blob.
  27176. Use this in your filter's getStateInformation() method if you want to
  27177. store its state as xml.
  27178. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  27179. from a binary blob.
  27180. */
  27181. static void copyXmlToBinary (const XmlElement& xml,
  27182. JUCE_NAMESPACE::MemoryBlock& destData);
  27183. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  27184. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  27185. an XmlElement object that the caller must delete when no longer needed.
  27186. */
  27187. static XmlElement* getXmlFromBinary (const void* data,
  27188. const int sizeInBytes);
  27189. /** @internal */
  27190. AudioPlayHead* playHead;
  27191. /** @internal */
  27192. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  27193. private:
  27194. VoidArray listeners;
  27195. AudioProcessorEditor* activeEditor;
  27196. double sampleRate;
  27197. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  27198. bool suspended, nonRealtime;
  27199. CriticalSection callbackLock, listenerLock;
  27200. #ifdef JUCE_DEBUG
  27201. BitArray changingParams;
  27202. #endif
  27203. AudioProcessor (const AudioProcessor&);
  27204. const AudioProcessor& operator= (const AudioProcessor&);
  27205. };
  27206. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  27207. /********* End of inlined file: juce_AudioProcessor.h *********/
  27208. /********* Start of inlined file: juce_PluginDescription.h *********/
  27209. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27210. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27211. /**
  27212. A small class to represent some facts about a particular type of plugin.
  27213. This class is for storing and managing the details about a plugin without
  27214. actually having to load an instance of it.
  27215. A KnownPluginList contains a list of PluginDescription objects.
  27216. @see KnownPluginList
  27217. */
  27218. class JUCE_API PluginDescription
  27219. {
  27220. public:
  27221. PluginDescription() throw();
  27222. PluginDescription (const PluginDescription& other) throw();
  27223. const PluginDescription& operator= (const PluginDescription& other) throw();
  27224. ~PluginDescription() throw();
  27225. /** The name of the plugin. */
  27226. String name;
  27227. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  27228. */
  27229. String pluginFormatName;
  27230. /** A category, such as "Dynamics", "Reverbs", etc.
  27231. */
  27232. String category;
  27233. /** The manufacturer. */
  27234. String manufacturerName;
  27235. /** The version. This string doesn't have any particular format. */
  27236. String version;
  27237. /** Either the file containing the plugin module, or some other unique way
  27238. of identifying it.
  27239. E.g. for an AU, this would be an ID string that the component manager
  27240. could use to retrieve the plugin. For a VST, it's the file path.
  27241. */
  27242. String fileOrIdentifier;
  27243. /** The last time the plugin file was changed.
  27244. This is handy when scanning for new or changed plugins.
  27245. */
  27246. Time lastFileModTime;
  27247. /** A unique ID for the plugin.
  27248. Note that this might not be unique between formats, e.g. a VST and some
  27249. other format might actually have the same id.
  27250. @see createIdentifierString
  27251. */
  27252. int uid;
  27253. /** True if the plugin identifies itself as a synthesiser. */
  27254. bool isInstrument;
  27255. /** The number of inputs. */
  27256. int numInputChannels;
  27257. /** The number of outputs. */
  27258. int numOutputChannels;
  27259. /** Returns true if the two descriptions refer the the same plugin.
  27260. This isn't quite as simple as them just having the same file (because of
  27261. shell plugins).
  27262. */
  27263. bool isDuplicateOf (const PluginDescription& other) const;
  27264. /** Returns a string that can be saved and used to uniquely identify the
  27265. plugin again.
  27266. This contains less info than the XML encoding, and is independent of the
  27267. plugin's file location, so can be used to store a plugin ID for use
  27268. across different machines.
  27269. */
  27270. const String createIdentifierString() const throw();
  27271. /** Creates an XML object containing these details.
  27272. @see loadFromXml
  27273. */
  27274. XmlElement* createXml() const;
  27275. /** Reloads the info in this structure from an XML record that was previously
  27276. saved with createXML().
  27277. Returns true if the XML was a valid plugin description.
  27278. */
  27279. bool loadFromXml (const XmlElement& xml);
  27280. juce_UseDebuggingNewOperator
  27281. };
  27282. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27283. /********* End of inlined file: juce_PluginDescription.h *********/
  27284. /**
  27285. Base class for an active instance of a plugin.
  27286. This derives from the AudioProcessor class, and adds some extra functionality
  27287. that helps when wrapping dynamically loaded plugins.
  27288. @see AudioProcessor, AudioPluginFormat
  27289. */
  27290. class JUCE_API AudioPluginInstance : public AudioProcessor
  27291. {
  27292. public:
  27293. /** Destructor.
  27294. Make sure that you delete any UI components that belong to this plugin before
  27295. deleting the plugin.
  27296. */
  27297. virtual ~AudioPluginInstance();
  27298. /** Fills-in the appropriate parts of this plugin description object.
  27299. */
  27300. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  27301. juce_UseDebuggingNewOperator
  27302. protected:
  27303. AudioPluginInstance();
  27304. AudioPluginInstance (const AudioPluginInstance&);
  27305. const AudioPluginInstance& operator= (const AudioPluginInstance&);
  27306. };
  27307. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  27308. /********* End of inlined file: juce_AudioPluginInstance.h *********/
  27309. class PluginDescription;
  27310. /**
  27311. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  27312. Use the static getNumFormats() and getFormat() calls to find the types
  27313. of format that are available.
  27314. */
  27315. class JUCE_API AudioPluginFormat
  27316. {
  27317. public:
  27318. /** Destructor. */
  27319. virtual ~AudioPluginFormat();
  27320. /** Returns the format name.
  27321. E.g. "VST", "AudioUnit", etc.
  27322. */
  27323. virtual const String getName() const = 0;
  27324. /** This tries to create descriptions for all the plugin types available in
  27325. a binary module file.
  27326. The file will be some kind of DLL or bundle.
  27327. Normally there will only be one type returned, but some plugins
  27328. (e.g. VST shells) can use a single DLL to create a set of different plugin
  27329. subtypes, so in that case, each subtype is returned as a separate object.
  27330. */
  27331. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  27332. const String& fileOrIdentifier) = 0;
  27333. /** Tries to recreate a type from a previously generated PluginDescription.
  27334. @see PluginDescription::createInstance
  27335. */
  27336. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  27337. /** Should do a quick check to see if this file or directory might be a plugin of
  27338. this format.
  27339. This is for searching for potential files, so it shouldn't actually try to
  27340. load the plugin or do anything time-consuming.
  27341. */
  27342. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  27343. /** Returns a readable version of the name of the plugin that this identifier refers to.
  27344. */
  27345. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  27346. /** Checks whether this plugin could possibly be loaded.
  27347. It doesn't actually need to load it, just to check whether the file or component
  27348. still exists.
  27349. */
  27350. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  27351. /** Searches a suggested set of directories for any plugins in this format.
  27352. The path might be ignored, e.g. by AUs, which are found by the OS rather
  27353. than manually.
  27354. */
  27355. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  27356. const bool recursive) = 0;
  27357. /** Returns the typical places to look for this kind of plugin.
  27358. Note that if this returns no paths, it means that the format can't be scanned-for
  27359. (i.e. it's an internal format that doesn't live in files)
  27360. */
  27361. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  27362. juce_UseDebuggingNewOperator
  27363. protected:
  27364. AudioPluginFormat() throw();
  27365. AudioPluginFormat (const AudioPluginFormat&);
  27366. const AudioPluginFormat& operator= (const AudioPluginFormat&);
  27367. };
  27368. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  27369. /********* End of inlined file: juce_AudioPluginFormat.h *********/
  27370. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  27371. /**
  27372. Implements a plugin format manager for AudioUnits.
  27373. */
  27374. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  27375. {
  27376. public:
  27377. AudioUnitPluginFormat();
  27378. ~AudioUnitPluginFormat();
  27379. const String getName() const { return "AudioUnit"; }
  27380. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27381. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27382. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27383. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  27384. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  27385. bool doesPluginStillExist (const PluginDescription& desc);
  27386. const FileSearchPath getDefaultLocationsToSearch();
  27387. juce_UseDebuggingNewOperator
  27388. private:
  27389. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  27390. const AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  27391. };
  27392. #endif
  27393. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27394. /********* End of inlined file: juce_AudioUnitPluginFormat.h *********/
  27395. #endif
  27396. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27397. /********* Start of inlined file: juce_DirectXPluginFormat.h *********/
  27398. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27399. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27400. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  27401. // Sorry, this file is just a placeholder at the moment!...
  27402. /**
  27403. Implements a plugin format manager for DirectX plugins.
  27404. */
  27405. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  27406. {
  27407. public:
  27408. DirectXPluginFormat();
  27409. ~DirectXPluginFormat();
  27410. const String getName() const { return "DirectX"; }
  27411. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27412. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27413. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27414. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  27415. const FileSearchPath getDefaultLocationsToSearch();
  27416. juce_UseDebuggingNewOperator
  27417. private:
  27418. DirectXPluginFormat (const DirectXPluginFormat&);
  27419. const DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  27420. };
  27421. #endif
  27422. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  27423. /********* End of inlined file: juce_DirectXPluginFormat.h *********/
  27424. #endif
  27425. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27426. /********* Start of inlined file: juce_LADSPAPluginFormat.h *********/
  27427. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27428. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27429. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  27430. // Sorry, this file is just a placeholder at the moment!...
  27431. /**
  27432. Implements a plugin format manager for DirectX plugins.
  27433. */
  27434. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  27435. {
  27436. public:
  27437. LADSPAPluginFormat();
  27438. ~LADSPAPluginFormat();
  27439. const String getName() const { return "LADSPA"; }
  27440. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27441. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27442. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27443. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  27444. const FileSearchPath getDefaultLocationsToSearch();
  27445. juce_UseDebuggingNewOperator
  27446. private:
  27447. LADSPAPluginFormat (const LADSPAPluginFormat&);
  27448. const LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  27449. };
  27450. #endif
  27451. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  27452. /********* End of inlined file: juce_LADSPAPluginFormat.h *********/
  27453. #endif
  27454. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27455. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  27456. #ifdef __aeffect__
  27457. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27458. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27459. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  27460. events to the list.
  27461. This is used by both the VST hosting code and the plugin wrapper.
  27462. */
  27463. class VSTMidiEventList
  27464. {
  27465. public:
  27466. VSTMidiEventList()
  27467. : numEventsUsed (0), numEventsAllocated (0)
  27468. {
  27469. }
  27470. ~VSTMidiEventList()
  27471. {
  27472. freeEvents();
  27473. }
  27474. void clear()
  27475. {
  27476. numEventsUsed = 0;
  27477. if (events != 0)
  27478. events->numEvents = 0;
  27479. }
  27480. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  27481. {
  27482. ensureSize (numEventsUsed + 1);
  27483. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  27484. events->numEvents = ++numEventsUsed;
  27485. if (numBytes <= 4)
  27486. {
  27487. if (e->type == kVstSysExType)
  27488. {
  27489. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  27490. e->type = kVstMidiType;
  27491. e->byteSize = sizeof (VstMidiEvent);
  27492. e->noteLength = 0;
  27493. e->noteOffset = 0;
  27494. e->detune = 0;
  27495. e->noteOffVelocity = 0;
  27496. }
  27497. e->deltaFrames = frameOffset;
  27498. memcpy (e->midiData, midiData, numBytes);
  27499. }
  27500. else
  27501. {
  27502. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  27503. if (se->type == kVstSysExType)
  27504. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  27505. else
  27506. se->sysexDump = (char*) juce_malloc (numBytes);
  27507. memcpy (se->sysexDump, midiData, numBytes);
  27508. se->type = kVstSysExType;
  27509. se->byteSize = sizeof (VstMidiSysexEvent);
  27510. se->deltaFrames = frameOffset;
  27511. se->flags = 0;
  27512. se->dumpBytes = numBytes;
  27513. se->resvd1 = 0;
  27514. se->resvd2 = 0;
  27515. }
  27516. }
  27517. // Handy method to pull the events out of an event buffer supplied by the host
  27518. // or plugin.
  27519. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  27520. {
  27521. for (int i = 0; i < events->numEvents; ++i)
  27522. {
  27523. const VstEvent* const e = events->events[i];
  27524. if (e != 0)
  27525. {
  27526. if (e->type == kVstMidiType)
  27527. {
  27528. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  27529. 4, e->deltaFrames);
  27530. }
  27531. else if (e->type == kVstSysExType)
  27532. {
  27533. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  27534. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  27535. e->deltaFrames);
  27536. }
  27537. }
  27538. }
  27539. }
  27540. void ensureSize (int numEventsNeeded)
  27541. {
  27542. if (numEventsNeeded > numEventsAllocated)
  27543. {
  27544. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  27545. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  27546. if (events == 0)
  27547. events.calloc (size, 1);
  27548. else
  27549. events.realloc (size, 1);
  27550. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  27551. {
  27552. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  27553. (int) sizeof (VstMidiSysexEvent)));
  27554. e->type = kVstMidiType;
  27555. e->byteSize = sizeof (VstMidiEvent);
  27556. events->events[i] = (VstEvent*) e;
  27557. }
  27558. numEventsAllocated = numEventsNeeded;
  27559. }
  27560. }
  27561. void freeEvents()
  27562. {
  27563. if (events != 0)
  27564. {
  27565. for (int i = numEventsAllocated; --i >= 0;)
  27566. {
  27567. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  27568. if (e->type == kVstSysExType)
  27569. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  27570. juce_free (e);
  27571. }
  27572. events.free();
  27573. numEventsUsed = 0;
  27574. numEventsAllocated = 0;
  27575. }
  27576. }
  27577. HeapBlock <VstEvents> events;
  27578. private:
  27579. int numEventsUsed, numEventsAllocated;
  27580. };
  27581. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27582. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  27583. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  27584. #endif
  27585. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27586. /********* Start of inlined file: juce_VSTPluginFormat.h *********/
  27587. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27588. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27589. #if JUCE_PLUGINHOST_VST
  27590. /**
  27591. Implements a plugin format manager for VSTs.
  27592. */
  27593. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  27594. {
  27595. public:
  27596. VSTPluginFormat();
  27597. ~VSTPluginFormat();
  27598. const String getName() const { return "VST"; }
  27599. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  27600. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  27601. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  27602. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  27603. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive);
  27604. bool doesPluginStillExist (const PluginDescription& desc);
  27605. const FileSearchPath getDefaultLocationsToSearch();
  27606. juce_UseDebuggingNewOperator
  27607. private:
  27608. VSTPluginFormat (const VSTPluginFormat&);
  27609. const VSTPluginFormat& operator= (const VSTPluginFormat&);
  27610. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  27611. };
  27612. #endif
  27613. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  27614. /********* End of inlined file: juce_VSTPluginFormat.h *********/
  27615. #endif
  27616. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  27617. #endif
  27618. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27619. /********* Start of inlined file: juce_AudioPluginFormatManager.h *********/
  27620. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27621. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27622. /**
  27623. This maintains a list of known AudioPluginFormats.
  27624. @see AudioPluginFormat
  27625. */
  27626. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  27627. {
  27628. public:
  27629. AudioPluginFormatManager() throw();
  27630. /** Destructor. */
  27631. ~AudioPluginFormatManager() throw();
  27632. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  27633. /** Adds any formats that it knows about, e.g. VST.
  27634. */
  27635. void addDefaultFormats();
  27636. /** Returns the number of types of format that are available.
  27637. Use getFormat() to get one of them.
  27638. */
  27639. int getNumFormats() throw();
  27640. /** Returns one of the available formats.
  27641. @see getNumFormats
  27642. */
  27643. AudioPluginFormat* getFormat (const int index) throw();
  27644. /** Adds a format to the list.
  27645. The object passed in will be owned and deleted by the manager.
  27646. */
  27647. void addFormat (AudioPluginFormat* const format) throw();
  27648. /** Tries to load the type for this description, by trying all the formats
  27649. that this manager knows about.
  27650. The caller is responsible for deleting the object that is returned.
  27651. If it can't load the plugin, it returns 0 and leaves a message in the
  27652. errorMessage string.
  27653. */
  27654. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  27655. String& errorMessage) const;
  27656. /** Checks that the file or component for this plugin actually still exists.
  27657. (This won't try to load the plugin)
  27658. */
  27659. bool doesPluginStillExist (const PluginDescription& description) const;
  27660. juce_UseDebuggingNewOperator
  27661. private:
  27662. OwnedArray <AudioPluginFormat> formats;
  27663. AudioPluginFormatManager (const AudioPluginFormatManager&);
  27664. const AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  27665. };
  27666. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  27667. /********* End of inlined file: juce_AudioPluginFormatManager.h *********/
  27668. #endif
  27669. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  27670. #endif
  27671. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27672. /********* Start of inlined file: juce_KnownPluginList.h *********/
  27673. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27674. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27675. /**
  27676. Manages a list of plugin types.
  27677. This can be easily edited, saved and loaded, and used to create instances of
  27678. the plugin types in it.
  27679. @see PluginListComponent
  27680. */
  27681. class JUCE_API KnownPluginList : public ChangeBroadcaster
  27682. {
  27683. public:
  27684. /** Creates an empty list.
  27685. */
  27686. KnownPluginList();
  27687. /** Destructor. */
  27688. ~KnownPluginList();
  27689. /** Clears the list. */
  27690. void clear();
  27691. /** Returns the number of types currently in the list.
  27692. @see getType
  27693. */
  27694. int getNumTypes() const throw() { return types.size(); }
  27695. /** Returns one of the types.
  27696. @see getNumTypes
  27697. */
  27698. PluginDescription* getType (const int index) const throw() { return types [index]; }
  27699. /** Looks for a type in the list which comes from this file.
  27700. */
  27701. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  27702. /** Looks for a type in the list which matches a plugin type ID.
  27703. The identifierString parameter must have been created by
  27704. PluginDescription::createIdentifierString().
  27705. */
  27706. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  27707. /** Adds a type manually from its description. */
  27708. bool addType (const PluginDescription& type);
  27709. /** Removes a type. */
  27710. void removeType (const int index) throw();
  27711. /** Looks for all types that can be loaded from a given file, and adds them
  27712. to the list.
  27713. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  27714. re-tested if it's not already in the list, or if the file's modification
  27715. time has changed since the list was created. If dontRescanIfAlreadyInList is
  27716. false, the file will always be reloaded and tested.
  27717. Returns true if any new types were added, and all the types found in this
  27718. file (even if it was already known and hasn't been re-scanned) get returned
  27719. in the array.
  27720. */
  27721. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  27722. const bool dontRescanIfAlreadyInList,
  27723. OwnedArray <PluginDescription>& typesFound,
  27724. AudioPluginFormat& formatToUse);
  27725. /** Returns true if the specified file is already known about and if it
  27726. hasn't been modified since our entry was created.
  27727. */
  27728. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  27729. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  27730. If any types are found in the files, their descriptions are returned in the array.
  27731. */
  27732. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  27733. OwnedArray <PluginDescription>& typesFound);
  27734. /** Sort methods used to change the order of the plugins in the list.
  27735. */
  27736. enum SortMethod
  27737. {
  27738. defaultOrder = 0,
  27739. sortAlphabetically,
  27740. sortByCategory,
  27741. sortByManufacturer,
  27742. sortByFileSystemLocation
  27743. };
  27744. /** Adds all the plugin types to a popup menu so that the user can select one.
  27745. Depending on the sort method, it may add sub-menus for categories,
  27746. manufacturers, etc.
  27747. Use getIndexChosenByMenu() to find out the type that was chosen.
  27748. */
  27749. void addToMenu (PopupMenu& menu,
  27750. const SortMethod sortMethod) const;
  27751. /** Converts a menu item index that has been chosen into its index in this list.
  27752. Returns -1 if it's not an ID that was used.
  27753. @see addToMenu
  27754. */
  27755. int getIndexChosenByMenu (const int menuResultCode) const;
  27756. /** Sorts the list. */
  27757. void sort (const SortMethod method);
  27758. /** Creates some XML that can be used to store the state of this list.
  27759. */
  27760. XmlElement* createXml() const;
  27761. /** Recreates the state of this list from its stored XML format.
  27762. */
  27763. void recreateFromXml (const XmlElement& xml);
  27764. juce_UseDebuggingNewOperator
  27765. private:
  27766. OwnedArray <PluginDescription> types;
  27767. KnownPluginList (const KnownPluginList&);
  27768. const KnownPluginList& operator= (const KnownPluginList&);
  27769. };
  27770. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  27771. /********* End of inlined file: juce_KnownPluginList.h *********/
  27772. #endif
  27773. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  27774. #endif
  27775. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27776. /********* Start of inlined file: juce_PluginDirectoryScanner.h *********/
  27777. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27778. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27779. /**
  27780. Scans a directory for plugins, and adds them to a KnownPluginList.
  27781. To use one of these, create it and call scanNextFile() repeatedly, until
  27782. it returns false.
  27783. */
  27784. class JUCE_API PluginDirectoryScanner
  27785. {
  27786. public:
  27787. /**
  27788. Creates a scanner.
  27789. @param listToAddResultsTo this will get the new types added to it.
  27790. @param formatToLookFor this is the type of format that you want to look for
  27791. @param directoriesToSearch the path to search
  27792. @param searchRecursively true to search recursively
  27793. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  27794. be used as a file to store the names of any plugins
  27795. that crash during initialisation. If there are
  27796. any plugins listed in it, then these will always
  27797. be scanned after all other possible files have
  27798. been tried - in this way, even if there's a few
  27799. dodgy plugins in your path, then a couple of rescans
  27800. will still manage to find all the proper plugins.
  27801. It's probably best to choose a file in the user's
  27802. application data directory (alongside your app's
  27803. settings file) for this. The file format it uses
  27804. is just a list of filenames of the modules that
  27805. failed.
  27806. */
  27807. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  27808. AudioPluginFormat& formatToLookFor,
  27809. FileSearchPath directoriesToSearch,
  27810. const bool searchRecursively,
  27811. const File& deadMansPedalFile);
  27812. /** Destructor. */
  27813. ~PluginDirectoryScanner();
  27814. /** Tries the next likely-looking file.
  27815. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  27816. re-tested if it's not already in the list, or if the file's modification
  27817. time has changed since the list was created. If dontRescanIfAlreadyInList is
  27818. false, the file will always be reloaded and tested.
  27819. Returns false when there are no more files to try.
  27820. */
  27821. bool scanNextFile (const bool dontRescanIfAlreadyInList);
  27822. /** Returns the description of the plugin that will be scanned during the next
  27823. call to scanNextFile().
  27824. This is handy if you want to show the user which file is currently getting
  27825. scanned.
  27826. */
  27827. const String getNextPluginFileThatWillBeScanned() const throw();
  27828. /** Returns the estimated progress, between 0 and 1.
  27829. */
  27830. float getProgress() const { return progress; }
  27831. /** This returns a list of all the filenames of things that looked like being
  27832. a plugin file, but which failed to open for some reason.
  27833. */
  27834. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  27835. juce_UseDebuggingNewOperator
  27836. private:
  27837. KnownPluginList& list;
  27838. AudioPluginFormat& format;
  27839. StringArray filesOrIdentifiersToScan;
  27840. File deadMansPedalFile;
  27841. StringArray failedFiles;
  27842. int nextIndex;
  27843. float progress;
  27844. const StringArray getDeadMansPedalFile() throw();
  27845. void setDeadMansPedalFile (const StringArray& newContents) throw();
  27846. PluginDirectoryScanner (const PluginDirectoryScanner&);
  27847. const PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  27848. };
  27849. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  27850. /********* End of inlined file: juce_PluginDirectoryScanner.h *********/
  27851. #endif
  27852. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27853. /********* Start of inlined file: juce_PluginListComponent.h *********/
  27854. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27855. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  27856. /********* Start of inlined file: juce_ListBox.h *********/
  27857. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  27858. #define __JUCE_LISTBOX_JUCEHEADER__
  27859. class ListViewport;
  27860. /**
  27861. A subclass of this is used to drive a ListBox.
  27862. @see ListBox
  27863. */
  27864. class JUCE_API ListBoxModel
  27865. {
  27866. public:
  27867. /** Destructor. */
  27868. virtual ~ListBoxModel() {}
  27869. /** This has to return the number of items in the list.
  27870. @see ListBox::getNumRows()
  27871. */
  27872. virtual int getNumRows() = 0;
  27873. /** This method must be implemented to draw a row of the list.
  27874. */
  27875. virtual void paintListBoxItem (int rowNumber,
  27876. Graphics& g,
  27877. int width, int height,
  27878. bool rowIsSelected) = 0;
  27879. /** This is used to create or update a custom component to go in a row of the list.
  27880. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  27881. and handle mouse clicks with listBoxItemClicked().
  27882. This method will be called whenever a custom component might need to be updated - e.g.
  27883. when the table is changed, or TableListBox::updateContent() is called.
  27884. If you don't need a custom component for the specified row, then return 0.
  27885. If you do want a custom component, and the existingComponentToUpdate is null, then
  27886. this method must create a suitable new component and return it.
  27887. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  27888. by this method. In this case, the method must either update it to make sure it's correctly representing
  27889. the given row (which may be different from the one that the component was created for), or it can
  27890. delete this component and return a new one.
  27891. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  27892. */
  27893. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  27894. Component* existingComponentToUpdate);
  27895. /** This can be overridden to react to the user clicking on a row.
  27896. @see listBoxItemDoubleClicked
  27897. */
  27898. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  27899. /** This can be overridden to react to the user double-clicking on a row.
  27900. @see listBoxItemClicked
  27901. */
  27902. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  27903. /** This can be overridden to react to the user double-clicking on a part of the list where
  27904. there are no rows.
  27905. @see listBoxItemClicked
  27906. */
  27907. virtual void backgroundClicked();
  27908. /** Override this to be informed when rows are selected or deselected.
  27909. This will be called whenever a row is selected or deselected. If a range of
  27910. rows is selected all at once, this will just be called once for that event.
  27911. @param lastRowSelected the last row that the user selected. If no
  27912. rows are currently selected, this may be -1.
  27913. */
  27914. virtual void selectedRowsChanged (int lastRowSelected);
  27915. /** Override this to be informed when the delete key is pressed.
  27916. If no rows are selected when they press the key, this won't be called.
  27917. @param lastRowSelected the last row that had been selected when they pressed the
  27918. key - if there are multiple selections, this might not be
  27919. very useful
  27920. */
  27921. virtual void deleteKeyPressed (int lastRowSelected);
  27922. /** Override this to be informed when the return key is pressed.
  27923. If no rows are selected when they press the key, this won't be called.
  27924. @param lastRowSelected the last row that had been selected when they pressed the
  27925. key - if there are multiple selections, this might not be
  27926. very useful
  27927. */
  27928. virtual void returnKeyPressed (int lastRowSelected);
  27929. /** Override this to be informed when the list is scrolled.
  27930. This might be caused by the user moving the scrollbar, or by programmatic changes
  27931. to the list position.
  27932. */
  27933. virtual void listWasScrolled();
  27934. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  27935. If this returns a non-empty name then when the user drags a row, the listbox will
  27936. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  27937. a drag-and-drop operation, using this string as the source description, with the listbox
  27938. itself as the source component.
  27939. @see DragAndDropContainer::startDragging
  27940. */
  27941. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  27942. /** You can override this to provide tool tips for specific rows.
  27943. @see TooltipClient
  27944. */
  27945. virtual const String getTooltipForRow (int row);
  27946. };
  27947. /**
  27948. A list of items that can be scrolled vertically.
  27949. To create a list, you'll need to create a subclass of ListBoxModel. This can
  27950. either paint each row of the list and respond to events via callbacks, or for
  27951. more specialised tasks, it can supply a custom component to fill each row.
  27952. @see ComboBox, TableListBox
  27953. */
  27954. class JUCE_API ListBox : public Component,
  27955. public SettableTooltipClient
  27956. {
  27957. public:
  27958. /** Creates a ListBox.
  27959. The model pointer passed-in can be null, in which case you can set it later
  27960. with setModel().
  27961. */
  27962. ListBox (const String& componentName,
  27963. ListBoxModel* const model);
  27964. /** Destructor. */
  27965. ~ListBox();
  27966. /** Changes the current data model to display. */
  27967. void setModel (ListBoxModel* const newModel);
  27968. /** Returns the current list model. */
  27969. ListBoxModel* getModel() const throw() { return model; }
  27970. /** Causes the list to refresh its content.
  27971. Call this when the number of rows in the list changes, or if you want it
  27972. to call refreshComponentForRow() on all the row components.
  27973. Be careful not to call it from a different thread, though, as it's not
  27974. thread-safe.
  27975. */
  27976. void updateContent();
  27977. /** Turns on multiple-selection of rows.
  27978. By default this is disabled.
  27979. When your row component gets clicked you'll need to call the
  27980. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  27981. clicked and to get it to do the appropriate selection based on whether
  27982. the ctrl/shift keys are held down.
  27983. */
  27984. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  27985. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  27986. This function is here primarily for the ComboBox class to use, but might be
  27987. useful for some other purpose too.
  27988. */
  27989. void setMouseMoveSelectsRows (bool shouldSelect);
  27990. /** Selects a row.
  27991. If the row is already selected, this won't do anything.
  27992. @param rowNumber the row to select
  27993. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  27994. the selected row is off-screen, it'll scroll to make
  27995. sure that row is on-screen
  27996. @param deselectOthersFirst if true and there are multiple selections, these will
  27997. first be deselected before this item is selected
  27998. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  27999. deselectAllRows, selectRangeOfRows
  28000. */
  28001. void selectRow (const int rowNumber,
  28002. bool dontScrollToShowThisRow = false,
  28003. bool deselectOthersFirst = true);
  28004. /** Selects a set of rows.
  28005. This will add these rows to the current selection, so you might need to
  28006. clear the current selection first with deselectAllRows()
  28007. @param firstRow the first row to select (inclusive)
  28008. @param lastRow the last row to select (inclusive)
  28009. */
  28010. void selectRangeOfRows (int firstRow,
  28011. int lastRow);
  28012. /** Deselects a row.
  28013. If it's not currently selected, this will do nothing.
  28014. @see selectRow, deselectAllRows
  28015. */
  28016. void deselectRow (const int rowNumber);
  28017. /** Deselects any currently selected rows.
  28018. @see deselectRow
  28019. */
  28020. void deselectAllRows();
  28021. /** Selects or deselects a row.
  28022. If the row's currently selected, this deselects it, and vice-versa.
  28023. */
  28024. void flipRowSelection (const int rowNumber);
  28025. /** Returns a sparse set indicating the rows that are currently selected.
  28026. @see setSelectedRows
  28027. */
  28028. const SparseSet<int> getSelectedRows() const;
  28029. /** Sets the rows that should be selected, based on an explicit set of ranges.
  28030. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  28031. method will be called. If it's false, no notification will be sent to the model.
  28032. @see getSelectedRows
  28033. */
  28034. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  28035. const bool sendNotificationEventToModel = true);
  28036. /** Checks whether a row is selected.
  28037. */
  28038. bool isRowSelected (const int rowNumber) const;
  28039. /** Returns the number of rows that are currently selected.
  28040. @see getSelectedRow, isRowSelected, getLastRowSelected
  28041. */
  28042. int getNumSelectedRows() const;
  28043. /** Returns the row number of a selected row.
  28044. This will return the row number of the Nth selected row. The row numbers returned will
  28045. be sorted in order from low to high.
  28046. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  28047. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  28048. selected
  28049. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  28050. */
  28051. int getSelectedRow (const int index = 0) const;
  28052. /** Returns the last row that the user selected.
  28053. This isn't the same as the highest row number that is currently selected - if the user
  28054. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  28055. If nothing is selected, it will return -1.
  28056. */
  28057. int getLastRowSelected() const;
  28058. /** Multiply-selects rows based on the modifier keys.
  28059. If no modifier keys are down, this will select the given row and
  28060. deselect any others.
  28061. If the ctrl (or command on the Mac) key is down, it'll flip the
  28062. state of the selected row.
  28063. If the shift key is down, it'll select up to the given row from the
  28064. last row selected.
  28065. @see selectRow
  28066. */
  28067. void selectRowsBasedOnModifierKeys (const int rowThatWasClickedOn,
  28068. const ModifierKeys& modifiers);
  28069. /** Scrolls the list to a particular position.
  28070. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  28071. 1.0 scrolls to the bottom.
  28072. If the total number of rows all fit onto the screen at once, then this
  28073. method won't do anything.
  28074. @see getVerticalPosition
  28075. */
  28076. void setVerticalPosition (const double newProportion);
  28077. /** Returns the current vertical position as a proportion of the total.
  28078. This can be used in conjunction with setVerticalPosition() to save and restore
  28079. the list's position. It returns a value in the range 0 to 1.
  28080. @see setVerticalPosition
  28081. */
  28082. double getVerticalPosition() const;
  28083. /** Scrolls if necessary to make sure that a particular row is visible.
  28084. */
  28085. void scrollToEnsureRowIsOnscreen (const int row);
  28086. /** Returns a pointer to the scrollbar.
  28087. (Unlikely to be useful for most people).
  28088. */
  28089. ScrollBar* getVerticalScrollBar() const throw();
  28090. /** Returns a pointer to the scrollbar.
  28091. (Unlikely to be useful for most people).
  28092. */
  28093. ScrollBar* getHorizontalScrollBar() const throw();
  28094. /** Finds the row index that contains a given x,y position.
  28095. The position is relative to the ListBox's top-left.
  28096. If no row exists at this position, the method will return -1.
  28097. @see getComponentForRowNumber
  28098. */
  28099. int getRowContainingPosition (const int x, const int y) const throw();
  28100. /** Finds a row index that would be the most suitable place to insert a new
  28101. item for a given position.
  28102. This is useful when the user is e.g. dragging and dropping onto the listbox,
  28103. because it lets you easily choose the best position to insert the item that
  28104. they drop, based on where they drop it.
  28105. If the position is out of range, this will return -1. If the position is
  28106. beyond the end of the list, it will return getNumRows() to indicate the end
  28107. of the list.
  28108. @see getComponentForRowNumber
  28109. */
  28110. int getInsertionIndexForPosition (const int x, const int y) const throw();
  28111. /** Returns the position of one of the rows, relative to the top-left of
  28112. the listbox.
  28113. This may be off-screen, and the range of the row number that is passed-in is
  28114. not checked to see if it's a valid row.
  28115. */
  28116. const Rectangle getRowPosition (const int rowNumber,
  28117. const bool relativeToComponentTopLeft) const throw();
  28118. /** Finds the row component for a given row in the list.
  28119. The component returned will have been created using createRowComponent().
  28120. If the component for this row is off-screen or if the row is out-of-range,
  28121. this will return 0.
  28122. @see getRowContainingPosition
  28123. */
  28124. Component* getComponentForRowNumber (const int rowNumber) const throw();
  28125. /** Returns the row number that the given component represents.
  28126. If the component isn't one of the list's rows, this will return -1.
  28127. */
  28128. int getRowNumberOfComponent (Component* const rowComponent) const throw();
  28129. /** Returns the width of a row (which may be less than the width of this component
  28130. if there's a scrollbar).
  28131. */
  28132. int getVisibleRowWidth() const throw();
  28133. /** Sets the height of each row in the list.
  28134. The default height is 22 pixels.
  28135. @see getRowHeight
  28136. */
  28137. void setRowHeight (const int newHeight);
  28138. /** Returns the height of a row in the list.
  28139. @see setRowHeight
  28140. */
  28141. int getRowHeight() const throw() { return rowHeight; }
  28142. /** Returns the number of rows actually visible.
  28143. This is the number of whole rows which will fit on-screen, so the value might
  28144. be more than the actual number of rows in the list.
  28145. */
  28146. int getNumRowsOnScreen() const throw();
  28147. /** A set of colour IDs to use to change the colour of various aspects of the label.
  28148. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  28149. methods.
  28150. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  28151. */
  28152. enum ColourIds
  28153. {
  28154. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  28155. Make this transparent if you don't want the background to be filled. */
  28156. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  28157. Make this transparent to not have an outline. */
  28158. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  28159. };
  28160. /** Sets the thickness of a border that will be drawn around the box.
  28161. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  28162. @see outlineColourId
  28163. */
  28164. void setOutlineThickness (const int outlineThickness);
  28165. /** Returns the thickness of outline that will be drawn around the listbox.
  28166. @see setOutlineColour
  28167. */
  28168. int getOutlineThickness() const throw() { return outlineThickness; }
  28169. /** Sets a component that the list should use as a header.
  28170. This will position the given component at the top of the list, maintaining the
  28171. height of the component passed-in, but rescaling it horizontally to match the
  28172. width of the items in the listbox.
  28173. The component will be deleted when setHeaderComponent() is called with a
  28174. different component, or when the listbox is deleted.
  28175. */
  28176. void setHeaderComponent (Component* const newHeaderComponent);
  28177. /** Changes the width of the rows in the list.
  28178. This can be used to make the list's row components wider than the list itself - the
  28179. width of the rows will be either the width of the list or this value, whichever is
  28180. greater, and if the rows become wider than the list, a horizontal scrollbar will
  28181. appear.
  28182. The default value for this is 0, which means that the rows will always
  28183. be the same width as the list.
  28184. */
  28185. void setMinimumContentWidth (const int newMinimumWidth);
  28186. /** Returns the space currently available for the row items, taking into account
  28187. borders, scrollbars, etc.
  28188. */
  28189. int getVisibleContentWidth() const throw();
  28190. /** Repaints one of the rows.
  28191. This is a lightweight alternative to calling updateContent, and just causes a
  28192. repaint of the row's area.
  28193. */
  28194. void repaintRow (const int rowNumber) throw();
  28195. /** This fairly obscure method creates an image that just shows the currently
  28196. selected row components.
  28197. It's a handy method for doing drag-and-drop, as it can be passed to the
  28198. DragAndDropContainer for use as the drag image.
  28199. Note that it will make the row components temporarily invisible, so if you're
  28200. using custom components this could affect them if they're sensitive to that
  28201. sort of thing.
  28202. @see Component::createComponentSnapshot
  28203. */
  28204. Image* createSnapshotOfSelectedRows (int& x, int& y);
  28205. /** Returns the viewport that this ListBox uses.
  28206. You may need to use this to change parameters such as whether scrollbars
  28207. are shown, etc.
  28208. */
  28209. Viewport* getViewport() const throw();
  28210. /** @internal */
  28211. bool keyPressed (const KeyPress& key);
  28212. /** @internal */
  28213. bool keyStateChanged (const bool isKeyDown);
  28214. /** @internal */
  28215. void paint (Graphics& g);
  28216. /** @internal */
  28217. void paintOverChildren (Graphics& g);
  28218. /** @internal */
  28219. void resized();
  28220. /** @internal */
  28221. void visibilityChanged();
  28222. /** @internal */
  28223. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  28224. /** @internal */
  28225. void mouseMove (const MouseEvent&);
  28226. /** @internal */
  28227. void mouseExit (const MouseEvent&);
  28228. /** @internal */
  28229. void mouseUp (const MouseEvent&);
  28230. /** @internal */
  28231. void colourChanged();
  28232. /** @internal */
  28233. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  28234. juce_UseDebuggingNewOperator
  28235. private:
  28236. friend class ListViewport;
  28237. friend class TableListBox;
  28238. ListBoxModel* model;
  28239. ListViewport* viewport;
  28240. Component* headerComponent;
  28241. int totalItems, rowHeight, minimumRowWidth;
  28242. int outlineThickness;
  28243. int lastMouseX, lastMouseY, lastRowSelected;
  28244. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  28245. SparseSet <int> selected;
  28246. void selectRowInternal (const int rowNumber,
  28247. bool dontScrollToShowThisRow,
  28248. bool deselectOthersFirst,
  28249. bool isMouseClick);
  28250. ListBox (const ListBox&);
  28251. const ListBox& operator= (const ListBox&);
  28252. };
  28253. #endif // __JUCE_LISTBOX_JUCEHEADER__
  28254. /********* End of inlined file: juce_ListBox.h *********/
  28255. /********* Start of inlined file: juce_TextButton.h *********/
  28256. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  28257. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  28258. /**
  28259. A button that uses the standard lozenge-shaped background with a line of
  28260. text on it.
  28261. @see Button, DrawableButton
  28262. */
  28263. class JUCE_API TextButton : public Button
  28264. {
  28265. public:
  28266. /** Creates a TextButton.
  28267. @param buttonName the text to put in the button (the component's name is also
  28268. initially set to this string, but these can be changed later
  28269. using the setName() and setButtonText() methods)
  28270. @param toolTip an optional string to use as a toolip
  28271. @see Button
  28272. */
  28273. TextButton (const String& buttonName,
  28274. const String& toolTip = String::empty);
  28275. /** Destructor. */
  28276. ~TextButton();
  28277. /** A set of colour IDs to use to change the colour of various aspects of the button.
  28278. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  28279. methods.
  28280. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  28281. */
  28282. enum ColourIds
  28283. {
  28284. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  28285. 'off'). The look-and-feel class might re-interpret this to add
  28286. effects, etc. */
  28287. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  28288. 'on'). The look-and-feel class might re-interpret this to add
  28289. effects, etc. */
  28290. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  28291. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  28292. };
  28293. /** Resizes the button to fit neatly around its current text.
  28294. If newHeight is >= 0, the button's height will be changed to this
  28295. value. If it's less than zero, its height will be unaffected.
  28296. */
  28297. void changeWidthToFitText (const int newHeight = -1);
  28298. /** This can be overridden to use different fonts than the default one.
  28299. Note that you'll need to set the font's size appropriately, too.
  28300. */
  28301. virtual const Font getFont();
  28302. juce_UseDebuggingNewOperator
  28303. protected:
  28304. /** @internal */
  28305. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  28306. /** @internal */
  28307. void colourChanged();
  28308. private:
  28309. TextButton (const TextButton&);
  28310. const TextButton& operator= (const TextButton&);
  28311. };
  28312. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  28313. /********* End of inlined file: juce_TextButton.h *********/
  28314. /**
  28315. A component displaying a list of plugins, with options to scan for them,
  28316. add, remove and sort them.
  28317. */
  28318. class JUCE_API PluginListComponent : public Component,
  28319. public ListBoxModel,
  28320. public ChangeListener,
  28321. public ButtonListener,
  28322. public Timer
  28323. {
  28324. public:
  28325. /**
  28326. Creates the list component.
  28327. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  28328. The properties file, if supplied, is used to store the user's last search paths.
  28329. */
  28330. PluginListComponent (KnownPluginList& listToRepresent,
  28331. const File& deadMansPedalFile,
  28332. PropertiesFile* const propertiesToUse);
  28333. /** Destructor. */
  28334. ~PluginListComponent();
  28335. /** @internal */
  28336. void resized();
  28337. /** @internal */
  28338. bool isInterestedInFileDrag (const StringArray& files);
  28339. /** @internal */
  28340. void filesDropped (const StringArray& files, int, int);
  28341. /** @internal */
  28342. int getNumRows();
  28343. /** @internal */
  28344. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  28345. /** @internal */
  28346. void deleteKeyPressed (int lastRowSelected);
  28347. /** @internal */
  28348. void buttonClicked (Button* b);
  28349. /** @internal */
  28350. void changeListenerCallback (void*);
  28351. /** @internal */
  28352. void timerCallback();
  28353. juce_UseDebuggingNewOperator
  28354. private:
  28355. KnownPluginList& list;
  28356. File deadMansPedalFile;
  28357. ListBox* listBox;
  28358. TextButton* optionsButton;
  28359. PropertiesFile* propertiesToUse;
  28360. int typeToScan;
  28361. void scanFor (AudioPluginFormat* format);
  28362. PluginListComponent (const PluginListComponent&);
  28363. const PluginListComponent& operator= (const PluginListComponent&);
  28364. };
  28365. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  28366. /********* End of inlined file: juce_PluginListComponent.h *********/
  28367. #endif
  28368. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28369. #endif
  28370. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28371. #endif
  28372. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28373. #endif
  28374. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  28375. /********* Start of inlined file: juce_AudioProcessorGraph.h *********/
  28376. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  28377. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  28378. /**
  28379. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  28380. Use one of these objects if you want to wire-up a set of AudioProcessors
  28381. and play back the result.
  28382. Processors can be added to the graph as "nodes" using addNode(), and once
  28383. added, you can connect any of their input or output channels to other
  28384. nodes using addConnection().
  28385. To play back a graph through an audio device, you might want to use an
  28386. AudioProcessorPlayer object.
  28387. */
  28388. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  28389. public AsyncUpdater
  28390. {
  28391. public:
  28392. /** Creates an empty graph.
  28393. */
  28394. AudioProcessorGraph();
  28395. /** Destructor.
  28396. Any processor objects that have been added to the graph will also be deleted.
  28397. */
  28398. ~AudioProcessorGraph();
  28399. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  28400. To create a node, call AudioProcessorGraph::addNode().
  28401. */
  28402. class JUCE_API Node : public ReferenceCountedObject
  28403. {
  28404. public:
  28405. /** Destructor.
  28406. */
  28407. ~Node();
  28408. /** The ID number assigned to this node.
  28409. This is assigned by the graph that owns it, and can't be changed.
  28410. */
  28411. const uint32 id;
  28412. /** The actual processor object that this node represents.
  28413. */
  28414. AudioProcessor* const processor;
  28415. /** A set of user-definable properties that are associated with this node.
  28416. This can be used to attach values to the node for whatever purpose seems
  28417. useful. For example, you might store an x and y position if your application
  28418. is displaying the nodes on-screen.
  28419. */
  28420. PropertySet properties;
  28421. /** A convenient typedef for referring to a pointer to a node object.
  28422. */
  28423. typedef ReferenceCountedObjectPtr <Node> Ptr;
  28424. juce_UseDebuggingNewOperator
  28425. private:
  28426. friend class AudioProcessorGraph;
  28427. bool isPrepared;
  28428. Node (const uint32 id, AudioProcessor* const processor) throw();
  28429. void prepare (const double sampleRate, const int blockSize, AudioProcessorGraph* const graph);
  28430. void unprepare();
  28431. Node (const Node&);
  28432. const Node& operator= (const Node&);
  28433. };
  28434. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  28435. To create a connection, use AudioProcessorGraph::addConnection().
  28436. */
  28437. struct JUCE_API Connection
  28438. {
  28439. public:
  28440. /** The ID number of the node which is the input source for this connection.
  28441. @see AudioProcessorGraph::getNodeForId
  28442. */
  28443. uint32 sourceNodeId;
  28444. /** The index of the output channel of the source node from which this
  28445. connection takes its data.
  28446. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  28447. it is referring to the source node's midi output. Otherwise, it is the zero-based
  28448. index of an audio output channel in the source node.
  28449. */
  28450. int sourceChannelIndex;
  28451. /** The ID number of the node which is the destination for this connection.
  28452. @see AudioProcessorGraph::getNodeForId
  28453. */
  28454. uint32 destNodeId;
  28455. /** The index of the input channel of the destination node to which this
  28456. connection delivers its data.
  28457. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  28458. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  28459. index of an audio input channel in the destination node.
  28460. */
  28461. int destChannelIndex;
  28462. juce_UseDebuggingNewOperator
  28463. private:
  28464. };
  28465. /** Deletes all nodes and connections from this graph.
  28466. Any processor objects in the graph will be deleted.
  28467. */
  28468. void clear();
  28469. /** Returns the number of nodes in the graph. */
  28470. int getNumNodes() const throw() { return nodes.size(); }
  28471. /** Returns a pointer to one of the nodes in the graph.
  28472. This will return 0 if the index is out of range.
  28473. @see getNodeForId
  28474. */
  28475. Node* getNode (const int index) const throw() { return nodes [index]; }
  28476. /** Searches the graph for a node with the given ID number and returns it.
  28477. If no such node was found, this returns 0.
  28478. @see getNode
  28479. */
  28480. Node* getNodeForId (const uint32 nodeId) const throw();
  28481. /** Adds a node to the graph.
  28482. This creates a new node in the graph, for the specified processor. Once you have
  28483. added a processor to the graph, the graph owns it and will delete it later when
  28484. it is no longer needed.
  28485. The optional nodeId parameter lets you specify an ID to use for the node, but
  28486. if the value is already in use, this new node will overwrite the old one.
  28487. If this succeeds, it returns a pointer to the newly-created node.
  28488. */
  28489. Node* addNode (AudioProcessor* const newProcessor,
  28490. uint32 nodeId = 0);
  28491. /** Deletes a node within the graph which has the specified ID.
  28492. This will also delete any connections that are attached to this node.
  28493. */
  28494. bool removeNode (const uint32 nodeId);
  28495. /** Returns the number of connections in the graph. */
  28496. int getNumConnections() const throw() { return connections.size(); }
  28497. /** Returns a pointer to one of the connections in the graph. */
  28498. const Connection* getConnection (const int index) const throw() { return connections [index]; }
  28499. /** Searches for a connection between some specified channels.
  28500. If no such connection is found, this returns 0.
  28501. */
  28502. const Connection* getConnectionBetween (const uint32 sourceNodeId,
  28503. const int sourceChannelIndex,
  28504. const uint32 destNodeId,
  28505. const int destChannelIndex) const throw();
  28506. /** Returns true if there is a connection between any of the channels of
  28507. two specified nodes.
  28508. */
  28509. bool isConnected (const uint32 possibleSourceNodeId,
  28510. const uint32 possibleDestNodeId) const throw();
  28511. /** Returns true if it would be legal to connect the specified points.
  28512. */
  28513. bool canConnect (const uint32 sourceNodeId, const int sourceChannelIndex,
  28514. const uint32 destNodeId, const int destChannelIndex) const throw();
  28515. /** Attempts to connect two specified channels of two nodes.
  28516. If this isn't allowed (e.g. because you're trying to connect a midi channel
  28517. to an audio one or other such nonsense), then it'll return false.
  28518. */
  28519. bool addConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28520. const uint32 destNodeId, const int destChannelIndex);
  28521. /** Deletes the connection with the specified index.
  28522. Returns true if a connection was actually deleted.
  28523. */
  28524. void removeConnection (const int index);
  28525. /** Deletes any connection between two specified points.
  28526. Returns true if a connection was actually deleted.
  28527. */
  28528. bool removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28529. const uint32 destNodeId, const int destChannelIndex);
  28530. /** Removes all connections from the specified node.
  28531. */
  28532. bool disconnectNode (const uint32 nodeId);
  28533. /** Performs a sanity checks of all the connections.
  28534. This might be useful if some of the processors are doing things like changing
  28535. their channel counts, which could render some connections obsolete.
  28536. */
  28537. bool removeIllegalConnections();
  28538. /** A special number that represents the midi channel of a node.
  28539. This is used as a channel index value if you want to refer to the midi input
  28540. or output instead of an audio channel.
  28541. */
  28542. static const int midiChannelIndex;
  28543. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  28544. in order to use the audio that comes into and out of the graph itself.
  28545. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  28546. node in the graph which delivers the audio that is coming into the parent
  28547. graph. This allows you to stream the data to other nodes and process the
  28548. incoming audio.
  28549. Likewise, one of these in "output" mode can be sent data which it will add to
  28550. the sum of data being sent to the graph's output.
  28551. @see AudioProcessorGraph
  28552. */
  28553. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  28554. {
  28555. public:
  28556. /** Specifies the mode in which this processor will operate.
  28557. */
  28558. enum IODeviceType
  28559. {
  28560. audioInputNode, /**< In this mode, the processor has output channels
  28561. representing all the audio input channels that are
  28562. coming into its parent audio graph. */
  28563. audioOutputNode, /**< In this mode, the processor has input channels
  28564. representing all the audio output channels that are
  28565. going out of its parent audio graph. */
  28566. midiInputNode, /**< In this mode, the processor has a midi output which
  28567. delivers the same midi data that is arriving at its
  28568. parent graph. */
  28569. midiOutputNode /**< In this mode, the processor has a midi input and
  28570. any data sent to it will be passed out of the parent
  28571. graph. */
  28572. };
  28573. /** Returns the mode of this processor. */
  28574. IODeviceType getType() const throw() { return type; }
  28575. /** Returns the parent graph to which this processor belongs, or 0 if it
  28576. hasn't yet been added to one. */
  28577. AudioProcessorGraph* getParentGraph() const throw() { return graph; }
  28578. /** True if this is an audio or midi input. */
  28579. bool isInput() const throw();
  28580. /** True if this is an audio or midi output. */
  28581. bool isOutput() const throw();
  28582. AudioGraphIOProcessor (const IODeviceType type);
  28583. ~AudioGraphIOProcessor();
  28584. const String getName() const;
  28585. void fillInPluginDescription (PluginDescription& d) const;
  28586. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  28587. void releaseResources();
  28588. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  28589. const String getInputChannelName (const int channelIndex) const;
  28590. const String getOutputChannelName (const int channelIndex) const;
  28591. bool isInputChannelStereoPair (int index) const;
  28592. bool isOutputChannelStereoPair (int index) const;
  28593. bool acceptsMidi() const;
  28594. bool producesMidi() const;
  28595. AudioProcessorEditor* createEditor();
  28596. int getNumParameters();
  28597. const String getParameterName (int);
  28598. float getParameter (int);
  28599. const String getParameterText (int);
  28600. void setParameter (int, float);
  28601. int getNumPrograms();
  28602. int getCurrentProgram();
  28603. void setCurrentProgram (int);
  28604. const String getProgramName (int);
  28605. void changeProgramName (int, const String&);
  28606. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  28607. void setStateInformation (const void* data, int sizeInBytes);
  28608. /** @internal */
  28609. void setParentGraph (AudioProcessorGraph* const graph) throw();
  28610. juce_UseDebuggingNewOperator
  28611. private:
  28612. const IODeviceType type;
  28613. AudioProcessorGraph* graph;
  28614. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  28615. const AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  28616. };
  28617. // AudioProcessor methods:
  28618. const String getName() const;
  28619. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  28620. void releaseResources();
  28621. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  28622. const String getInputChannelName (const int channelIndex) const;
  28623. const String getOutputChannelName (const int channelIndex) const;
  28624. bool isInputChannelStereoPair (int index) const;
  28625. bool isOutputChannelStereoPair (int index) const;
  28626. bool acceptsMidi() const;
  28627. bool producesMidi() const;
  28628. AudioProcessorEditor* createEditor() { return 0; }
  28629. int getNumParameters() { return 0; }
  28630. const String getParameterName (int) { return String::empty; }
  28631. float getParameter (int) { return 0; }
  28632. const String getParameterText (int) { return String::empty; }
  28633. void setParameter (int, float) { }
  28634. int getNumPrograms() { return 0; }
  28635. int getCurrentProgram() { return 0; }
  28636. void setCurrentProgram (int) { }
  28637. const String getProgramName (int) { return String::empty; }
  28638. void changeProgramName (int, const String&) { }
  28639. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  28640. void setStateInformation (const void* data, int sizeInBytes);
  28641. /** @internal */
  28642. void handleAsyncUpdate();
  28643. juce_UseDebuggingNewOperator
  28644. private:
  28645. ReferenceCountedArray <Node> nodes;
  28646. OwnedArray <Connection> connections;
  28647. int lastNodeId;
  28648. AudioSampleBuffer renderingBuffers;
  28649. OwnedArray <MidiBuffer> midiBuffers;
  28650. CriticalSection renderLock;
  28651. VoidArray renderingOps;
  28652. friend class AudioGraphIOProcessor;
  28653. AudioSampleBuffer* currentAudioInputBuffer;
  28654. AudioSampleBuffer currentAudioOutputBuffer;
  28655. MidiBuffer* currentMidiInputBuffer;
  28656. MidiBuffer currentMidiOutputBuffer;
  28657. void clearRenderingSequence();
  28658. void buildRenderingSequence();
  28659. bool isAnInputTo (const uint32 possibleInputId,
  28660. const uint32 possibleDestinationId,
  28661. const int recursionCheck) const throw();
  28662. AudioProcessorGraph (const AudioProcessorGraph&);
  28663. const AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  28664. };
  28665. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  28666. /********* End of inlined file: juce_AudioProcessorGraph.h *********/
  28667. #endif
  28668. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28669. #endif
  28670. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  28671. /********* Start of inlined file: juce_AudioProcessorPlayer.h *********/
  28672. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  28673. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  28674. /**
  28675. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  28676. To use one of these, just make it the callback used by your AudioIODevice, and
  28677. give it a processor to use by calling setProcessor().
  28678. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  28679. input to send both streams through the processor.
  28680. @see AudioProcessor, AudioProcessorGraph
  28681. */
  28682. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  28683. public MidiInputCallback
  28684. {
  28685. public:
  28686. /**
  28687. */
  28688. AudioProcessorPlayer();
  28689. /** Destructor. */
  28690. virtual ~AudioProcessorPlayer();
  28691. /** Sets the processor that should be played.
  28692. The processor that is passed in will not be deleted or owned by this object.
  28693. To stop anything playing, pass in 0 to this method.
  28694. */
  28695. void setProcessor (AudioProcessor* const processorToPlay);
  28696. /** Returns the current audio processor that is being played.
  28697. */
  28698. AudioProcessor* getCurrentProcessor() const throw() { return processor; }
  28699. /** Returns a midi message collector that you can pass midi messages to if you
  28700. want them to be injected into the midi stream that is being sent to the
  28701. processor.
  28702. */
  28703. MidiMessageCollector& getMidiMessageCollector() throw() { return messageCollector; }
  28704. /** @internal */
  28705. void audioDeviceIOCallback (const float** inputChannelData,
  28706. int totalNumInputChannels,
  28707. float** outputChannelData,
  28708. int totalNumOutputChannels,
  28709. int numSamples);
  28710. /** @internal */
  28711. void audioDeviceAboutToStart (AudioIODevice* device);
  28712. /** @internal */
  28713. void audioDeviceStopped();
  28714. /** @internal */
  28715. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28716. juce_UseDebuggingNewOperator
  28717. private:
  28718. AudioProcessor* processor;
  28719. CriticalSection lock;
  28720. double sampleRate;
  28721. int blockSize;
  28722. bool isPrepared;
  28723. int numInputChans, numOutputChans;
  28724. float* channels [128];
  28725. AudioSampleBuffer tempBuffer;
  28726. MidiBuffer incomingMidi;
  28727. MidiMessageCollector messageCollector;
  28728. AudioProcessorPlayer (const AudioProcessorPlayer&);
  28729. const AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  28730. };
  28731. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  28732. /********* End of inlined file: juce_AudioProcessorPlayer.h *********/
  28733. #endif
  28734. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  28735. /********* Start of inlined file: juce_GenericAudioProcessorEditor.h *********/
  28736. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  28737. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  28738. /********* Start of inlined file: juce_PropertyPanel.h *********/
  28739. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  28740. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  28741. /********* Start of inlined file: juce_PropertyComponent.h *********/
  28742. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  28743. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  28744. class EditableProperty;
  28745. /**
  28746. A base class for a component that goes in a PropertyPanel and displays one of
  28747. an item's properties.
  28748. Subclasses of this are used to display a property in various forms, e.g. a
  28749. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  28750. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  28751. A subclass must implement the refresh() method which will be called to tell the
  28752. component to update itself, and is also responsible for calling this it when the
  28753. item that it refers to is changed.
  28754. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  28755. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  28756. */
  28757. class JUCE_API PropertyComponent : public Component,
  28758. public SettableTooltipClient
  28759. {
  28760. public:
  28761. /** Creates a PropertyComponent.
  28762. @param propertyName the name is stored as this component's name, and is
  28763. used as the name displayed next to this component in
  28764. a property panel
  28765. @param preferredHeight the height that the component should be given - some
  28766. items may need to be larger than a normal row height.
  28767. This value can also be set if a subclass changes the
  28768. preferredHeight member variable.
  28769. */
  28770. PropertyComponent (const String& propertyName,
  28771. const int preferredHeight = 25);
  28772. /** Destructor. */
  28773. ~PropertyComponent();
  28774. /** Returns this item's preferred height.
  28775. This value is specified either in the constructor or by a subclass changing the
  28776. preferredHeight member variable.
  28777. */
  28778. int getPreferredHeight() const throw() { return preferredHeight; }
  28779. /** Updates the property component if the item it refers to has changed.
  28780. A subclass must implement this method, and other objects may call it to
  28781. force it to refresh itself.
  28782. The subclass should be economical in the amount of work is done, so for
  28783. example it should check whether it really needs to do a repaint rather than
  28784. just doing one every time this method is called, as it may be called when
  28785. the value being displayed hasn't actually changed.
  28786. */
  28787. virtual void refresh() = 0;
  28788. /** The default paint method fills the background and draws a label for the
  28789. item's name.
  28790. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  28791. */
  28792. void paint (Graphics& g);
  28793. /** The default resize method positions any child component to the right of this
  28794. one, based on the look and feel's default label size.
  28795. */
  28796. void resized();
  28797. /** By default, this just repaints the component. */
  28798. void enablementChanged();
  28799. juce_UseDebuggingNewOperator
  28800. protected:
  28801. /** Used by the PropertyPanel to determine how high this component needs to be.
  28802. A subclass can update this value in its constructor but shouldn't alter it later
  28803. as changes won't necessarily be picked up.
  28804. */
  28805. int preferredHeight;
  28806. };
  28807. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  28808. /********* End of inlined file: juce_PropertyComponent.h *********/
  28809. /**
  28810. A panel that holds a list of PropertyComponent objects.
  28811. This panel displays a list of PropertyComponents, and allows them to be organised
  28812. into collapsible sections.
  28813. To use, simply create one of these and add your properties to it with addProperties()
  28814. or addSection().
  28815. @see PropertyComponent
  28816. */
  28817. class JUCE_API PropertyPanel : public Component
  28818. {
  28819. public:
  28820. /** Creates an empty property panel. */
  28821. PropertyPanel();
  28822. /** Destructor. */
  28823. ~PropertyPanel();
  28824. /** Deletes all property components from the panel.
  28825. */
  28826. void clear();
  28827. /** Adds a set of properties to the panel.
  28828. The components in the list will be owned by this object and will be automatically
  28829. deleted later on when no longer needed.
  28830. These properties are added without them being inside a named section. If you
  28831. want them to be kept together in a collapsible section, use addSection() instead.
  28832. */
  28833. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  28834. /** Adds a set of properties to the panel.
  28835. These properties are added at the bottom of the list, under a section heading with
  28836. a plus/minus button that allows it to be opened and closed.
  28837. The components in the list will be owned by this object and will be automatically
  28838. deleted later on when no longer needed.
  28839. To add properies without them being in a section, use addProperties().
  28840. */
  28841. void addSection (const String& sectionTitle,
  28842. const Array <PropertyComponent*>& newPropertyComponents,
  28843. const bool shouldSectionInitiallyBeOpen = true);
  28844. /** Calls the refresh() method of all PropertyComponents in the panel */
  28845. void refreshAll() const;
  28846. /** Returns a list of all the names of sections in the panel.
  28847. These are the sections that have been added with addSection().
  28848. */
  28849. const StringArray getSectionNames() const;
  28850. /** Returns true if the section at this index is currently open.
  28851. The index is from 0 up to the number of items returned by getSectionNames().
  28852. */
  28853. bool isSectionOpen (const int sectionIndex) const;
  28854. /** Opens or closes one of the sections.
  28855. The index is from 0 up to the number of items returned by getSectionNames().
  28856. */
  28857. void setSectionOpen (const int sectionIndex, const bool shouldBeOpen);
  28858. /** Enables or disables one of the sections.
  28859. The index is from 0 up to the number of items returned by getSectionNames().
  28860. */
  28861. void setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled);
  28862. /** Saves the current state of open/closed sections so it can be restored later.
  28863. The caller is responsible for deleting the object that is returned.
  28864. To restore this state, use restoreOpennessState().
  28865. @see restoreOpennessState
  28866. */
  28867. XmlElement* getOpennessState() const;
  28868. /** Restores a previously saved arrangement of open/closed sections.
  28869. This will try to restore a snapshot of the panel's state that was created by
  28870. the getOpennessState() method. If any of the sections named in the original
  28871. XML aren't present, they will be ignored.
  28872. @see getOpennessState
  28873. */
  28874. void restoreOpennessState (const XmlElement& newState);
  28875. /** Sets a message to be displayed when there are no properties in the panel.
  28876. The default message is "nothing selected".
  28877. */
  28878. void setMessageWhenEmpty (const String& newMessage);
  28879. /** Returns the message that is displayed when there are no properties.
  28880. @see setMessageWhenEmpty
  28881. */
  28882. const String& getMessageWhenEmpty() const throw();
  28883. /** @internal */
  28884. void paint (Graphics& g);
  28885. /** @internal */
  28886. void resized();
  28887. juce_UseDebuggingNewOperator
  28888. private:
  28889. Viewport* viewport;
  28890. Component* propertyHolderComponent;
  28891. String messageWhenEmpty;
  28892. void updatePropHolderLayout() const;
  28893. void updatePropHolderLayout (const int width) const;
  28894. };
  28895. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  28896. /********* End of inlined file: juce_PropertyPanel.h *********/
  28897. /**
  28898. A type of UI component that displays the parameters of an AudioProcessor as
  28899. a simple list of sliders.
  28900. This can be used for showing an editor for a processor that doesn't supply
  28901. its own custom editor.
  28902. @see AudioProcessor
  28903. */
  28904. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  28905. {
  28906. public:
  28907. GenericAudioProcessorEditor (AudioProcessor* const owner);
  28908. ~GenericAudioProcessorEditor();
  28909. void paint (Graphics& g);
  28910. void resized();
  28911. juce_UseDebuggingNewOperator
  28912. private:
  28913. PropertyPanel* panel;
  28914. };
  28915. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  28916. /********* End of inlined file: juce_GenericAudioProcessorEditor.h *********/
  28917. #endif
  28918. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  28919. /********* Start of inlined file: juce_Sampler.h *********/
  28920. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  28921. #define __JUCE_SAMPLER_JUCEHEADER__
  28922. /********* Start of inlined file: juce_Synthesiser.h *********/
  28923. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  28924. #define __JUCE_SYNTHESISER_JUCEHEADER__
  28925. /**
  28926. Describes one of the sounds that a Synthesiser can play.
  28927. A synthesiser can contain one or more sounds, and a sound can choose which
  28928. midi notes and channels can trigger it.
  28929. The SynthesiserSound is a passive class that just describes what the sound is -
  28930. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  28931. more than one SynthesiserVoice to play the same sound at the same time.
  28932. @see Synthesiser, SynthesiserVoice
  28933. */
  28934. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  28935. {
  28936. protected:
  28937. SynthesiserSound();
  28938. public:
  28939. /** Destructor. */
  28940. virtual ~SynthesiserSound();
  28941. /** Returns true if this sound should be played when a given midi note is pressed.
  28942. The Synthesiser will use this information when deciding which sounds to trigger
  28943. for a given note.
  28944. */
  28945. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  28946. /** Returns true if the sound should be triggered by midi events on a given channel.
  28947. The Synthesiser will use this information when deciding which sounds to trigger
  28948. for a given note.
  28949. */
  28950. virtual bool appliesToChannel (const int midiChannel) = 0;
  28951. /**
  28952. */
  28953. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  28954. juce_UseDebuggingNewOperator
  28955. };
  28956. /**
  28957. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  28958. A voice plays a single sound at a time, and a synthesiser holds an array of
  28959. voices so that it can play polyphonically.
  28960. @see Synthesiser, SynthesiserSound
  28961. */
  28962. class JUCE_API SynthesiserVoice
  28963. {
  28964. public:
  28965. /** Creates a voice. */
  28966. SynthesiserVoice();
  28967. /** Destructor. */
  28968. virtual ~SynthesiserVoice();
  28969. /** Returns the midi note that this voice is currently playing.
  28970. Returns a value less than 0 if no note is playing.
  28971. */
  28972. int getCurrentlyPlayingNote() const throw() { return currentlyPlayingNote; }
  28973. /** Returns the sound that this voice is currently playing.
  28974. Returns 0 if it's not playing.
  28975. */
  28976. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const throw() { return currentlyPlayingSound; }
  28977. /** Must return true if this voice object is capable of playing the given sound.
  28978. If there are different classes of sound, and different classes of voice, a voice can
  28979. choose which ones it wants to take on.
  28980. A typical implementation of this method may just return true if there's only one type
  28981. of voice and sound, or it might check the type of the sound object passed-in and
  28982. see if it's one that it understands.
  28983. */
  28984. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  28985. /** Called to start a new note.
  28986. This will be called during the rendering callback, so must be fast and thread-safe.
  28987. */
  28988. virtual void startNote (const int midiNoteNumber,
  28989. const float velocity,
  28990. SynthesiserSound* sound,
  28991. const int currentPitchWheelPosition) = 0;
  28992. /** Called to stop a note.
  28993. This will be called during the rendering callback, so must be fast and thread-safe.
  28994. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  28995. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  28996. and allow the synth to reassign it another sound.
  28997. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  28998. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  28999. finishes playing (during the rendering callback), it must make sure that it calls
  29000. clearCurrentNote().
  29001. */
  29002. virtual void stopNote (const bool allowTailOff) = 0;
  29003. /** Called to let the voice know that the pitch wheel has been moved.
  29004. This will be called during the rendering callback, so must be fast and thread-safe.
  29005. */
  29006. virtual void pitchWheelMoved (const int newValue) = 0;
  29007. /** Called to let the voice know that a midi controller has been moved.
  29008. This will be called during the rendering callback, so must be fast and thread-safe.
  29009. */
  29010. virtual void controllerMoved (const int controllerNumber,
  29011. const int newValue) = 0;
  29012. /** Renders the next block of data for this voice.
  29013. The output audio data must be added to the current contents of the buffer provided.
  29014. Only the region of the buffer between startSample and (startSample + numSamples)
  29015. should be altered by this method.
  29016. If the voice is currently silent, it should just return without doing anything.
  29017. If the sound that the voice is playing finishes during the course of this rendered
  29018. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  29019. The size of the blocks that are rendered can change each time it is called, and may
  29020. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  29021. the voice's methods will be called to tell it about note and controller events.
  29022. */
  29023. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  29024. int startSample,
  29025. int numSamples) = 0;
  29026. /** Returns true if the voice is currently playing a sound which is mapped to the given
  29027. midi channel.
  29028. If it's not currently playing, this will return false.
  29029. */
  29030. bool isPlayingChannel (const int midiChannel) const;
  29031. /** Changes the voice's reference sample rate.
  29032. The rate is set so that subclasses know the output rate and can set their pitch
  29033. accordingly.
  29034. This method is called by the synth, and subclasses can access the current rate with
  29035. the currentSampleRate member.
  29036. */
  29037. void setCurrentPlaybackSampleRate (const double newRate);
  29038. juce_UseDebuggingNewOperator
  29039. protected:
  29040. /** Returns the current target sample rate at which rendering is being done.
  29041. This is available for subclasses so they can pitch things correctly.
  29042. */
  29043. double getSampleRate() const throw() { return currentSampleRate; }
  29044. /** Resets the state of this voice after a sound has finished playing.
  29045. The subclass must call this when it finishes playing a note and becomes available
  29046. to play new ones.
  29047. It must either call it in the stopNote() method, or if the voice is tailing off,
  29048. then it should call it later during the renderNextBlock method, as soon as it
  29049. finishes its tail-off.
  29050. It can also be called at any time during the render callback if the sound happens
  29051. to have finished, e.g. if it's playing a sample and the sample finishes.
  29052. */
  29053. void clearCurrentNote();
  29054. private:
  29055. friend class Synthesiser;
  29056. double currentSampleRate;
  29057. int currentlyPlayingNote;
  29058. uint32 noteOnTime;
  29059. SynthesiserSound::Ptr currentlyPlayingSound;
  29060. };
  29061. /**
  29062. Base class for a musical device that can play sounds.
  29063. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  29064. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  29065. which can play back one of these sounds.
  29066. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  29067. set of sounds, and a set of voices it can use to play them. If you only give it
  29068. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  29069. have available.
  29070. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  29071. events that go in will be scanned for note on/off messages, and these are used to
  29072. start and stop the voices playing the appropriate sounds.
  29073. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  29074. noteOff() and other controller methods.
  29075. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  29076. what the target playback rate is. This value is passed on to the voices so that
  29077. they can pitch their output correctly.
  29078. */
  29079. class JUCE_API Synthesiser
  29080. {
  29081. public:
  29082. /** Creates a new synthesiser.
  29083. You'll need to add some sounds and voices before it'll make any sound..
  29084. */
  29085. Synthesiser();
  29086. /** Destructor. */
  29087. virtual ~Synthesiser();
  29088. /** Deletes all voices. */
  29089. void clearVoices();
  29090. /** Returns the number of voices that have been added. */
  29091. int getNumVoices() const throw() { return voices.size(); }
  29092. /** Returns one of the voices that have been added. */
  29093. SynthesiserVoice* getVoice (const int index) const throw();
  29094. /** Adds a new voice to the synth.
  29095. All the voices should be the same class of object and are treated equally.
  29096. The object passed in will be managed by the synthesiser, which will delete
  29097. it later on when no longer needed. The caller should not retain a pointer to the
  29098. voice.
  29099. */
  29100. void addVoice (SynthesiserVoice* const newVoice);
  29101. /** Deletes one of the voices. */
  29102. void removeVoice (const int index);
  29103. /** Deletes all sounds. */
  29104. void clearSounds();
  29105. /** Returns the number of sounds that have been added to the synth. */
  29106. int getNumSounds() const throw() { return sounds.size(); }
  29107. /** Returns one of the sounds. */
  29108. SynthesiserSound* getSound (const int index) const throw() { return sounds [index]; }
  29109. /** Adds a new sound to the synthesiser.
  29110. The object passed in is reference counted, so will be deleted when it is removed
  29111. from the synthesiser, and when no voices are still using it.
  29112. */
  29113. void addSound (const SynthesiserSound::Ptr& newSound);
  29114. /** Removes and deletes one of the sounds. */
  29115. void removeSound (const int index);
  29116. /** If set to true, then the synth will try to take over an existing voice if
  29117. it runs out and needs to play another note.
  29118. The value of this boolean is passed into findFreeVoice(), so the result will
  29119. depend on the implementation of this method.
  29120. */
  29121. void setNoteStealingEnabled (const bool shouldStealNotes);
  29122. /** Returns true if note-stealing is enabled.
  29123. @see setNoteStealingEnabled
  29124. */
  29125. bool isNoteStealingEnabled() const throw() { return shouldStealNotes; }
  29126. /** Triggers a note-on event.
  29127. The default method here will find all the sounds that want to be triggered by
  29128. this note/channel. For each sound, it'll try to find a free voice, and use the
  29129. voice to start playing the sound.
  29130. Subclasses might want to override this if they need a more complex algorithm.
  29131. This method will be called automatically according to the midi data passed into
  29132. renderNextBlock(), but may be called explicitly too.
  29133. */
  29134. virtual void noteOn (const int midiChannel,
  29135. const int midiNoteNumber,
  29136. const float velocity);
  29137. /** Triggers a note-off event.
  29138. This will turn off any voices that are playing a sound for the given note/channel.
  29139. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  29140. (if they can do). If this is false, the notes will all be cut off immediately.
  29141. This method will be called automatically according to the midi data passed into
  29142. renderNextBlock(), but may be called explicitly too.
  29143. */
  29144. virtual void noteOff (const int midiChannel,
  29145. const int midiNoteNumber,
  29146. const bool allowTailOff);
  29147. /** Turns off all notes.
  29148. This will turn off any voices that are playing a sound on the given midi channel.
  29149. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  29150. which channel they're playing.
  29151. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  29152. (if they can do). If this is false, the notes will all be cut off immediately.
  29153. This method will be called automatically according to the midi data passed into
  29154. renderNextBlock(), but may be called explicitly too.
  29155. */
  29156. virtual void allNotesOff (const int midiChannel,
  29157. const bool allowTailOff);
  29158. /** Sends a pitch-wheel message.
  29159. This will send a pitch-wheel message to any voices that are playing sounds on
  29160. the given midi channel.
  29161. This method will be called automatically according to the midi data passed into
  29162. renderNextBlock(), but may be called explicitly too.
  29163. @param midiChannel the midi channel for the event
  29164. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  29165. */
  29166. virtual void handlePitchWheel (const int midiChannel,
  29167. const int wheelValue);
  29168. /** Sends a midi controller message.
  29169. This will send a midi controller message to any voices that are playing sounds on
  29170. the given midi channel.
  29171. This method will be called automatically according to the midi data passed into
  29172. renderNextBlock(), but may be called explicitly too.
  29173. @param midiChannel the midi channel for the event
  29174. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  29175. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  29176. */
  29177. virtual void handleController (const int midiChannel,
  29178. const int controllerNumber,
  29179. const int controllerValue);
  29180. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  29181. render.
  29182. This value is propagated to the voices so that they can use it to render the correct
  29183. pitches.
  29184. */
  29185. void setCurrentPlaybackSampleRate (const double sampleRate);
  29186. /** Creates the next block of audio output.
  29187. This will process the next numSamples of data from all the voices, and add that output
  29188. to the audio block supplied, starting from the offset specified. Note that the
  29189. data will be added to the current contents of the buffer, so you should clear it
  29190. before calling this method if necessary.
  29191. The midi events in the inputMidi buffer are parsed for note and controller events,
  29192. and these are used to trigger the voices. Note that the startSample offset applies
  29193. both to the audio output buffer and the midi input buffer, so any midi events
  29194. with timestamps outside the specified region will be ignored.
  29195. */
  29196. void renderNextBlock (AudioSampleBuffer& outputAudio,
  29197. const MidiBuffer& inputMidi,
  29198. int startSample,
  29199. int numSamples);
  29200. juce_UseDebuggingNewOperator
  29201. protected:
  29202. /** This is used to control access to the rendering callback and the note trigger methods. */
  29203. CriticalSection lock;
  29204. OwnedArray <SynthesiserVoice> voices;
  29205. ReferenceCountedArray <SynthesiserSound> sounds;
  29206. /** The last pitch-wheel values for each midi channel. */
  29207. int lastPitchWheelValues [16];
  29208. /** Searches through the voices to find one that's not currently playing, and which
  29209. can play the given sound.
  29210. Returns 0 if all voices are busy and stealing isn't enabled.
  29211. This can be overridden to implement custom voice-stealing algorithms.
  29212. */
  29213. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  29214. const bool stealIfNoneAvailable) const;
  29215. /** Starts a specified voice playing a particular sound.
  29216. You'll probably never need to call this, it's used internally by noteOn(), but
  29217. may be needed by subclasses for custom behaviours.
  29218. */
  29219. void startVoice (SynthesiserVoice* const voice,
  29220. SynthesiserSound* const sound,
  29221. const int midiChannel,
  29222. const int midiNoteNumber,
  29223. const float velocity);
  29224. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  29225. int findFreeVoice (const bool) const { return 0; }
  29226. private:
  29227. double sampleRate;
  29228. uint32 lastNoteOnCounter;
  29229. bool shouldStealNotes;
  29230. Synthesiser (const Synthesiser&);
  29231. const Synthesiser& operator= (const Synthesiser&);
  29232. };
  29233. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  29234. /********* End of inlined file: juce_Synthesiser.h *********/
  29235. /**
  29236. A subclass of SynthesiserSound that represents a sampled audio clip.
  29237. This is a pretty basic sampler, and just attempts to load the whole audio stream
  29238. into memory.
  29239. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  29240. give it some SampledSound objects to play.
  29241. @see SamplerVoice, Synthesiser, SynthesiserSound
  29242. */
  29243. class JUCE_API SamplerSound : public SynthesiserSound
  29244. {
  29245. public:
  29246. /** Creates a sampled sound from an audio reader.
  29247. This will attempt to load the audio from the source into memory and store
  29248. it in this object.
  29249. @param name a name for the sample
  29250. @param source the audio to load. This object can be safely deleted by the
  29251. caller after this constructor returns
  29252. @param midiNotes the set of midi keys that this sound should be played on. This
  29253. is used by the SynthesiserSound::appliesToNote() method
  29254. @param midiNoteForNormalPitch the midi note at which the sample should be played
  29255. with its natural rate. All other notes will be pitched
  29256. up or down relative to this one
  29257. @param attackTimeSecs the attack (fade-in) time, in seconds
  29258. @param releaseTimeSecs the decay (fade-out) time, in seconds
  29259. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  29260. source, in seconds
  29261. */
  29262. SamplerSound (const String& name,
  29263. AudioFormatReader& source,
  29264. const BitArray& midiNotes,
  29265. const int midiNoteForNormalPitch,
  29266. const double attackTimeSecs,
  29267. const double releaseTimeSecs,
  29268. const double maxSampleLengthSeconds);
  29269. /** Destructor. */
  29270. ~SamplerSound();
  29271. /** Returns the sample's name */
  29272. const String& getName() const throw() { return name; }
  29273. /** Returns the audio sample data.
  29274. This could be 0 if there was a problem loading it.
  29275. */
  29276. AudioSampleBuffer* getAudioData() const throw() { return data; }
  29277. bool appliesToNote (const int midiNoteNumber);
  29278. bool appliesToChannel (const int midiChannel);
  29279. juce_UseDebuggingNewOperator
  29280. private:
  29281. friend class SamplerVoice;
  29282. String name;
  29283. ScopedPointer <AudioSampleBuffer> data;
  29284. double sourceSampleRate;
  29285. BitArray midiNotes;
  29286. int length, attackSamples, releaseSamples;
  29287. int midiRootNote;
  29288. };
  29289. /**
  29290. A subclass of SynthesiserVoice that can play a SamplerSound.
  29291. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  29292. give it some SampledSound objects to play.
  29293. @see SamplerSound, Synthesiser, SynthesiserVoice
  29294. */
  29295. class JUCE_API SamplerVoice : public SynthesiserVoice
  29296. {
  29297. public:
  29298. /** Creates a SamplerVoice.
  29299. */
  29300. SamplerVoice();
  29301. /** Destructor. */
  29302. ~SamplerVoice();
  29303. bool canPlaySound (SynthesiserSound* sound);
  29304. void startNote (const int midiNoteNumber,
  29305. const float velocity,
  29306. SynthesiserSound* sound,
  29307. const int currentPitchWheelPosition);
  29308. void stopNote (const bool allowTailOff);
  29309. void pitchWheelMoved (const int newValue);
  29310. void controllerMoved (const int controllerNumber,
  29311. const int newValue);
  29312. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  29313. juce_UseDebuggingNewOperator
  29314. private:
  29315. double pitchRatio;
  29316. double sourceSamplePosition;
  29317. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  29318. bool isInAttack, isInRelease;
  29319. };
  29320. #endif // __JUCE_SAMPLER_JUCEHEADER__
  29321. /********* End of inlined file: juce_Sampler.h *********/
  29322. #endif
  29323. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  29324. #endif
  29325. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29326. /********* Start of inlined file: juce_ActionBroadcaster.h *********/
  29327. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29328. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29329. /********* Start of inlined file: juce_ActionListenerList.h *********/
  29330. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29331. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29332. /**
  29333. A set of ActionListeners.
  29334. Listeners can be added and removed from the list, and messages can be
  29335. broadcast to all the listeners.
  29336. @see ActionListener, ActionBroadcaster
  29337. */
  29338. class JUCE_API ActionListenerList : public MessageListener
  29339. {
  29340. public:
  29341. /** Creates an empty list. */
  29342. ActionListenerList() throw();
  29343. /** Destructor. */
  29344. ~ActionListenerList() throw();
  29345. /** Adds a listener to the list.
  29346. (Trying to add a listener that's already on the list will have no effect).
  29347. */
  29348. void addActionListener (ActionListener* const listener) throw();
  29349. /** Removes a listener from the list.
  29350. If the listener isn't on the list, this won't have any effect.
  29351. */
  29352. void removeActionListener (ActionListener* const listener) throw();
  29353. /** Removes all listeners from the list. */
  29354. void removeAllActionListeners() throw();
  29355. /** Broadcasts a message to all the registered listeners.
  29356. This sends the message asynchronously.
  29357. If a listener is on the list when this method is called but is removed from
  29358. the list before the message arrives, it won't receive the message. Similarly
  29359. listeners that are added to the list after the message is sent but before it
  29360. arrives won't get the message either.
  29361. */
  29362. void sendActionMessage (const String& message) const;
  29363. /** @internal */
  29364. void handleMessage (const Message&);
  29365. juce_UseDebuggingNewOperator
  29366. private:
  29367. SortedSet <void*> actionListeners_;
  29368. CriticalSection actionListenerLock_;
  29369. ActionListenerList (const ActionListenerList&);
  29370. const ActionListenerList& operator= (const ActionListenerList&);
  29371. };
  29372. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29373. /********* End of inlined file: juce_ActionListenerList.h *********/
  29374. /** Manages a list of ActionListeners, and can send them messages.
  29375. To quickly add methods to your class that can add/remove action
  29376. listeners and broadcast to them, you can derive from this.
  29377. @see ActionListenerList, ActionListener
  29378. */
  29379. class JUCE_API ActionBroadcaster
  29380. {
  29381. public:
  29382. /** Creates an ActionBroadcaster. */
  29383. ActionBroadcaster() throw();
  29384. /** Destructor. */
  29385. virtual ~ActionBroadcaster();
  29386. /** Adds a listener to the list.
  29387. (Trying to add a listener that's already on the list will have no effect).
  29388. */
  29389. void addActionListener (ActionListener* const listener);
  29390. /** Removes a listener from the list.
  29391. If the listener isn't on the list, this won't have any effect.
  29392. */
  29393. void removeActionListener (ActionListener* const listener);
  29394. /** Removes all listeners from the list. */
  29395. void removeAllActionListeners();
  29396. /** Broadcasts a message to all the registered listeners.
  29397. @see ActionListenerList::sendActionMessage
  29398. */
  29399. void sendActionMessage (const String& message) const;
  29400. private:
  29401. ActionListenerList actionListenerList;
  29402. ActionBroadcaster (const ActionBroadcaster&);
  29403. const ActionBroadcaster& operator= (const ActionBroadcaster&);
  29404. };
  29405. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  29406. /********* End of inlined file: juce_ActionBroadcaster.h *********/
  29407. #endif
  29408. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  29409. #endif
  29410. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  29411. #endif
  29412. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  29413. #endif
  29414. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29415. /********* Start of inlined file: juce_CallbackMessage.h *********/
  29416. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29417. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29418. /**
  29419. A message that calls a custom function when it gets delivered.
  29420. You can use this class to fire off actions that you want to be performed later
  29421. on the message thread.
  29422. Unlike other Message objects, these don't get sent to a MessageListener, you
  29423. just call the post() method to send them, and when they arrive, your
  29424. messageCallback() method will automatically be invoked.
  29425. @see MessageListener, MessageManager, ActionListener, ChangeListener
  29426. */
  29427. class JUCE_API CallbackMessage : public Message
  29428. {
  29429. public:
  29430. CallbackMessage() throw();
  29431. /** Destructor. */
  29432. ~CallbackMessage() throw();
  29433. /** Called when the message is delivered.
  29434. You should implement this method and make it do whatever action you want
  29435. to perform.
  29436. Note that like all other messages, this object will be deleted immediately
  29437. after this method has been invoked.
  29438. */
  29439. virtual void messageCallback() = 0;
  29440. /** Instead of sending this message to a MessageListener, just call this method
  29441. to post it to the event queue.
  29442. After you've called this, this object will belong to the MessageManager,
  29443. which will delete it later. So make sure you don't delete the object yourself,
  29444. call post() more than once, or call post() on a stack-based obect!
  29445. */
  29446. void post();
  29447. juce_UseDebuggingNewOperator
  29448. private:
  29449. CallbackMessage (const CallbackMessage&);
  29450. const CallbackMessage& operator= (const CallbackMessage&);
  29451. };
  29452. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  29453. /********* End of inlined file: juce_CallbackMessage.h *********/
  29454. #endif
  29455. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  29456. #endif
  29457. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  29458. #endif
  29459. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  29460. #endif
  29461. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29462. /********* Start of inlined file: juce_InterprocessConnection.h *********/
  29463. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29464. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29465. class InterprocessConnectionServer;
  29466. /**
  29467. Manages a simple two-way messaging connection to another process, using either
  29468. a socket or a named pipe as the transport medium.
  29469. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  29470. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  29471. and incoming messages will result in a callback via the messageReceived()
  29472. method.
  29473. To open a pipe and wait for another client to connect to it, use the createPipe()
  29474. method.
  29475. To act as a socket server and create connections for one or more client, see the
  29476. InterprocessConnectionServer class.
  29477. @see InterprocessConnectionServer, Socket, NamedPipe
  29478. */
  29479. class JUCE_API InterprocessConnection : public Thread,
  29480. private MessageListener
  29481. {
  29482. public:
  29483. /** Creates a connection.
  29484. Connections are created manually, connecting them with the connectToSocket()
  29485. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  29486. when a client wants to connect.
  29487. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  29488. connectionLost() and messageReceived() methods will
  29489. always be made using the message thread; if false,
  29490. these will be called immediately on the connection's
  29491. own thread.
  29492. @param magicMessageHeaderNumber a magic number to use in the header to check the
  29493. validity of the data blocks being sent and received. This
  29494. can be any number, but the sender and receiver must obviously
  29495. use matching values or they won't recognise each other.
  29496. */
  29497. InterprocessConnection (const bool callbacksOnMessageThread = true,
  29498. const uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  29499. /** Destructor. */
  29500. ~InterprocessConnection();
  29501. /** Tries to connect this object to a socket.
  29502. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  29503. object waiting to receive client connections on this port number.
  29504. @param hostName the host computer, either a network address or name
  29505. @param portNumber the socket port number to try to connect to
  29506. @param timeOutMillisecs how long to keep trying before giving up
  29507. @returns true if the connection is established successfully
  29508. @see Socket
  29509. */
  29510. bool connectToSocket (const String& hostName,
  29511. const int portNumber,
  29512. const int timeOutMillisecs);
  29513. /** Tries to connect the object to an existing named pipe.
  29514. For this to work, another process on the same computer must already have opened
  29515. an InterprocessConnection object and used createPipe() to create a pipe for this
  29516. to connect to.
  29517. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  29518. @returns true if it connects successfully.
  29519. @see createPipe, NamedPipe
  29520. */
  29521. bool connectToPipe (const String& pipeName,
  29522. const int pipeReceiveMessageTimeoutMs = -1);
  29523. /** Tries to create a new pipe for other processes to connect to.
  29524. This creates a pipe with the given name, so that other processes can use
  29525. connectToPipe() to connect to the other end.
  29526. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  29527. If another process is already using this pipe, this will fail and return false.
  29528. */
  29529. bool createPipe (const String& pipeName,
  29530. const int pipeReceiveMessageTimeoutMs = -1);
  29531. /** Disconnects and closes any currently-open sockets or pipes. */
  29532. void disconnect();
  29533. /** True if a socket or pipe is currently active. */
  29534. bool isConnected() const;
  29535. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  29536. StreamingSocket* getSocket() const throw() { return socket; }
  29537. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  29538. NamedPipe* getPipe() const throw() { return pipe; }
  29539. /** Returns the name of the machine at the other end of this connection.
  29540. This will return an empty string if the other machine isn't known for
  29541. some reason.
  29542. */
  29543. const String getConnectedHostName() const;
  29544. /** Tries to send a message to the other end of this connection.
  29545. This will fail if it's not connected, or if there's some kind of write error. If
  29546. it succeeds, the connection object at the other end will receive the message by
  29547. a callback to its messageReceived() method.
  29548. @see messageReceived
  29549. */
  29550. bool sendMessage (const MemoryBlock& message);
  29551. /** Called when the connection is first connected.
  29552. If the connection was created with the callbacksOnMessageThread flag set, then
  29553. this will be called on the message thread; otherwise it will be called on a server
  29554. thread.
  29555. */
  29556. virtual void connectionMade() = 0;
  29557. /** Called when the connection is broken.
  29558. If the connection was created with the callbacksOnMessageThread flag set, then
  29559. this will be called on the message thread; otherwise it will be called on a server
  29560. thread.
  29561. */
  29562. virtual void connectionLost() = 0;
  29563. /** Called when a message arrives.
  29564. When the object at the other end of this connection sends us a message with sendMessage(),
  29565. this callback is used to deliver it to us.
  29566. If the connection was created with the callbacksOnMessageThread flag set, then
  29567. this will be called on the message thread; otherwise it will be called on a server
  29568. thread.
  29569. @see sendMessage
  29570. */
  29571. virtual void messageReceived (const MemoryBlock& message) = 0;
  29572. juce_UseDebuggingNewOperator
  29573. private:
  29574. CriticalSection pipeAndSocketLock;
  29575. ScopedPointer <StreamingSocket> socket;
  29576. ScopedPointer <NamedPipe> pipe;
  29577. bool callbackConnectionState;
  29578. const bool useMessageThread;
  29579. const uint32 magicMessageHeader;
  29580. int pipeReceiveMessageTimeout;
  29581. friend class InterprocessConnectionServer;
  29582. void initialiseWithSocket (StreamingSocket* const socket_);
  29583. void initialiseWithPipe (NamedPipe* const pipe_);
  29584. void handleMessage (const Message& message);
  29585. void connectionMadeInt();
  29586. void connectionLostInt();
  29587. void deliverDataInt (const MemoryBlock& data);
  29588. bool readNextMessageInt();
  29589. void run();
  29590. InterprocessConnection (const InterprocessConnection&);
  29591. const InterprocessConnection& operator= (const InterprocessConnection&);
  29592. };
  29593. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  29594. /********* End of inlined file: juce_InterprocessConnection.h *********/
  29595. #endif
  29596. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29597. /********* Start of inlined file: juce_InterprocessConnectionServer.h *********/
  29598. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29599. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29600. /**
  29601. An object that waits for client sockets to connect to a port on this host, and
  29602. creates InterprocessConnection objects for each one.
  29603. To use this, create a class derived from it which implements the createConnectionObject()
  29604. method, so that it creates suitable connection objects for each client that tries
  29605. to connect.
  29606. @see InterprocessConnection
  29607. */
  29608. class JUCE_API InterprocessConnectionServer : private Thread
  29609. {
  29610. public:
  29611. /** Creates an uninitialised server object.
  29612. */
  29613. InterprocessConnectionServer();
  29614. /** Destructor. */
  29615. ~InterprocessConnectionServer();
  29616. /** Starts an internal thread which listens on the given port number.
  29617. While this is running, in another process tries to connect with the
  29618. InterprocessConnection::connectToSocket() method, this object will call
  29619. createConnectionObject() to create a connection to that client.
  29620. Use stop() to stop the thread running.
  29621. @see createConnectionObject, stop
  29622. */
  29623. bool beginWaitingForSocket (const int portNumber);
  29624. /** Terminates the listener thread, if it's active.
  29625. @see beginWaitingForSocket
  29626. */
  29627. void stop();
  29628. protected:
  29629. /** Creates a suitable connection object for a client process that wants to
  29630. connect to this one.
  29631. This will be called by the listener thread when a client process tries
  29632. to connect, and must return a new InterprocessConnection object that will
  29633. then run as this end of the connection.
  29634. @see InterprocessConnection
  29635. */
  29636. virtual InterprocessConnection* createConnectionObject() = 0;
  29637. public:
  29638. juce_UseDebuggingNewOperator
  29639. private:
  29640. ScopedPointer <StreamingSocket> socket;
  29641. void run();
  29642. InterprocessConnectionServer (const InterprocessConnectionServer&);
  29643. const InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  29644. };
  29645. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  29646. /********* End of inlined file: juce_InterprocessConnectionServer.h *********/
  29647. #endif
  29648. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  29649. #endif
  29650. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  29651. #endif
  29652. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29653. /********* Start of inlined file: juce_MessageManager.h *********/
  29654. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29655. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29656. class Component;
  29657. class MessageManagerLock;
  29658. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  29659. */
  29660. typedef void* (MessageCallbackFunction) (void* userData);
  29661. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  29662. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  29663. */
  29664. class JUCE_API MessageManager
  29665. {
  29666. public:
  29667. /** Returns the global instance of the MessageManager. */
  29668. static MessageManager* getInstance() throw();
  29669. /** Runs the event dispatch loop until a stop message is posted.
  29670. This method is only intended to be run by the application's startup routine,
  29671. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  29672. @see stopDispatchLoop
  29673. */
  29674. void runDispatchLoop();
  29675. /** Sends a signal that the dispatch loop should terminate.
  29676. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  29677. will be interrupted and will return.
  29678. @see runDispatchLoop
  29679. */
  29680. void stopDispatchLoop();
  29681. /** Returns true if the stopDispatchLoop() method has been called.
  29682. */
  29683. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  29684. /** Synchronously dispatches messages until a given time has elapsed.
  29685. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  29686. otherwise returns true.
  29687. */
  29688. bool runDispatchLoopUntil (int millisecondsToRunFor);
  29689. /** Calls a function using the message-thread.
  29690. This can be used by any thread to cause this function to be called-back
  29691. by the message thread. If it's the message-thread that's calling this method,
  29692. then the function will just be called; if another thread is calling, a message
  29693. will be posted to the queue, and this method will block until that message
  29694. is delivered, the function is called, and the result is returned.
  29695. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  29696. thread has a critical section locked, which an unrelated message callback then tries to lock
  29697. before the message thread gets round to processing this callback.
  29698. @param callback the function to call - its signature must be @code
  29699. void* myCallbackFunction (void*) @endcode
  29700. @param userData a user-defined pointer that will be passed to the function that gets called
  29701. @returns the value that the callback function returns.
  29702. @see MessageManagerLock
  29703. */
  29704. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  29705. void* userData);
  29706. /** Returns true if the caller-thread is the message thread. */
  29707. bool isThisTheMessageThread() const throw();
  29708. /** Called to tell the manager which thread is the one that's running the dispatch loop.
  29709. (Best to ignore this method unless you really know what you're doing..)
  29710. @see getCurrentMessageThread
  29711. */
  29712. void setCurrentMessageThread (const Thread::ThreadID threadId) throw();
  29713. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  29714. (Best to ignore this method unless you really know what you're doing..)
  29715. @see setCurrentMessageThread
  29716. */
  29717. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  29718. /** Returns true if the caller thread has currenltly got the message manager locked.
  29719. see the MessageManagerLock class for more info about this.
  29720. This will be true if the caller is the message thread, because that automatically
  29721. gains a lock while a message is being dispatched.
  29722. */
  29723. bool currentThreadHasLockedMessageManager() const throw();
  29724. /** Sends a message to all other JUCE applications that are running.
  29725. @param messageText the string that will be passed to the actionListenerCallback()
  29726. method of the broadcast listeners in the other app.
  29727. @see registerBroadcastListener, ActionListener
  29728. */
  29729. static void broadcastMessage (const String& messageText) throw();
  29730. /** Registers a listener to get told about broadcast messages.
  29731. The actionListenerCallback() callback's string parameter
  29732. is the message passed into broadcastMessage().
  29733. @see broadcastMessage
  29734. */
  29735. void registerBroadcastListener (ActionListener* listener) throw();
  29736. /** Deregisters a broadcast listener. */
  29737. void deregisterBroadcastListener (ActionListener* listener) throw();
  29738. /** @internal */
  29739. void deliverMessage (void*);
  29740. /** @internal */
  29741. void deliverBroadcastMessage (const String&);
  29742. /** @internal */
  29743. ~MessageManager() throw();
  29744. juce_UseDebuggingNewOperator
  29745. private:
  29746. MessageManager() throw();
  29747. friend class MessageListener;
  29748. friend class ChangeBroadcaster;
  29749. friend class ActionBroadcaster;
  29750. friend class CallbackMessage;
  29751. static MessageManager* instance;
  29752. SortedSet <const MessageListener*> messageListeners;
  29753. ScopedPointer <ActionListenerList> broadcastListeners;
  29754. friend class JUCEApplication;
  29755. bool quitMessagePosted, quitMessageReceived;
  29756. Thread::ThreadID messageThreadId;
  29757. VoidArray modalComponents;
  29758. static void* exitModalLoopCallback (void*);
  29759. void postMessageToQueue (Message* const message);
  29760. void postCallbackMessage (Message* const message);
  29761. static void doPlatformSpecificInitialisation();
  29762. static void doPlatformSpecificShutdown();
  29763. friend class MessageManagerLock;
  29764. Thread::ThreadID volatile threadWithLock;
  29765. CriticalSection lockingLock;
  29766. MessageManager (const MessageManager&);
  29767. const MessageManager& operator= (const MessageManager&);
  29768. };
  29769. /** Used to make sure that the calling thread has exclusive access to the message loop.
  29770. Because it's not thread-safe to call any of the Component or other UI classes
  29771. from threads other than the message thread, one of these objects can be used to
  29772. lock the message loop and allow this to be done. The message thread will be
  29773. suspended for the lifetime of the MessageManagerLock object, so create one on
  29774. the stack like this: @code
  29775. void MyThread::run()
  29776. {
  29777. someData = 1234;
  29778. const MessageManagerLock mmLock;
  29779. // the event loop will now be locked so it's safe to make a few calls..
  29780. myComponent->setBounds (newBounds);
  29781. myComponent->repaint();
  29782. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  29783. }
  29784. @endcode
  29785. Obviously be careful not to create one of these and leave it lying around, or
  29786. your app will grind to a halt!
  29787. Another caveat is that using this in conjunction with other CriticalSections
  29788. can create lots of interesting ways of producing a deadlock! In particular, if
  29789. your message thread calls stopThread() for a thread that uses these locks,
  29790. you'll get an (occasional) deadlock..
  29791. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  29792. */
  29793. class JUCE_API MessageManagerLock
  29794. {
  29795. public:
  29796. /** Tries to acquire a lock on the message manager.
  29797. The constructor attempts to gain a lock on the message loop, and the lock will be
  29798. kept for the lifetime of this object.
  29799. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  29800. this method will keep checking whether the thread has been given the
  29801. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  29802. without gaining the lock. If you pass a thread, you must check whether the lock was
  29803. successful by calling lockWasGained(). If this is false, your thread is being told to
  29804. die, so you should take evasive action.
  29805. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  29806. careful when doing this, because it's very easy to deadlock if your message thread
  29807. attempts to call stopThread() on a thread just as that thread attempts to get the
  29808. message lock.
  29809. If the calling thread already has the lock, nothing will be done, so it's safe and
  29810. quick to use these locks recursively.
  29811. E.g.
  29812. @code
  29813. void run()
  29814. {
  29815. ...
  29816. while (! threadShouldExit())
  29817. {
  29818. MessageManagerLock mml (Thread::getCurrentThread());
  29819. if (! mml.lockWasGained())
  29820. return; // another thread is trying to kill us!
  29821. ..do some locked stuff here..
  29822. }
  29823. ..and now the MM is now unlocked..
  29824. }
  29825. @endcode
  29826. */
  29827. MessageManagerLock (Thread* const threadToCheckForExitSignal = 0) throw();
  29828. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  29829. instead of a thread.
  29830. See the MessageManagerLock (Thread*) constructor for details on how this works.
  29831. */
  29832. MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw();
  29833. /** Releases the current thread's lock on the message manager.
  29834. Make sure this object is created and deleted by the same thread,
  29835. otherwise there are no guarantees what will happen!
  29836. */
  29837. ~MessageManagerLock() throw();
  29838. /** Returns true if the lock was successfully acquired.
  29839. (See the constructor that takes a Thread for more info).
  29840. */
  29841. bool lockWasGained() const throw() { return locked; }
  29842. private:
  29843. bool locked, needsUnlocking;
  29844. void* sharedEvents;
  29845. void init (Thread* const thread, ThreadPoolJob* const job) throw();
  29846. MessageManagerLock (const MessageManagerLock&);
  29847. const MessageManagerLock& operator= (const MessageManagerLock&);
  29848. };
  29849. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  29850. /********* End of inlined file: juce_MessageManager.h *********/
  29851. #endif
  29852. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  29853. /********* Start of inlined file: juce_MultiTimer.h *********/
  29854. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  29855. #define __JUCE_MULTITIMER_JUCEHEADER__
  29856. /**
  29857. A type of timer class that can run multiple timers with different frequencies,
  29858. all of which share a single callback.
  29859. This class is very similar to the Timer class, but allows you run multiple
  29860. separate timers, where each one has a unique ID number. The methods in this
  29861. class are exactly equivalent to those in Timer, but with the addition of
  29862. this ID number.
  29863. To use it, you need to create a subclass of MultiTimer, implementing the
  29864. timerCallback() method. Then you can start timers with startTimer(), and
  29865. each time the callback is triggered, it passes in the ID of the timer that
  29866. caused it.
  29867. @see Timer
  29868. */
  29869. class JUCE_API MultiTimer
  29870. {
  29871. protected:
  29872. /** Creates a MultiTimer.
  29873. When created, no timers are running, so use startTimer() to start things off.
  29874. */
  29875. MultiTimer() throw();
  29876. /** Creates a copy of another timer.
  29877. Note that this timer will not contain any running timers, even if the one you're
  29878. copying from was running.
  29879. */
  29880. MultiTimer (const MultiTimer& other) throw();
  29881. public:
  29882. /** Destructor. */
  29883. virtual ~MultiTimer();
  29884. /** The user-defined callback routine that actually gets called by each of the
  29885. timers that are running.
  29886. It's perfectly ok to call startTimer() or stopTimer() from within this
  29887. callback to change the subsequent intervals.
  29888. */
  29889. virtual void timerCallback (const int timerId) = 0;
  29890. /** Starts a timer and sets the length of interval required.
  29891. If the timer is already started, this will reset it, so the
  29892. time between calling this method and the next timer callback
  29893. will not be less than the interval length passed in.
  29894. @param timerId a unique Id number that identifies the timer to
  29895. start. This is the id that will be passed back
  29896. to the timerCallback() method when this timer is
  29897. triggered
  29898. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  29899. rounded up to 1)
  29900. */
  29901. void startTimer (const int timerId, const int intervalInMilliseconds) throw();
  29902. /** Stops a timer.
  29903. If a timer has been started with the given ID number, it will be cancelled.
  29904. No more callbacks will be made for the specified timer after this method returns.
  29905. If this is called from a different thread, any callbacks that may
  29906. be currently executing may be allowed to finish before the method
  29907. returns.
  29908. */
  29909. void stopTimer (const int timerId) throw();
  29910. /** Checks whether a timer has been started for a specified ID.
  29911. @returns true if a timer with the given ID is running.
  29912. */
  29913. bool isTimerRunning (const int timerId) const throw();
  29914. /** Returns the interval for a specified timer ID.
  29915. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  29916. is running for the ID number specified.
  29917. */
  29918. int getTimerInterval (const int timerId) const throw();
  29919. private:
  29920. CriticalSection timerListLock;
  29921. VoidArray timers;
  29922. const MultiTimer& operator= (const MultiTimer&);
  29923. };
  29924. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  29925. /********* End of inlined file: juce_MultiTimer.h *********/
  29926. #endif
  29927. #ifndef __JUCE_TIMER_JUCEHEADER__
  29928. #endif
  29929. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  29930. /********* Start of inlined file: juce_ArrowButton.h *********/
  29931. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  29932. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  29933. /********* Start of inlined file: juce_DropShadowEffect.h *********/
  29934. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  29935. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  29936. /**
  29937. An effect filter that adds a drop-shadow behind the image's content.
  29938. (This will only work on images/components that aren't opaque, of course).
  29939. When added to a component, this effect will draw a soft-edged
  29940. shadow based on what gets drawn inside it. The shadow will also
  29941. be applied to the component's children.
  29942. For speed, this doesn't use a proper gaussian blur, but cheats by
  29943. using a simple bilinear filter. If you need a really high-quality
  29944. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  29945. @see Component::setComponentEffect
  29946. */
  29947. class JUCE_API DropShadowEffect : public ImageEffectFilter
  29948. {
  29949. public:
  29950. /** Creates a default drop-shadow effect.
  29951. To customise the shadow's appearance, use the setShadowProperties()
  29952. method.
  29953. */
  29954. DropShadowEffect();
  29955. /** Destructor. */
  29956. ~DropShadowEffect();
  29957. /** Sets up parameters affecting the shadow's appearance.
  29958. @param newRadius the (approximate) radius of the blur used
  29959. @param newOpacity the opacity with which the shadow is rendered
  29960. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  29961. component's contents
  29962. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  29963. component's contents
  29964. */
  29965. void setShadowProperties (const float newRadius,
  29966. const float newOpacity,
  29967. const int newShadowOffsetX,
  29968. const int newShadowOffsetY);
  29969. /** @internal */
  29970. void applyEffect (Image& sourceImage, Graphics& destContext);
  29971. juce_UseDebuggingNewOperator
  29972. private:
  29973. int offsetX, offsetY;
  29974. float radius, opacity;
  29975. };
  29976. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  29977. /********* End of inlined file: juce_DropShadowEffect.h *********/
  29978. /**
  29979. A button with an arrow in it.
  29980. @see Button
  29981. */
  29982. class JUCE_API ArrowButton : public Button
  29983. {
  29984. public:
  29985. /** Creates an ArrowButton.
  29986. @param buttonName the name to give the button
  29987. @param arrowDirection the direction the arrow should point in, where 0.0 is
  29988. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  29989. @param arrowColour the colour to use for the arrow
  29990. */
  29991. ArrowButton (const String& buttonName,
  29992. float arrowDirection,
  29993. const Colour& arrowColour);
  29994. /** Destructor. */
  29995. ~ArrowButton();
  29996. juce_UseDebuggingNewOperator
  29997. protected:
  29998. /** @internal */
  29999. void paintButton (Graphics& g,
  30000. bool isMouseOverButton,
  30001. bool isButtonDown);
  30002. /** @internal */
  30003. void buttonStateChanged();
  30004. private:
  30005. Colour colour;
  30006. DropShadowEffect shadow;
  30007. Path path;
  30008. int offset;
  30009. ArrowButton (const ArrowButton&);
  30010. const ArrowButton& operator= (const ArrowButton&);
  30011. };
  30012. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  30013. /********* End of inlined file: juce_ArrowButton.h *********/
  30014. #endif
  30015. #ifndef __JUCE_BUTTON_JUCEHEADER__
  30016. #endif
  30017. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30018. /********* Start of inlined file: juce_DrawableButton.h *********/
  30019. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30020. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30021. /********* Start of inlined file: juce_Drawable.h *********/
  30022. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  30023. #define __JUCE_DRAWABLE_JUCEHEADER__
  30024. /**
  30025. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  30026. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30027. */
  30028. class JUCE_API Drawable
  30029. {
  30030. protected:
  30031. /** The base class can't be instantiated directly.
  30032. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  30033. */
  30034. Drawable();
  30035. public:
  30036. /** Destructor. */
  30037. virtual ~Drawable();
  30038. /** Creates a deep copy of this Drawable object.
  30039. Use this to create a new copy of this and any sub-objects in the tree.
  30040. */
  30041. virtual Drawable* createCopy() const = 0;
  30042. /** Renders this Drawable object.
  30043. @see drawWithin
  30044. */
  30045. void draw (Graphics& g, const float opacity,
  30046. const AffineTransform& transform = AffineTransform::identity) const;
  30047. /** Renders the Drawable at a given offset within the Graphics context.
  30048. The co-ordinates passed-in are used to translate the object relative to its own
  30049. origin before drawing it - this is basically a quick way of saying:
  30050. @code
  30051. draw (g, AffineTransform::translation (x, y)).
  30052. @endcode
  30053. */
  30054. void drawAt (Graphics& g,
  30055. const float x,
  30056. const float y,
  30057. const float opacity) const;
  30058. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  30059. changing its aspect-ratio.
  30060. The object can placed arbitrarily within the rectangle based on a Justification type,
  30061. and can either be made as big as possible, or just reduced to fit.
  30062. @param g the graphics context to render onto
  30063. @param destX top-left of the target rectangle to fit it into
  30064. @param destY top-left of the target rectangle to fit it into
  30065. @param destWidth size of the target rectangle to fit the image into
  30066. @param destHeight size of the target rectangle to fit the image into
  30067. @param placement defines the alignment and rescaling to use to fit
  30068. this object within the target rectangle.
  30069. @param opacity the opacity to use, in the range 0 to 1.0
  30070. */
  30071. void drawWithin (Graphics& g,
  30072. const int destX,
  30073. const int destY,
  30074. const int destWidth,
  30075. const int destHeight,
  30076. const RectanglePlacement& placement,
  30077. const float opacity) const;
  30078. /** Holds the information needed when telling a drawable to render itself.
  30079. @see Drawable::draw
  30080. */
  30081. class RenderingContext
  30082. {
  30083. public:
  30084. RenderingContext (Graphics& g, const AffineTransform& transform, const float opacity) throw();
  30085. Graphics& g;
  30086. AffineTransform transform;
  30087. float opacity;
  30088. private:
  30089. const RenderingContext& operator= (const RenderingContext&);
  30090. };
  30091. /** Renders this Drawable object.
  30092. @see draw
  30093. */
  30094. virtual void render (const RenderingContext& context) const = 0;
  30095. /** Returns the smallest rectangle that can contain this Drawable object.
  30096. Co-ordinates are relative to the object's own origin.
  30097. */
  30098. virtual void getBounds (float& x, float& y, float& width, float& height) const = 0;
  30099. /** Returns true if the given point is somewhere inside this Drawable.
  30100. Co-ordinates are relative to the object's own origin.
  30101. */
  30102. virtual bool hitTest (float x, float y) const = 0;
  30103. /** Returns the name given to this drawable.
  30104. @see setName
  30105. */
  30106. const String& getName() const throw() { return name; }
  30107. /** Assigns a name to this drawable. */
  30108. void setName (const String& newName) throw() { name = newName; }
  30109. /** Tries to turn some kind of image file into a drawable.
  30110. The data could be an image that the ImageFileFormat class understands, or it
  30111. could be SVG.
  30112. */
  30113. static Drawable* createFromImageData (const void* data, const int numBytes);
  30114. /** Tries to turn a stream containing some kind of image data into a drawable.
  30115. The data could be an image that the ImageFileFormat class understands, or it
  30116. could be SVG.
  30117. */
  30118. static Drawable* createFromImageDataStream (InputStream& dataSource);
  30119. /** Tries to turn a file containing some kind of image data into a drawable.
  30120. The data could be an image that the ImageFileFormat class understands, or it
  30121. could be SVG.
  30122. */
  30123. static Drawable* createFromImageFile (const File& file);
  30124. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  30125. into a Drawable tree.
  30126. The object returned must be deleted by the caller. If something goes wrong
  30127. while parsing, it may return 0.
  30128. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  30129. implementation, but it can return the basic vector objects.
  30130. */
  30131. static Drawable* createFromSVG (const XmlElement& svgDocument);
  30132. /** Tries to create a Drawable from a previously-saved ValueTree.
  30133. The ValueTree must have been created by the createValueTree() method.
  30134. */
  30135. static Drawable* createFromValueTree (const ValueTree& tree) throw();
  30136. /** Creates a ValueTree to represent this Drawable.
  30137. The VarTree that is returned can be turned back into a Drawable with
  30138. createFromValueTree().
  30139. */
  30140. virtual ValueTree createValueTree() const throw() = 0;
  30141. juce_UseDebuggingNewOperator
  30142. private:
  30143. Drawable (const Drawable&);
  30144. const Drawable& operator= (const Drawable&);
  30145. String name;
  30146. };
  30147. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  30148. /********* End of inlined file: juce_Drawable.h *********/
  30149. /**
  30150. A button that displays a Drawable.
  30151. Up to three Drawable objects can be given to this button, to represent the
  30152. 'normal', 'over' and 'down' states.
  30153. @see Button
  30154. */
  30155. class JUCE_API DrawableButton : public Button
  30156. {
  30157. public:
  30158. enum ButtonStyle
  30159. {
  30160. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  30161. ImageRaw, /**< The button will just display the images in their normal size and position.
  30162. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  30163. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  30164. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  30165. };
  30166. /** Creates a DrawableButton.
  30167. After creating one of these, use setImages() to specify the drawables to use.
  30168. @param buttonName the name to give the component
  30169. @param buttonStyle the layout to use
  30170. @see ButtonStyle, setButtonStyle, setImages
  30171. */
  30172. DrawableButton (const String& buttonName,
  30173. const ButtonStyle buttonStyle);
  30174. /** Destructor. */
  30175. ~DrawableButton();
  30176. /** Sets up the images to draw for the various button states.
  30177. The button will keep its own internal copies of these drawables.
  30178. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  30179. will be made of the object passed-in if it is non-zero.
  30180. @param overImage the thing to draw for the button's 'over' state - if this is
  30181. zero, the button's normal image will be used when the mouse is
  30182. over it. An internal copy will be made of the object passed-in
  30183. if it is non-zero.
  30184. @param downImage the thing to draw for the button's 'down' state - if this is
  30185. zero, the 'over' image will be used instead (or the normal image
  30186. as a last resort). An internal copy will be made of the object
  30187. passed-in if it is non-zero.
  30188. @param disabledImage an image to draw when the button is disabled. If this is zero,
  30189. the normal image will be drawn with a reduced opacity instead.
  30190. An internal copy will be made of the object passed-in if it is
  30191. non-zero.
  30192. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  30193. state is 'on'. If this is 0, the normal image is used instead
  30194. @param overImageOn same as the overImage, but this is used when the button's toggle
  30195. state is 'on'. If this is 0, the normalImageOn is drawn instead
  30196. @param downImageOn same as the downImage, but this is used when the button's toggle
  30197. state is 'on'. If this is 0, the overImageOn is drawn instead
  30198. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  30199. state is 'on'. If this is 0, the normal image will be drawn instead
  30200. with a reduced opacity
  30201. */
  30202. void setImages (const Drawable* normalImage,
  30203. const Drawable* overImage = 0,
  30204. const Drawable* downImage = 0,
  30205. const Drawable* disabledImage = 0,
  30206. const Drawable* normalImageOn = 0,
  30207. const Drawable* overImageOn = 0,
  30208. const Drawable* downImageOn = 0,
  30209. const Drawable* disabledImageOn = 0);
  30210. /** Changes the button's style.
  30211. @see ButtonStyle
  30212. */
  30213. void setButtonStyle (const ButtonStyle newStyle);
  30214. /** Changes the button's background colours.
  30215. The toggledOffColour is the colour to use when the button's toggle state
  30216. is off, and toggledOnColour when it's on.
  30217. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  30218. used to fill the background of the component.
  30219. For an ImageOnButtonBackground style, the colour is used to draw the
  30220. button's lozenge shape and exactly how the colour's used will depend
  30221. on the LookAndFeel.
  30222. */
  30223. void setBackgroundColours (const Colour& toggledOffColour,
  30224. const Colour& toggledOnColour);
  30225. /** Returns the current background colour being used.
  30226. @see setBackgroundColour
  30227. */
  30228. const Colour& getBackgroundColour() const throw();
  30229. /** Gives the button an optional amount of space around the edge of the drawable.
  30230. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  30231. ones on a button background. If the button is too small for the given gap, a
  30232. smaller gap will be used.
  30233. By default there's a gap of about 3 pixels.
  30234. */
  30235. void setEdgeIndent (const int numPixelsIndent);
  30236. /** Returns the image that the button is currently displaying. */
  30237. const Drawable* getCurrentImage() const throw();
  30238. const Drawable* getNormalImage() const throw();
  30239. const Drawable* getOverImage() const throw();
  30240. const Drawable* getDownImage() const throw();
  30241. juce_UseDebuggingNewOperator
  30242. protected:
  30243. /** @internal */
  30244. void paintButton (Graphics& g,
  30245. bool isMouseOverButton,
  30246. bool isButtonDown);
  30247. private:
  30248. ButtonStyle style;
  30249. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  30250. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  30251. Colour backgroundOff, backgroundOn;
  30252. int edgeIndent;
  30253. void deleteImages();
  30254. DrawableButton (const DrawableButton&);
  30255. const DrawableButton& operator= (const DrawableButton&);
  30256. };
  30257. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  30258. /********* End of inlined file: juce_DrawableButton.h *********/
  30259. #endif
  30260. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30261. /********* Start of inlined file: juce_HyperlinkButton.h *********/
  30262. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30263. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30264. /**
  30265. A button showing an underlined weblink, that will launch the link
  30266. when it's clicked.
  30267. @see Button
  30268. */
  30269. class JUCE_API HyperlinkButton : public Button
  30270. {
  30271. public:
  30272. /** Creates a HyperlinkButton.
  30273. @param linkText the text that will be displayed in the button - this is
  30274. also set as the Component's name, but the text can be
  30275. changed later with the Button::getButtonText() method
  30276. @param linkURL the URL to launch when the user clicks the button
  30277. */
  30278. HyperlinkButton (const String& linkText,
  30279. const URL& linkURL);
  30280. /** Destructor. */
  30281. ~HyperlinkButton();
  30282. /** Changes the font to use for the text.
  30283. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  30284. to match the size of the component.
  30285. */
  30286. void setFont (const Font& newFont,
  30287. const bool resizeToMatchComponentHeight,
  30288. const Justification& justificationType = Justification::horizontallyCentred);
  30289. /** A set of colour IDs to use to change the colour of various aspects of the link.
  30290. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30291. methods.
  30292. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30293. */
  30294. enum ColourIds
  30295. {
  30296. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  30297. };
  30298. /** Changes the URL that the button will trigger. */
  30299. void setURL (const URL& newURL) throw();
  30300. /** Returns the URL that the button will trigger. */
  30301. const URL& getURL() const throw() { return url; }
  30302. /** Resizes the button horizontally to fit snugly around the text.
  30303. This won't affect the button's height.
  30304. */
  30305. void changeWidthToFitText();
  30306. juce_UseDebuggingNewOperator
  30307. protected:
  30308. /** @internal */
  30309. void clicked();
  30310. /** @internal */
  30311. void colourChanged();
  30312. /** @internal */
  30313. void paintButton (Graphics& g,
  30314. bool isMouseOverButton,
  30315. bool isButtonDown);
  30316. private:
  30317. URL url;
  30318. Font font;
  30319. bool resizeFont;
  30320. Justification justification;
  30321. const Font getFontToUse() const;
  30322. HyperlinkButton (const HyperlinkButton&);
  30323. const HyperlinkButton& operator= (const HyperlinkButton&);
  30324. };
  30325. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  30326. /********* End of inlined file: juce_HyperlinkButton.h *********/
  30327. #endif
  30328. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30329. /********* Start of inlined file: juce_ImageButton.h *********/
  30330. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  30331. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  30332. /**
  30333. As the title suggests, this is a button containing an image.
  30334. The colour and transparency of the image can be set to vary when the
  30335. button state changes.
  30336. @see Button, ShapeButton, TextButton
  30337. */
  30338. class JUCE_API ImageButton : public Button
  30339. {
  30340. public:
  30341. /** Creates an ImageButton.
  30342. Use setImage() to specify the image to use. The colours and opacities that
  30343. are specified here can be changed later using setDrawingOptions().
  30344. @param name the name to give the component
  30345. */
  30346. ImageButton (const String& name);
  30347. /** Destructor. */
  30348. ~ImageButton();
  30349. /** Sets up the images to draw in various states.
  30350. Important! Bear in mind that if you pass the same image in for more than one of
  30351. these parameters, this button will delete it (or release from the ImageCache)
  30352. multiple times!
  30353. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  30354. resized to the same dimensions as the normal image
  30355. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  30356. button when the button's size changes
  30357. @param preserveImageProportions if true then any rescaling of the image to fit
  30358. the button will keep the image's x and y proportions
  30359. correct - i.e. it won't distort its shape, although
  30360. this might create gaps around the edges
  30361. @param normalImage the image to use when the button is in its normal state. The
  30362. image passed in will be deleted (or released if it
  30363. was created by the ImageCache class) when the
  30364. button no longer needs it.
  30365. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  30366. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  30367. normal image - if this colour is transparent, no overlay
  30368. will be drawn. The overlay will be drawn over the top of the
  30369. image, so you can basically add a solid or semi-transparent
  30370. colour to the image to brighten or darken it
  30371. @param overImage the image to use when the mouse is over the button. If
  30372. you want to use the same image as was set in the normalImage
  30373. parameter, this value can be 0. As for normalImage, it
  30374. will be deleted or released by the button when no longer
  30375. needed
  30376. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  30377. is over the button
  30378. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  30379. image when the mouse is over - if this colour is transparent,
  30380. no overlay will be drawn
  30381. @param downImage an image to use when the button is pressed down. If set
  30382. to zero, the 'over' image will be drawn instead (or the
  30383. normal image if there isn't an 'over' image either). This
  30384. image will be deleted or released by the button when no
  30385. longer needed
  30386. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  30387. is pressed
  30388. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  30389. image when the button is pressed down - if this colour is
  30390. transparent, no overlay will be drawn
  30391. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  30392. whenever it's inside the button's bounding rectangle. If
  30393. set to values higher than 0, the mouse will only be
  30394. considered to be over the image when the value of the
  30395. image's alpha channel at that position is greater than
  30396. this level.
  30397. */
  30398. void setImages (const bool resizeButtonNowToFitThisImage,
  30399. const bool rescaleImagesWhenButtonSizeChanges,
  30400. const bool preserveImageProportions,
  30401. Image* const normalImage,
  30402. const float imageOpacityWhenNormal,
  30403. const Colour& overlayColourWhenNormal,
  30404. Image* const overImage,
  30405. const float imageOpacityWhenOver,
  30406. const Colour& overlayColourWhenOver,
  30407. Image* const downImage,
  30408. const float imageOpacityWhenDown,
  30409. const Colour& overlayColourWhenDown,
  30410. const float hitTestAlphaThreshold = 0.0f);
  30411. /** Returns the currently set 'normal' image. */
  30412. Image* getNormalImage() const throw();
  30413. /** Returns the image that's drawn when the mouse is over the button.
  30414. If an 'over' image has been set, this will return it; otherwise it'll
  30415. just return the normal image.
  30416. */
  30417. Image* getOverImage() const throw();
  30418. /** Returns the image that's drawn when the button is held down.
  30419. If a 'down' image has been set, this will return it; otherwise it'll
  30420. return the 'over' image or normal image, depending on what's available.
  30421. */
  30422. Image* getDownImage() const throw();
  30423. juce_UseDebuggingNewOperator
  30424. protected:
  30425. /** @internal */
  30426. bool hitTest (int x, int y);
  30427. /** @internal */
  30428. void paintButton (Graphics& g,
  30429. bool isMouseOverButton,
  30430. bool isButtonDown);
  30431. private:
  30432. bool scaleImageToFit, preserveProportions;
  30433. unsigned char alphaThreshold;
  30434. int imageX, imageY, imageW, imageH;
  30435. Image* normalImage;
  30436. Image* overImage;
  30437. Image* downImage;
  30438. float normalOpacity, overOpacity, downOpacity;
  30439. Colour normalOverlay, overOverlay, downOverlay;
  30440. Image* getCurrentImage() const;
  30441. void deleteImages();
  30442. ImageButton (const ImageButton&);
  30443. const ImageButton& operator= (const ImageButton&);
  30444. };
  30445. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  30446. /********* End of inlined file: juce_ImageButton.h *********/
  30447. #endif
  30448. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30449. /********* Start of inlined file: juce_ShapeButton.h *********/
  30450. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  30451. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  30452. /**
  30453. A button that contains a filled shape.
  30454. @see Button, ImageButton, TextButton, ArrowButton
  30455. */
  30456. class JUCE_API ShapeButton : public Button
  30457. {
  30458. public:
  30459. /** Creates a ShapeButton.
  30460. @param name a name to give the component - see Component::setName()
  30461. @param normalColour the colour to fill the shape with when the mouse isn't over
  30462. @param overColour the colour to use when the mouse is over the shape
  30463. @param downColour the colour to use when the button is in the pressed-down state
  30464. */
  30465. ShapeButton (const String& name,
  30466. const Colour& normalColour,
  30467. const Colour& overColour,
  30468. const Colour& downColour);
  30469. /** Destructor. */
  30470. ~ShapeButton();
  30471. /** Sets the shape to use.
  30472. @param newShape the shape to use
  30473. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  30474. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  30475. the button is resized
  30476. @param hasDropShadow if true, the button will be given a drop-shadow effect
  30477. */
  30478. void setShape (const Path& newShape,
  30479. const bool resizeNowToFitThisShape,
  30480. const bool maintainShapeProportions,
  30481. const bool hasDropShadow);
  30482. /** Set the colours to use for drawing the shape.
  30483. @param normalColour the colour to fill the shape with when the mouse isn't over
  30484. @param overColour the colour to use when the mouse is over the shape
  30485. @param downColour the colour to use when the button is in the pressed-down state
  30486. */
  30487. void setColours (const Colour& normalColour,
  30488. const Colour& overColour,
  30489. const Colour& downColour);
  30490. /** Sets up an outline to draw around the shape.
  30491. @param outlineColour the colour to use
  30492. @param outlineStrokeWidth the thickness of line to draw
  30493. */
  30494. void setOutline (const Colour& outlineColour,
  30495. const float outlineStrokeWidth);
  30496. juce_UseDebuggingNewOperator
  30497. protected:
  30498. /** @internal */
  30499. void paintButton (Graphics& g,
  30500. bool isMouseOverButton,
  30501. bool isButtonDown);
  30502. private:
  30503. Colour normalColour, overColour, downColour, outlineColour;
  30504. DropShadowEffect shadow;
  30505. Path shape;
  30506. bool maintainShapeProportions;
  30507. float outlineWidth;
  30508. ShapeButton (const ShapeButton&);
  30509. const ShapeButton& operator= (const ShapeButton&);
  30510. };
  30511. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  30512. /********* End of inlined file: juce_ShapeButton.h *********/
  30513. #endif
  30514. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30515. #endif
  30516. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30517. /********* Start of inlined file: juce_ToggleButton.h *********/
  30518. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30519. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30520. /**
  30521. A button that can be toggled on/off.
  30522. All buttons can be toggle buttons, but this lets you create one of the
  30523. standard ones which has a tick-box and a text label next to it.
  30524. @see Button, DrawableButton, TextButton
  30525. */
  30526. class JUCE_API ToggleButton : public Button
  30527. {
  30528. public:
  30529. /** Creates a ToggleButton.
  30530. @param buttonText the text to put in the button (the component's name is also
  30531. initially set to this string, but these can be changed later
  30532. using the setName() and setButtonText() methods)
  30533. */
  30534. ToggleButton (const String& buttonText);
  30535. /** Destructor. */
  30536. ~ToggleButton();
  30537. /** Resizes the button to fit neatly around its current text.
  30538. The button's height won't be affected, only its width.
  30539. */
  30540. void changeWidthToFitText();
  30541. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30542. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30543. methods.
  30544. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30545. */
  30546. enum ColourIds
  30547. {
  30548. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  30549. };
  30550. juce_UseDebuggingNewOperator
  30551. protected:
  30552. /** @internal */
  30553. void paintButton (Graphics& g,
  30554. bool isMouseOverButton,
  30555. bool isButtonDown);
  30556. /** @internal */
  30557. void colourChanged();
  30558. private:
  30559. ToggleButton (const ToggleButton&);
  30560. const ToggleButton& operator= (const ToggleButton&);
  30561. };
  30562. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  30563. /********* End of inlined file: juce_ToggleButton.h *********/
  30564. #endif
  30565. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30566. /********* Start of inlined file: juce_ToolbarButton.h *********/
  30567. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30568. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  30569. /********* Start of inlined file: juce_ToolbarItemComponent.h *********/
  30570. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30571. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  30572. /********* Start of inlined file: juce_Toolbar.h *********/
  30573. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  30574. #define __JUCE_TOOLBAR_JUCEHEADER__
  30575. /********* Start of inlined file: juce_DragAndDropContainer.h *********/
  30576. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30577. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30578. /********* Start of inlined file: juce_DragAndDropTarget.h *********/
  30579. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30580. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30581. /**
  30582. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  30583. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  30584. derive your component from this class, and make sure that it is somewhere inside a
  30585. DragAndDropContainer component.
  30586. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30587. the operating system onto your component, you don't need any of these classes: instead
  30588. see the FileDragAndDropTarget class.
  30589. @see DragAndDropContainer, FileDragAndDropTarget
  30590. */
  30591. class JUCE_API DragAndDropTarget
  30592. {
  30593. public:
  30594. /** Destructor. */
  30595. virtual ~DragAndDropTarget() {}
  30596. /** Callback to check whether this target is interested in the type of object being
  30597. dragged.
  30598. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30599. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30600. @returns true if this component wants to receive the other callbacks regarging this
  30601. type of object; if it returns false, no other callbacks will be made.
  30602. */
  30603. virtual bool isInterestedInDragSource (const String& sourceDescription,
  30604. Component* sourceComponent) = 0;
  30605. /** Callback to indicate that something is being dragged over this component.
  30606. This gets called when the user moves the mouse into this component while dragging
  30607. something.
  30608. Use this callback as a trigger to make your component repaint itself to give the
  30609. user feedback about whether the item can be dropped here or not.
  30610. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30611. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30612. @param x the mouse x position, relative to this component
  30613. @param y the mouse y position, relative to this component
  30614. @see itemDragExit
  30615. */
  30616. virtual void itemDragEnter (const String& sourceDescription,
  30617. Component* sourceComponent,
  30618. int x,
  30619. int y);
  30620. /** Callback to indicate that the user is dragging something over this component.
  30621. This gets called when the user moves the mouse over this component while dragging
  30622. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  30623. this lets you know what happens in-between.
  30624. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30625. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30626. @param x the mouse x position, relative to this component
  30627. @param y the mouse y position, relative to this component
  30628. */
  30629. virtual void itemDragMove (const String& sourceDescription,
  30630. Component* sourceComponent,
  30631. int x,
  30632. int y);
  30633. /** Callback to indicate that something has been dragged off the edge of this component.
  30634. This gets called when the user moves the mouse out of this component while dragging
  30635. something.
  30636. If you've used itemDragEnter() to repaint your component and give feedback, use this
  30637. as a signal to repaint it in its normal state.
  30638. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30639. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30640. @see itemDragEnter
  30641. */
  30642. virtual void itemDragExit (const String& sourceDescription,
  30643. Component* sourceComponent);
  30644. /** Callback to indicate that the user has dropped something onto this component.
  30645. When the user drops an item this get called, and you can use the description to
  30646. work out whether your object wants to deal with it or not.
  30647. Note that after this is called, the itemDragExit method may not be called, so you should
  30648. clean up in here if there's anything you need to do when the drag finishes.
  30649. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  30650. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  30651. @param x the mouse x position, relative to this component
  30652. @param y the mouse y position, relative to this component
  30653. */
  30654. virtual void itemDropped (const String& sourceDescription,
  30655. Component* sourceComponent,
  30656. int x,
  30657. int y) = 0;
  30658. /** Overriding this allows the target to tell the drag container whether to
  30659. draw the drag image while the cursor is over it.
  30660. By default it returns true, but if you return false, then the normal drag
  30661. image will not be shown when the cursor is over this target.
  30662. */
  30663. virtual bool shouldDrawDragImageWhenOver();
  30664. };
  30665. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  30666. /********* End of inlined file: juce_DragAndDropTarget.h *********/
  30667. /**
  30668. Enables drag-and-drop behaviour for a component and all its sub-components.
  30669. For a component to be able to make or receive drag-and-drop events, one of its parent
  30670. components must derive from this class. It's probably best for the top-level
  30671. component to implement it.
  30672. Then to start a drag operation, any sub-component can just call the startDragging()
  30673. method, and this object will take over, tracking the mouse and sending appropriate
  30674. callbacks to any child components derived from DragAndDropTarget which the mouse
  30675. moves over.
  30676. Note: If all that you need to do is to respond to files being drag-and-dropped from
  30677. the operating system onto your component, you don't need any of these classes: you can do this
  30678. simply by overriding Component::filesDropped().
  30679. @see DragAndDropTarget
  30680. */
  30681. class JUCE_API DragAndDropContainer
  30682. {
  30683. public:
  30684. /** Creates a DragAndDropContainer.
  30685. The object that derives from this class must also be a Component.
  30686. */
  30687. DragAndDropContainer();
  30688. /** Destructor. */
  30689. virtual ~DragAndDropContainer();
  30690. /** Begins a drag-and-drop operation.
  30691. This starts a drag-and-drop operation - call it when the user drags the
  30692. mouse in your drag-source component, and this object will track mouse
  30693. movements until the user lets go of the mouse button, and will send
  30694. appropriate messages to DragAndDropTarget objects that the mouse moves
  30695. over.
  30696. findParentDragContainerFor() is a handy method to call to find the
  30697. drag container to use for a component.
  30698. @param sourceDescription a string to use as the description of the thing being
  30699. dragged - this will be passed to the objects that might be
  30700. dropped-onto so they can decide if they want to handle it or
  30701. not
  30702. @param sourceComponent the component that is being dragged
  30703. @param dragImage the image to drag around underneath the mouse. If this is
  30704. zero, a snapshot of the sourceComponent will be used instead. An
  30705. image passed-in will be deleted by this object when no longer
  30706. needed.
  30707. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  30708. window, and can be dragged to DragAndDropTargets that are the
  30709. children of components other than this one.
  30710. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  30711. at which the image should be drawn from the mouse. If it isn't
  30712. specified, then the image will be centred around the mouse. If
  30713. an image hasn't been passed-in, this will be ignored.
  30714. */
  30715. void startDragging (const String& sourceDescription,
  30716. Component* sourceComponent,
  30717. Image* dragImage = 0,
  30718. const bool allowDraggingToOtherJuceWindows = false,
  30719. const Point* imageOffsetFromMouse = 0);
  30720. /** Returns true if something is currently being dragged. */
  30721. bool isDragAndDropActive() const;
  30722. /** Returns the description of the thing that's currently being dragged.
  30723. If nothing's being dragged, this will return an empty string, otherwise it's the
  30724. string that was passed into startDragging().
  30725. @see startDragging
  30726. */
  30727. const String getCurrentDragDescription() const;
  30728. /** Utility to find the DragAndDropContainer for a given Component.
  30729. This will search up this component's parent hierarchy looking for the first
  30730. parent component which is a DragAndDropContainer.
  30731. It's useful when a component wants to call startDragging but doesn't know
  30732. the DragAndDropContainer it should to use.
  30733. Obviously this may return 0 if it doesn't find a suitable component.
  30734. */
  30735. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  30736. /** This performs a synchronous drag-and-drop of a set of files to some external
  30737. application.
  30738. You can call this function in response to a mouseDrag callback, and it will
  30739. block, running its own internal message loop and tracking the mouse, while it
  30740. uses a native operating system drag-and-drop operation to move or copy some
  30741. files to another application.
  30742. @param files a list of filenames to drag
  30743. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  30744. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  30745. @returns true if the files were successfully dropped somewhere, or false if it
  30746. was interrupted
  30747. @see performExternalDragDropOfText
  30748. */
  30749. static bool performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles);
  30750. /** This performs a synchronous drag-and-drop of a block of text to some external
  30751. application.
  30752. You can call this function in response to a mouseDrag callback, and it will
  30753. block, running its own internal message loop and tracking the mouse, while it
  30754. uses a native operating system drag-and-drop operation to move or copy some
  30755. text to another application.
  30756. @param text the text to copy
  30757. @returns true if the text was successfully dropped somewhere, or false if it
  30758. was interrupted
  30759. @see performExternalDragDropOfFiles
  30760. */
  30761. static bool performExternalDragDropOfText (const String& text);
  30762. juce_UseDebuggingNewOperator
  30763. protected:
  30764. /** Override this if you want to be able to perform an external drag a set of files
  30765. when the user drags outside of this container component.
  30766. This method will be called when a drag operation moves outside the Juce-based window,
  30767. and if you want it to then perform a file drag-and-drop, add the filenames you want
  30768. to the array passed in, and return true.
  30769. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  30770. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  30771. @param files on return, the filenames you want to drag
  30772. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  30773. it must make a copy of them (see the performExternalDragDropOfFiles()
  30774. method)
  30775. @see performExternalDragDropOfFiles
  30776. */
  30777. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  30778. Component* dragSourceComponent,
  30779. StringArray& files,
  30780. bool& canMoveFiles);
  30781. private:
  30782. friend class DragImageComponent;
  30783. ScopedPointer <Component> dragImageComponent;
  30784. String currentDragDesc;
  30785. };
  30786. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  30787. /********* End of inlined file: juce_DragAndDropContainer.h *********/
  30788. /********* Start of inlined file: juce_ComponentAnimator.h *********/
  30789. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  30790. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  30791. /**
  30792. Animates a set of components, moving it to a new position.
  30793. To use this, create a ComponentAnimator, and use its animateComponent() method
  30794. to tell it to move components to destination positions. Any number of
  30795. components can be animated by one ComponentAnimator object (if you've got a
  30796. lot of components to move, it's much more efficient to share a single animator
  30797. than to have many animators running at once).
  30798. You'll need to make sure the animator object isn't deleted before it finishes
  30799. moving the components.
  30800. The class is a ChangeBroadcaster and sends a notification when any components
  30801. start or finish being animated.
  30802. */
  30803. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  30804. private Timer
  30805. {
  30806. public:
  30807. /** Creates a ComponentAnimator. */
  30808. ComponentAnimator();
  30809. /** Destructor. */
  30810. ~ComponentAnimator();
  30811. /** Starts a component moving from its current position to a specified position.
  30812. If the component is already in the middle of an animation, that will be abandoned,
  30813. and a new animation will begin, moving the component from its current location.
  30814. The start and end speed parameters let you apply some acceleration to the component's
  30815. movement.
  30816. @param component the component to move
  30817. @param finalPosition the destination position and size to move it to
  30818. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  30819. to arrive at its destination
  30820. @param startSpeed a value to indicate the relative start speed of the
  30821. animation. If this is 0, the component will start
  30822. by accelerating from rest; higher values mean that it
  30823. will have an initial speed greater than zero. If the
  30824. value if greater than 1, it will decelerate towards the
  30825. middle of its journey. To move the component at a constant
  30826. rate for its entire animation, set both the start and
  30827. end speeds to 1.0
  30828. @param endSpeed a relative speed at which the component should be moving
  30829. when the animation finishes. If this is 0, the component
  30830. will decelerate to a standstill at its final position; higher
  30831. values mean the component will still be moving when it stops.
  30832. To move the component at a constant rate for its entire
  30833. animation, set both the start and end speeds to 1.0
  30834. */
  30835. void animateComponent (Component* const component,
  30836. const Rectangle& finalPosition,
  30837. const int millisecondsToSpendMoving,
  30838. const double startSpeed = 1.0,
  30839. const double endSpeed = 1.0);
  30840. /** Stops a component if it's currently being animated.
  30841. If moveComponentToItsFinalPosition is true, then the component will
  30842. be immediately moved to its destination position and size. If false, it will be
  30843. left in whatever location it currently occupies.
  30844. */
  30845. void cancelAnimation (Component* const component,
  30846. const bool moveComponentToItsFinalPosition);
  30847. /** Clears all of the active animations.
  30848. If moveComponentsToTheirFinalPositions is true, all the components will
  30849. be immediately set to their final positions. If false, they will be
  30850. left in whatever locations they currently occupy.
  30851. */
  30852. void cancelAllAnimations (const bool moveComponentsToTheirFinalPositions);
  30853. /** Returns the destination position for a component.
  30854. If the component is being animated, this will return the target position that
  30855. was specified when animateComponent() was called.
  30856. If the specified component isn't currently being animated, this method will just
  30857. return its current position.
  30858. */
  30859. const Rectangle getComponentDestination (Component* const component);
  30860. /** Returns true if the specified component is currently being animated.
  30861. */
  30862. bool isAnimating (Component* component) const;
  30863. juce_UseDebuggingNewOperator
  30864. private:
  30865. VoidArray tasks;
  30866. uint32 lastTime;
  30867. void* findTaskFor (Component* const component) const;
  30868. void timerCallback();
  30869. };
  30870. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  30871. /********* End of inlined file: juce_ComponentAnimator.h *********/
  30872. class ToolbarItemComponent;
  30873. class ToolbarItemFactory;
  30874. class MissingItemsComponent;
  30875. /**
  30876. A toolbar component.
  30877. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  30878. and looks after their order and layout.
  30879. Items (icon buttons or other custom components) are added to a toolbar using a
  30880. ToolbarItemFactory - each type of item is given a unique ID number, and a
  30881. toolbar might contain more than one instance of a particular item type.
  30882. Toolbars can be interactively customised, allowing the user to drag the items
  30883. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  30884. component as a source of new items.
  30885. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  30886. */
  30887. class JUCE_API Toolbar : public Component,
  30888. public DragAndDropContainer,
  30889. public DragAndDropTarget,
  30890. private ButtonListener
  30891. {
  30892. public:
  30893. /** Creates an empty toolbar component.
  30894. To add some icons or other components to your toolbar, you'll need to
  30895. create a ToolbarItemFactory class that can create a suitable set of
  30896. ToolbarItemComponents.
  30897. @see ToolbarItemFactory, ToolbarItemComponents
  30898. */
  30899. Toolbar();
  30900. /** Destructor.
  30901. Any items on the bar will be deleted when the toolbar is deleted.
  30902. */
  30903. ~Toolbar();
  30904. /** Changes the bar's orientation.
  30905. @see isVertical
  30906. */
  30907. void setVertical (const bool shouldBeVertical);
  30908. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  30909. You can change the bar's orientation with setVertical().
  30910. */
  30911. bool isVertical() const throw() { return vertical; }
  30912. /** Returns the depth of the bar.
  30913. If the bar is horizontal, this will return its height; if it's vertical, it
  30914. will return its width.
  30915. @see getLength
  30916. */
  30917. int getThickness() const throw();
  30918. /** Returns the length of the bar.
  30919. If the bar is horizontal, this will return its width; if it's vertical, it
  30920. will return its height.
  30921. @see getThickness
  30922. */
  30923. int getLength() const throw();
  30924. /** Deletes all items from the bar.
  30925. */
  30926. void clear();
  30927. /** Adds an item to the toolbar.
  30928. The factory's ToolbarItemFactory::createItem() will be called by this method
  30929. to create the component that will actually be added to the bar.
  30930. The new item will be inserted at the specified index (if the index is -1, it
  30931. will be added to the right-hand or bottom end of the bar).
  30932. Once added, the component will be automatically deleted by this object when it
  30933. is no longer needed.
  30934. @see ToolbarItemFactory
  30935. */
  30936. void addItem (ToolbarItemFactory& factory,
  30937. const int itemId,
  30938. const int insertIndex = -1);
  30939. /** Deletes one of the items from the bar.
  30940. */
  30941. void removeToolbarItem (const int itemIndex);
  30942. /** Returns the number of items currently on the toolbar.
  30943. @see getItemId, getItemComponent
  30944. */
  30945. int getNumItems() const throw();
  30946. /** Returns the ID of the item with the given index.
  30947. If the index is less than zero or greater than the number of items,
  30948. this will return 0.
  30949. @see getNumItems
  30950. */
  30951. int getItemId (const int itemIndex) const throw();
  30952. /** Returns the component being used for the item with the given index.
  30953. If the index is less than zero or greater than the number of items,
  30954. this will return 0.
  30955. @see getNumItems
  30956. */
  30957. ToolbarItemComponent* getItemComponent (const int itemIndex) const throw();
  30958. /** Clears this toolbar and adds to it the default set of items that the specified
  30959. factory creates.
  30960. @see ToolbarItemFactory::getDefaultItemSet
  30961. */
  30962. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  30963. /** Options for the way items should be displayed.
  30964. @see setStyle, getStyle
  30965. */
  30966. enum ToolbarItemStyle
  30967. {
  30968. iconsOnly, /**< Means that the toolbar should just contain icons. */
  30969. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  30970. textOnly /**< Means that the toolbar only display text labels for each item. */
  30971. };
  30972. /** Returns the toolbar's current style.
  30973. @see ToolbarItemStyle, setStyle
  30974. */
  30975. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  30976. /** Changes the toolbar's current style.
  30977. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  30978. */
  30979. void setStyle (const ToolbarItemStyle& newStyle);
  30980. /** Flags used by the showCustomisationDialog() method. */
  30981. enum CustomisationFlags
  30982. {
  30983. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  30984. show the "icons only" option on its choice of toolbar styles. */
  30985. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  30986. show the "icons with text" option on its choice of toolbar styles. */
  30987. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  30988. show the "text only" option on its choice of toolbar styles. */
  30989. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  30990. show a button to reset the toolbar to its default set of items. */
  30991. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  30992. };
  30993. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  30994. The dialog contains a ToolbarItemPalette and various controls for editing other
  30995. aspects of the toolbar. This method will block and run the dialog box modally,
  30996. returning when the user closes it.
  30997. The factory is used to determine the set of items that will be shown on the
  30998. palette.
  30999. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  31000. enum.
  31001. @see ToolbarItemPalette
  31002. */
  31003. void showCustomisationDialog (ToolbarItemFactory& factory,
  31004. const int optionFlags = allCustomisationOptionsEnabled);
  31005. /** Turns on or off the toolbar's editing mode, in which its items can be
  31006. rearranged by the user.
  31007. (In most cases it's easier just to use showCustomisationDialog() instead of
  31008. trying to enable editing directly).
  31009. @see ToolbarItemPalette
  31010. */
  31011. void setEditingActive (const bool editingEnabled);
  31012. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  31013. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31014. methods.
  31015. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31016. */
  31017. enum ColourIds
  31018. {
  31019. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  31020. more control over this, override LookAndFeel::paintToolbarBackground(). */
  31021. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  31022. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  31023. over them. */
  31024. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  31025. held down on them. */
  31026. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  31027. when the style is set to iconsWithText or textOnly. */
  31028. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  31029. the customisation dialog is active and the mouse moves over them. */
  31030. };
  31031. /** Returns a string that represents the toolbar's current set of items.
  31032. This lets you later restore the same item layout using restoreFromString().
  31033. @see restoreFromString
  31034. */
  31035. const String toString() const;
  31036. /** Restores a set of items that was previously stored in a string by the toString()
  31037. method.
  31038. The factory object is used to create any item components that are needed.
  31039. @see toString
  31040. */
  31041. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  31042. const String& savedVersion);
  31043. /** @internal */
  31044. void paint (Graphics& g);
  31045. /** @internal */
  31046. void resized();
  31047. /** @internal */
  31048. void buttonClicked (Button*);
  31049. /** @internal */
  31050. void mouseDown (const MouseEvent&);
  31051. /** @internal */
  31052. bool isInterestedInDragSource (const String&, Component*);
  31053. /** @internal */
  31054. void itemDragMove (const String&, Component*, int, int);
  31055. /** @internal */
  31056. void itemDragExit (const String&, Component*);
  31057. /** @internal */
  31058. void itemDropped (const String&, Component*, int, int);
  31059. /** @internal */
  31060. void updateAllItemPositions (const bool animate);
  31061. /** @internal */
  31062. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  31063. juce_UseDebuggingNewOperator
  31064. private:
  31065. Button* missingItemsButton;
  31066. bool vertical, isEditingActive;
  31067. ToolbarItemStyle toolbarStyle;
  31068. ComponentAnimator animator;
  31069. friend class MissingItemsComponent;
  31070. Array <ToolbarItemComponent*> items;
  31071. friend class ItemDragAndDropOverlayComponent;
  31072. static const tchar* const toolbarDragDescriptor;
  31073. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  31074. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  31075. Toolbar (const Toolbar&);
  31076. const Toolbar& operator= (const Toolbar&);
  31077. };
  31078. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  31079. /********* End of inlined file: juce_Toolbar.h *********/
  31080. class ItemDragAndDropOverlayComponent;
  31081. /**
  31082. A component that can be used as one of the items in a Toolbar.
  31083. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  31084. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  31085. class for further info about creating them.
  31086. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  31087. components too. To do this, set the value of isBeingUsedAsAButton to false when
  31088. calling the constructor, and override contentAreaChanged(), in which you can position
  31089. any sub-components you need to add.
  31090. To add basic buttons without writing a special subclass, have a look at the
  31091. ToolbarButton class.
  31092. @see ToolbarButton, Toolbar, ToolbarItemFactory
  31093. */
  31094. class JUCE_API ToolbarItemComponent : public Button
  31095. {
  31096. public:
  31097. /** Constructor.
  31098. @param itemId the ID of the type of toolbar item which this represents
  31099. @param labelText the text to display if the toolbar's style is set to
  31100. Toolbar::iconsWithText or Toolbar::textOnly
  31101. @param isBeingUsedAsAButton set this to false if you don't want the button
  31102. to draw itself with button over/down states when the mouse
  31103. moves over it or clicks
  31104. */
  31105. ToolbarItemComponent (const int itemId,
  31106. const String& labelText,
  31107. const bool isBeingUsedAsAButton);
  31108. /** Destructor. */
  31109. ~ToolbarItemComponent();
  31110. /** Returns the item type ID that this component represents.
  31111. This value is in the constructor.
  31112. */
  31113. int getItemId() const throw() { return itemId; }
  31114. /** Returns the toolbar that contains this component, or 0 if it's not currently
  31115. inside one.
  31116. */
  31117. Toolbar* getToolbar() const;
  31118. /** Returns true if this component is currently inside a toolbar which is vertical.
  31119. @see Toolbar::isVertical
  31120. */
  31121. bool isToolbarVertical() const;
  31122. /** Returns the current style setting of this item.
  31123. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  31124. @see setStyle, Toolbar::getStyle
  31125. */
  31126. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  31127. /** Changes the current style setting of this item.
  31128. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  31129. by the toolbar that holds this item.
  31130. @see setStyle, Toolbar::setStyle
  31131. */
  31132. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  31133. /** Returns the area of the component that should be used to display the button image or
  31134. other contents of the item.
  31135. This content area may change when the item's style changes, and may leave a space around the
  31136. edge of the component where the text label can be shown.
  31137. @see contentAreaChanged
  31138. */
  31139. const Rectangle getContentArea() const throw() { return contentArea; }
  31140. /** This method must return the size criteria for this item, based on a given toolbar
  31141. size and orientation.
  31142. The preferredSize, minSize and maxSize values must all be set by your implementation
  31143. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  31144. toolbar, they refer to the item's height.
  31145. The preferredSize is the size that the component would like to be, and this must be
  31146. between the min and max sizes. For a fixed-size item, simply set all three variables to
  31147. the same value.
  31148. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  31149. Toolbar::getThickness().
  31150. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  31151. vertically.
  31152. */
  31153. virtual bool getToolbarItemSizes (int toolbarThickness,
  31154. bool isToolbarVertical,
  31155. int& preferredSize,
  31156. int& minSize,
  31157. int& maxSize) = 0;
  31158. /** Your subclass should use this method to draw its content area.
  31159. The graphics object that is passed-in will have been clipped and had its origin
  31160. moved to fit the content area as specified get getContentArea(). The width and height
  31161. parameters are the width and height of the content area.
  31162. If the component you're writing isn't a button, you can just do nothing in this method.
  31163. */
  31164. virtual void paintButtonArea (Graphics& g,
  31165. int width, int height,
  31166. bool isMouseOver, bool isMouseDown) = 0;
  31167. /** Callback to indicate that the content area of this item has changed.
  31168. This might be because the component was resized, or because the style changed and
  31169. the space needed for the text label is different.
  31170. See getContentArea() for a description of what the area is.
  31171. */
  31172. virtual void contentAreaChanged (const Rectangle& newBounds) = 0;
  31173. /** Editing modes.
  31174. These are used by setEditingMode(), but will be rarely needed in user code.
  31175. */
  31176. enum ToolbarEditingMode
  31177. {
  31178. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  31179. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  31180. customisation mode, and the items can be dragged around. */
  31181. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  31182. dragged onto a toolbar to add it to that bar.*/
  31183. };
  31184. /** Changes the editing mode of this component.
  31185. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31186. and is unlikely to be of much use in end-user-code.
  31187. */
  31188. void setEditingMode (const ToolbarEditingMode newMode);
  31189. /** Returns the current editing mode of this component.
  31190. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  31191. and is unlikely to be of much use in end-user-code.
  31192. */
  31193. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  31194. /** @internal */
  31195. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  31196. /** @internal */
  31197. void resized();
  31198. juce_UseDebuggingNewOperator
  31199. private:
  31200. friend class Toolbar;
  31201. friend class ItemDragAndDropOverlayComponent;
  31202. const int itemId;
  31203. ToolbarEditingMode mode;
  31204. Toolbar::ToolbarItemStyle toolbarStyle;
  31205. ScopedPointer <Component> overlayComp;
  31206. int dragOffsetX, dragOffsetY;
  31207. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  31208. Rectangle contentArea;
  31209. ToolbarItemComponent (const ToolbarItemComponent&);
  31210. const ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  31211. };
  31212. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  31213. /********* End of inlined file: juce_ToolbarItemComponent.h *********/
  31214. /**
  31215. A type of button designed to go on a toolbar.
  31216. This simple button can have two Drawable objects specified - one for normal
  31217. use and another one (optionally) for the button's "on" state if it's a
  31218. toggle button.
  31219. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  31220. */
  31221. class JUCE_API ToolbarButton : public ToolbarItemComponent
  31222. {
  31223. public:
  31224. /** Creates a ToolbarButton.
  31225. @param itemId the ID for this toolbar item type. This is passed through to the
  31226. ToolbarItemComponent constructor
  31227. @param labelText the text to display on the button (if the toolbar is using a style
  31228. that shows text labels). This is passed through to the
  31229. ToolbarItemComponent constructor
  31230. @param normalImage a drawable object that the button should use as its icon. The object
  31231. that is passed-in here will be kept by this object and will be
  31232. deleted when no longer needed or when this button is deleted.
  31233. @param toggledOnImage a drawable object that the button can use as its icon if the button
  31234. is in a toggled-on state (see the Button::getToggleState() method). If
  31235. 0 is passed-in here, then the normal image will be used instead, regardless
  31236. of the toggle state. The object that is passed-in here will be kept by
  31237. this object and will be deleted when no longer needed or when this button
  31238. is deleted.
  31239. */
  31240. ToolbarButton (const int itemId,
  31241. const String& labelText,
  31242. Drawable* const normalImage,
  31243. Drawable* const toggledOnImage);
  31244. /** Destructor. */
  31245. ~ToolbarButton();
  31246. /** @internal */
  31247. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  31248. int& minSize, int& maxSize);
  31249. /** @internal */
  31250. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  31251. /** @internal */
  31252. void contentAreaChanged (const Rectangle& newBounds);
  31253. juce_UseDebuggingNewOperator
  31254. private:
  31255. ScopedPointer <Drawable> normalImage, toggledOnImage;
  31256. ToolbarButton (const ToolbarButton&);
  31257. const ToolbarButton& operator= (const ToolbarButton&);
  31258. };
  31259. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  31260. /********* End of inlined file: juce_ToolbarButton.h *********/
  31261. #endif
  31262. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  31263. /********* Start of inlined file: juce_CodeDocument.h *********/
  31264. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  31265. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  31266. class CodeDocumentLine;
  31267. /**
  31268. A class for storing and manipulating a source code file.
  31269. When using a CodeEditorComponent, it takes one of these as its source object.
  31270. The CodeDocument stores its content as an array of lines, which makes it
  31271. quick to insert and delete.
  31272. @see CodeEditorComponent
  31273. */
  31274. class JUCE_API CodeDocument
  31275. {
  31276. public:
  31277. /** Creates a new, empty document.
  31278. */
  31279. CodeDocument();
  31280. /** Destructor. */
  31281. ~CodeDocument();
  31282. /** A position in a code document.
  31283. Using this class you can find a position in a code document and quickly get its
  31284. character position, line, and index. By calling setPositionMaintained (true), the
  31285. position is automatically updated when text is inserted or deleted in the document,
  31286. so that it maintains its original place in the text.
  31287. */
  31288. class JUCE_API Position
  31289. {
  31290. public:
  31291. /** Creates an uninitialised postion.
  31292. Don't attempt to call any methods on this until you've given it an owner document
  31293. to refer to!
  31294. */
  31295. Position() throw();
  31296. /** Creates a position based on a line and index in a document.
  31297. Note that this index is NOT the column number, it's the number of characters from the
  31298. start of the line. The "column" number isn't quite the same, because if the line
  31299. contains any tab characters, the relationship of the index to its visual column depends on
  31300. the number of spaces per tab being used!
  31301. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  31302. they will be adjusted to keep them within its limits.
  31303. */
  31304. Position (const CodeDocument* const ownerDocument,
  31305. const int line, const int indexInLine) throw();
  31306. /** Creates a position based on a character index in a document.
  31307. This position is placed at the specified number of characters from the start of the
  31308. document. The line and column are auto-calculated.
  31309. If the position is beyond the range of the document, it'll be adjusted to keep it
  31310. inside.
  31311. */
  31312. Position (const CodeDocument* const ownerDocument,
  31313. const int charactersFromStartOfDocument) throw();
  31314. /** Creates a copy of another position.
  31315. This will copy the position, but the new object will not be set to maintain its position,
  31316. even if the source object was set to do so.
  31317. */
  31318. Position (const Position& other) throw();
  31319. /** Destructor. */
  31320. ~Position() throw();
  31321. const Position& operator= (const Position& other) throw();
  31322. bool operator== (const Position& other) const throw();
  31323. bool operator!= (const Position& other) const throw();
  31324. /** Points this object at a new position within the document.
  31325. If the position is beyond the range of the document, it'll be adjusted to keep it
  31326. inside.
  31327. @see getPosition, setLineAndIndex
  31328. */
  31329. void setPosition (const int charactersFromStartOfDocument) throw();
  31330. /** Returns the position as the number of characters from the start of the document.
  31331. @see setPosition, getLineNumber, getIndexInLine
  31332. */
  31333. int getPosition() const throw() { return characterPos; }
  31334. /** Moves the position to a new line and index within the line.
  31335. Note that the index is NOT the column at which the position appears in an editor.
  31336. If the line contains any tab characters, the relationship of the index to its
  31337. visual position depends on the number of spaces per tab being used!
  31338. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  31339. they will be adjusted to keep them within its limits.
  31340. */
  31341. void setLineAndIndex (const int newLine, const int newIndexInLine) throw();
  31342. /** Returns the line number of this position.
  31343. The first line in the document is numbered zero, not one!
  31344. */
  31345. int getLineNumber() const throw() { return line; }
  31346. /** Returns the number of characters from the start of the line.
  31347. Note that this value is NOT the column at which the position appears in an editor.
  31348. If the line contains any tab characters, the relationship of the index to its
  31349. visual position depends on the number of spaces per tab being used!
  31350. */
  31351. int getIndexInLine() const throw() { return indexInLine; }
  31352. /** Allows the position to be automatically updated when the document changes.
  31353. If this is set to true, the positon will register with its document so that
  31354. when the document has text inserted or deleted, this position will be automatically
  31355. moved to keep it at the same position in the text.
  31356. */
  31357. void setPositionMaintained (const bool isMaintained) throw();
  31358. /** Moves the position forwards or backwards by the specified number of characters.
  31359. @see movedBy
  31360. */
  31361. void moveBy (int characterDelta) throw();
  31362. /** Returns a position which is the same as this one, moved by the specified number of
  31363. characters.
  31364. @see moveBy
  31365. */
  31366. const Position movedBy (const int characterDelta) const throw();
  31367. /** Returns a position which is the same as this one, moved up or down by the specified
  31368. number of lines.
  31369. @see movedBy
  31370. */
  31371. const Position movedByLines (const int deltaLines) const throw();
  31372. /** Returns the character in the document at this position.
  31373. @see getLineText
  31374. */
  31375. const tchar getCharacter() const throw();
  31376. /** Returns the line from the document that this position is within.
  31377. @see getCharacter, getLineNumber
  31378. */
  31379. const String getLineText() const throw();
  31380. private:
  31381. CodeDocument* owner;
  31382. int characterPos, line, indexInLine;
  31383. bool positionMaintained;
  31384. };
  31385. /** Returns the full text of the document. */
  31386. const String getAllContent() const throw();
  31387. /** Returns a section of the document's text. */
  31388. const String getTextBetween (const Position& start, const Position& end) const throw();
  31389. /** Returns a line from the document. */
  31390. const String getLine (const int lineIndex) const throw();
  31391. /** Returns the number of characters in the document. */
  31392. int getNumCharacters() const throw();
  31393. /** Returns the number of lines in the document. */
  31394. int getNumLines() const throw() { return lines.size(); }
  31395. /** Returns the number of characters in the longest line of the document. */
  31396. int getMaximumLineLength() throw();
  31397. /** Deletes a section of the text.
  31398. This operation is undoable.
  31399. */
  31400. void deleteSection (const Position& startPosition, const Position& endPosition);
  31401. /** Inserts some text into the document at a given position.
  31402. This operation is undoable.
  31403. */
  31404. void insertText (const Position& position, const String& text);
  31405. /** Clears the document and replaces it with some new text.
  31406. This operation is undoable - if you're trying to completely reset the document, you
  31407. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  31408. */
  31409. void replaceAllContent (const String& newContent);
  31410. /** Returns the preferred new-line characters for the document.
  31411. This will be either "\n", "\r\n", or (rarely) "\r".
  31412. @see setNewLineCharacters
  31413. */
  31414. const String getNewLineCharacters() const throw() { return newLineChars; }
  31415. /** Sets the new-line characters that the document should use.
  31416. The string must be either "\n", "\r\n", or (rarely) "\r".
  31417. @see getNewLineCharacters
  31418. */
  31419. void setNewLineCharacters (const String& newLine) throw();
  31420. /** Begins a new undo transaction.
  31421. The document itself will not call this internally, so relies on whatever is using the
  31422. document to periodically call this to break up the undo sequence into sensible chunks.
  31423. @see UndoManager::beginNewTransaction
  31424. */
  31425. void newTransaction();
  31426. /** Undo the last operation.
  31427. @see UndoManager::undo
  31428. */
  31429. void undo();
  31430. /** Redo the last operation.
  31431. @see UndoManager::redo
  31432. */
  31433. void redo();
  31434. /** Clears the undo history.
  31435. @see UndoManager::clearUndoHistory
  31436. */
  31437. void clearUndoHistory();
  31438. /** Returns the document's UndoManager */
  31439. UndoManager& getUndoManager() throw() { return undoManager; }
  31440. /** Makes a note that the document's current state matches the one that is saved.
  31441. After this has been called, hasChangedSinceSavePoint() will return false until
  31442. the document has been altered, and then it'll start returning true. If the document is
  31443. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  31444. will again return false.
  31445. @see hasChangedSinceSavePoint
  31446. */
  31447. void setSavePoint() throw();
  31448. /** Returns true if the state of the document differs from the state it was in when
  31449. setSavePoint() was last called.
  31450. @see setSavePoint
  31451. */
  31452. bool hasChangedSinceSavePoint() const throw();
  31453. /** Searches for a word-break. */
  31454. const Position findWordBreakAfter (const Position& position) const throw();
  31455. /** Searches for a word-break. */
  31456. const Position findWordBreakBefore (const Position& position) const throw();
  31457. /** An object that receives callbacks from the CodeDocument when its text changes.
  31458. @see CodeDocument::addListener, CodeDocument::removeListener
  31459. */
  31460. class JUCE_API Listener
  31461. {
  31462. public:
  31463. Listener() {}
  31464. virtual ~Listener() {}
  31465. /** Called by a CodeDocument when it is altered.
  31466. */
  31467. virtual void codeDocumentChanged (const Position& affectedTextStart,
  31468. const Position& affectedTextEnd) = 0;
  31469. };
  31470. /** Registers a listener object to receive callbacks when the document changes.
  31471. If the listener is already registered, this method has no effect.
  31472. @see removeListener
  31473. */
  31474. void addListener (Listener* const listener) throw();
  31475. /** Deregisters a listener.
  31476. @see addListener
  31477. */
  31478. void removeListener (Listener* const listener) throw();
  31479. /** Iterates the text in a CodeDocument.
  31480. This class lets you read characters from a CodeDocument. It's designed to be used
  31481. by a SyntaxAnalyser object.
  31482. @see CodeDocument, SyntaxAnalyser
  31483. */
  31484. class Iterator
  31485. {
  31486. public:
  31487. Iterator (CodeDocument* const document) throw();
  31488. Iterator (const Iterator& other);
  31489. const Iterator& operator= (const Iterator& other) throw();
  31490. ~Iterator() throw();
  31491. /** Reads the next character and returns it.
  31492. @see peekNextChar
  31493. */
  31494. juce_wchar nextChar() throw();
  31495. /** Reads the next character without advancing the current position. */
  31496. juce_wchar peekNextChar() const throw();
  31497. /** Advances the position by one character. */
  31498. void skip() throw();
  31499. /** Returns the position of the next character as its position within the
  31500. whole document.
  31501. */
  31502. int getPosition() const throw() { return position; }
  31503. /** Skips over any whitespace characters until the next character is non-whitespace. */
  31504. void skipWhitespace();
  31505. /** Skips forward until the next character will be the first character on the next line */
  31506. void skipToEndOfLine();
  31507. /** Returns the line number of the next character. */
  31508. int getLine() const throw() { return line; }
  31509. /** Returns true if the iterator has reached the end of the document. */
  31510. bool isEOF() const throw();
  31511. private:
  31512. CodeDocument* document;
  31513. int line, position;
  31514. };
  31515. juce_UseDebuggingNewOperator
  31516. private:
  31517. friend class CodeDocumentInsertAction;
  31518. friend class CodeDocumentDeleteAction;
  31519. friend class Iterator;
  31520. friend class Position;
  31521. OwnedArray <CodeDocumentLine> lines;
  31522. Array <Position*> positionsToMaintain;
  31523. UndoManager undoManager;
  31524. int currentActionIndex, indexOfSavedState;
  31525. int maximumLineLength;
  31526. VoidArray listeners;
  31527. String newLineChars;
  31528. void sendListenerChangeMessage (const int startLine, const int endLine);
  31529. void insert (const String& text, const int insertPos, const bool undoable);
  31530. void remove (const int startPos, const int endPos, const bool undoable);
  31531. CodeDocument (const CodeDocument&);
  31532. const CodeDocument& operator= (const CodeDocument&);
  31533. };
  31534. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  31535. /********* End of inlined file: juce_CodeDocument.h *********/
  31536. #endif
  31537. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  31538. /********* Start of inlined file: juce_CodeEditorComponent.h *********/
  31539. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  31540. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  31541. /********* Start of inlined file: juce_CodeTokeniser.h *********/
  31542. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  31543. #define __JUCE_CODETOKENISER_JUCEHEADER__
  31544. /**
  31545. A base class for tokenising code so that the syntax can be displayed in a
  31546. code editor.
  31547. @see CodeDocument, CodeEditorComponent
  31548. */
  31549. class JUCE_API CodeTokeniser
  31550. {
  31551. public:
  31552. CodeTokeniser() {}
  31553. virtual ~CodeTokeniser() {}
  31554. /** Reads the next token from the source and returns its token type.
  31555. This must leave the source pointing to the first character in the
  31556. next token.
  31557. */
  31558. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  31559. /** Returns a list of the names of the token types this analyser uses.
  31560. The index in this list must match the token type numbers that are
  31561. returned by readNextToken().
  31562. */
  31563. virtual const StringArray getTokenTypes() = 0;
  31564. /** Returns a suggested syntax highlighting colour for a specified
  31565. token type.
  31566. */
  31567. virtual const Colour getDefaultColour (const int tokenType) = 0;
  31568. juce_UseDebuggingNewOperator
  31569. };
  31570. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  31571. /********* End of inlined file: juce_CodeTokeniser.h *********/
  31572. class CodeEditorLine;
  31573. /**
  31574. A text editor component designed specifically for source code.
  31575. This is designed to handle syntax highlighting and fast editing of very large
  31576. files.
  31577. */
  31578. class JUCE_API CodeEditorComponent : public Component,
  31579. public Timer,
  31580. public ScrollBarListener,
  31581. public CodeDocument::Listener,
  31582. public AsyncUpdater
  31583. {
  31584. public:
  31585. /** Creates an editor for a document.
  31586. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  31587. The object that you pass in is not owned or deleted by the editor - you must
  31588. make sure that it doesn't get deleted while this component is still using it.
  31589. @see CodeDocument
  31590. */
  31591. CodeEditorComponent (CodeDocument& document,
  31592. CodeTokeniser* const codeTokeniser);
  31593. /** Destructor. */
  31594. ~CodeEditorComponent();
  31595. /** Returns the code document that this component is editing. */
  31596. CodeDocument& getDocument() const throw() { return document; }
  31597. /** Loads the given content into the document.
  31598. This will completely reset the CodeDocument object, clear its undo history,
  31599. and fill it with this text.
  31600. */
  31601. void loadContent (const String& newContent);
  31602. /** Returns the standard character width. */
  31603. float getCharWidth() const throw() { return charWidth; }
  31604. /** Returns the height of a line of text, in pixels. */
  31605. int getLineHeight() const throw() { return lineHeight; }
  31606. /** Returns the number of whole lines visible on the screen,
  31607. This doesn't include a cut-off line that might be visible at the bottom if the
  31608. component's height isn't an exact multiple of the line-height.
  31609. */
  31610. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  31611. /** Returns the number of whole columns visible on the screen.
  31612. This doesn't include any cut-off columns at the right-hand edge.
  31613. */
  31614. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  31615. /** Returns the current caret position. */
  31616. const CodeDocument::Position getCaretPos() const { return caretPos; }
  31617. /** Moves the caret.
  31618. If selecting is true, the section of the document between the current
  31619. caret position and the new one will become selected. If false, any currently
  31620. selected region will be deselected.
  31621. */
  31622. void moveCaretTo (const CodeDocument::Position& newPos, const bool selecting);
  31623. /** Returns the on-screen position of a character in the document.
  31624. The rectangle returned is relative to this component's top-left origin.
  31625. */
  31626. const Rectangle getCharacterBounds (const CodeDocument::Position& pos) const throw();
  31627. /** Finds the character at a given on-screen position.
  31628. The co-ordinates are relative to this component's top-left origin.
  31629. */
  31630. const CodeDocument::Position getPositionAt (int x, int y);
  31631. void cursorLeft (const bool moveInWholeWordSteps, const bool selecting);
  31632. void cursorRight (const bool moveInWholeWordSteps, const bool selecting);
  31633. void cursorDown (const bool selecting);
  31634. void cursorUp (const bool selecting);
  31635. void pageDown (const bool selecting);
  31636. void pageUp (const bool selecting);
  31637. void scrollDown();
  31638. void scrollUp();
  31639. void scrollToLine (int newFirstLineOnScreen);
  31640. void scrollBy (int deltaLines);
  31641. void scrollToColumn (int newFirstColumnOnScreen);
  31642. void scrollToKeepCaretOnScreen();
  31643. void goToStartOfDocument (const bool selecting);
  31644. void goToStartOfLine (const bool selecting);
  31645. void goToEndOfDocument (const bool selecting);
  31646. void goToEndOfLine (const bool selecting);
  31647. void deselectAll();
  31648. void selectAll();
  31649. void insertTextAtCaret (const String& textToInsert);
  31650. void insertTabAtCaret();
  31651. void cut();
  31652. void copy();
  31653. void copyThenCut();
  31654. void paste();
  31655. void backspace (const bool moveInWholeWordSteps);
  31656. void deleteForward (const bool moveInWholeWordSteps);
  31657. void undo();
  31658. void redo();
  31659. /** Changes the current tab settings.
  31660. This lets you change the tab size and whether pressing the tab key inserts a
  31661. tab character, or its equivalent number of spaces.
  31662. */
  31663. void setTabSize (const int numSpacesPerTab,
  31664. const bool insertSpacesInsteadOfTabCharacters) throw();
  31665. /** Returns the current number of spaces per tab.
  31666. @see setTabSize
  31667. */
  31668. int getTabSize() const throw() { return spacesPerTab; }
  31669. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  31670. @see setTabSize
  31671. */
  31672. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  31673. /** Changes the font.
  31674. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  31675. */
  31676. void setFont (const Font& newFont);
  31677. /** Resets the syntax highlighting colours to the default ones provided by the
  31678. code tokeniser.
  31679. @see CodeTokeniser::getDefaultColour
  31680. */
  31681. void resetToDefaultColours();
  31682. /** Changes one of the syntax highlighting colours.
  31683. The token type values are dependent on the tokeniser being used - use
  31684. CodeTokeniser::getTokenTypes() to get a list of the token types.
  31685. @see getColourForTokenType
  31686. */
  31687. void setColourForTokenType (const int tokenType, const Colour& colour);
  31688. /** Returns one of the syntax highlighting colours.
  31689. The token type values are dependent on the tokeniser being used - use
  31690. CodeTokeniser::getTokenTypes() to get a list of the token types.
  31691. @see setColourForTokenType
  31692. */
  31693. const Colour getColourForTokenType (const int tokenType) const throw();
  31694. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  31695. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31696. methods.
  31697. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31698. */
  31699. enum ColourIds
  31700. {
  31701. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  31702. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  31703. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  31704. selected text. */
  31705. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  31706. enabled. */
  31707. };
  31708. /** Changes the size of the scrollbars. */
  31709. void setScrollbarThickness (const int thickness) throw();
  31710. /** @internal */
  31711. void resized();
  31712. /** @internal */
  31713. void paint (Graphics& g);
  31714. /** @internal */
  31715. bool keyPressed (const KeyPress& key);
  31716. /** @internal */
  31717. void mouseDown (const MouseEvent& e);
  31718. /** @internal */
  31719. void mouseDrag (const MouseEvent& e);
  31720. /** @internal */
  31721. void mouseUp (const MouseEvent& e);
  31722. /** @internal */
  31723. void mouseDoubleClick (const MouseEvent& e);
  31724. /** @internal */
  31725. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  31726. /** @internal */
  31727. void timerCallback();
  31728. /** @internal */
  31729. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart);
  31730. /** @internal */
  31731. void handleAsyncUpdate();
  31732. /** @internal */
  31733. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  31734. const CodeDocument::Position& affectedTextEnd);
  31735. juce_UseDebuggingNewOperator
  31736. private:
  31737. CodeDocument& document;
  31738. Font font;
  31739. int firstLineOnScreen, gutter, spacesPerTab;
  31740. float charWidth;
  31741. int lineHeight, linesOnScreen, columnsOnScreen;
  31742. int scrollbarThickness;
  31743. bool useSpacesForTabs;
  31744. double xOffset;
  31745. CodeDocument::Position caretPos;
  31746. CodeDocument::Position selectionStart, selectionEnd;
  31747. Component* caret;
  31748. ScrollBar* verticalScrollBar;
  31749. ScrollBar* horizontalScrollBar;
  31750. enum DragType
  31751. {
  31752. notDragging,
  31753. draggingSelectionStart,
  31754. draggingSelectionEnd
  31755. };
  31756. DragType dragType;
  31757. CodeTokeniser* codeTokeniser;
  31758. Array <Colour> coloursForTokenCategories;
  31759. OwnedArray <CodeEditorLine> lines;
  31760. void rebuildLineTokens();
  31761. OwnedArray <CodeDocument::Iterator> cachedIterators;
  31762. void clearCachedIterators (const int firstLineToBeInvalid) throw();
  31763. void updateCachedIterators (int maxLineNum);
  31764. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  31765. void updateScrollBars();
  31766. void scrollToLineInternal (int line);
  31767. void scrollToColumnInternal (double column);
  31768. void newTransaction();
  31769. int indexToColumn (int line, int index) const throw();
  31770. int columnToIndex (int line, int column) const throw();
  31771. CodeEditorComponent (const CodeEditorComponent&);
  31772. const CodeEditorComponent& operator= (const CodeEditorComponent&);
  31773. };
  31774. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  31775. /********* End of inlined file: juce_CodeEditorComponent.h *********/
  31776. #endif
  31777. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  31778. #endif
  31779. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  31780. /********* Start of inlined file: juce_CPlusPlusCodeTokeniser.h *********/
  31781. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  31782. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  31783. /**
  31784. A simple lexical analyser for syntax colouring of C++ code.
  31785. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  31786. */
  31787. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  31788. {
  31789. public:
  31790. CPlusPlusCodeTokeniser();
  31791. ~CPlusPlusCodeTokeniser();
  31792. enum TokenType
  31793. {
  31794. tokenType_error = 0,
  31795. tokenType_comment,
  31796. tokenType_builtInKeyword,
  31797. tokenType_identifier,
  31798. tokenType_integerLiteral,
  31799. tokenType_floatLiteral,
  31800. tokenType_stringLiteral,
  31801. tokenType_operator,
  31802. tokenType_bracket,
  31803. tokenType_punctuation,
  31804. tokenType_preprocessor
  31805. };
  31806. int readNextToken (CodeDocument::Iterator& source);
  31807. const StringArray getTokenTypes();
  31808. const Colour getDefaultColour (const int tokenType);
  31809. juce_UseDebuggingNewOperator
  31810. };
  31811. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  31812. /********* End of inlined file: juce_CPlusPlusCodeTokeniser.h *********/
  31813. #endif
  31814. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  31815. #endif
  31816. #ifndef __JUCE_LABEL_JUCEHEADER__
  31817. #endif
  31818. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  31819. #endif
  31820. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  31821. /********* Start of inlined file: juce_ProgressBar.h *********/
  31822. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  31823. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  31824. /**
  31825. A progress bar component.
  31826. To use this, just create one and make it visible. It'll run its own timer
  31827. to keep an eye on a variable that you give it, and will automatically
  31828. redraw itself when the variable changes.
  31829. For an easy way of running a background task with a dialog box showing its
  31830. progress, see the ThreadWithProgressWindow class.
  31831. @see ThreadWithProgressWindow
  31832. */
  31833. class JUCE_API ProgressBar : public Component,
  31834. public SettableTooltipClient,
  31835. private Timer
  31836. {
  31837. public:
  31838. /** Creates a ProgressBar.
  31839. @param progress pass in a reference to a double that you're going to
  31840. update with your task's progress. The ProgressBar will
  31841. monitor the value of this variable and will redraw itself
  31842. when the value changes. The range is from 0 to 1.0. Obviously
  31843. you'd better be careful not to delete this variable while the
  31844. ProgressBar still exists!
  31845. */
  31846. ProgressBar (double& progress);
  31847. /** Destructor. */
  31848. ~ProgressBar();
  31849. /** Turns the percentage display on or off.
  31850. By default this is on, and the progress bar will display a text string showing
  31851. its current percentage.
  31852. */
  31853. void setPercentageDisplay (const bool shouldDisplayPercentage);
  31854. /** Gives the progress bar a string to display inside it.
  31855. If you call this, it will turn off the percentage display.
  31856. @see setPercentageDisplay
  31857. */
  31858. void setTextToDisplay (const String& text);
  31859. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  31860. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  31861. methods.
  31862. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  31863. */
  31864. enum ColourIds
  31865. {
  31866. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  31867. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  31868. classes will probably use variations on this colour. */
  31869. };
  31870. juce_UseDebuggingNewOperator
  31871. protected:
  31872. /** @internal */
  31873. void paint (Graphics& g);
  31874. /** @internal */
  31875. void lookAndFeelChanged();
  31876. /** @internal */
  31877. void visibilityChanged();
  31878. /** @internal */
  31879. void colourChanged();
  31880. private:
  31881. double& progress;
  31882. double currentValue;
  31883. bool displayPercentage;
  31884. String displayedMessage, currentMessage;
  31885. uint32 lastCallbackTime;
  31886. void timerCallback();
  31887. ProgressBar (const ProgressBar&);
  31888. const ProgressBar& operator= (const ProgressBar&);
  31889. };
  31890. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  31891. /********* End of inlined file: juce_ProgressBar.h *********/
  31892. #endif
  31893. #ifndef __JUCE_SLIDER_JUCEHEADER__
  31894. /********* Start of inlined file: juce_Slider.h *********/
  31895. #ifndef __JUCE_SLIDER_JUCEHEADER__
  31896. #define __JUCE_SLIDER_JUCEHEADER__
  31897. /********* Start of inlined file: juce_SliderListener.h *********/
  31898. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  31899. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  31900. class Slider;
  31901. /**
  31902. A class for receiving callbacks from a Slider.
  31903. To be told when a slider's value changes, you can register a SliderListener
  31904. object using Slider::addListener().
  31905. @see Slider::addListener, Slider::removeListener
  31906. */
  31907. class JUCE_API SliderListener
  31908. {
  31909. public:
  31910. /** Destructor. */
  31911. virtual ~SliderListener() {}
  31912. /** Called when the slider's value is changed.
  31913. This may be caused by dragging it, or by typing in its text entry box,
  31914. or by a call to Slider::setValue().
  31915. You can find out the new value using Slider::getValue().
  31916. @see Slider::valueChanged
  31917. */
  31918. virtual void sliderValueChanged (Slider* slider) = 0;
  31919. /** Called when the slider is about to be dragged.
  31920. This is called when a drag begins, then it's followed by multiple calls
  31921. to sliderValueChanged(), and then sliderDragEnded() is called after the
  31922. user lets go.
  31923. @see sliderDragEnded, Slider::startedDragging
  31924. */
  31925. virtual void sliderDragStarted (Slider* slider);
  31926. /** Called after a drag operation has finished.
  31927. @see sliderDragStarted, Slider::stoppedDragging
  31928. */
  31929. virtual void sliderDragEnded (Slider* slider);
  31930. };
  31931. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  31932. /********* End of inlined file: juce_SliderListener.h *********/
  31933. /**
  31934. A slider control for changing a value.
  31935. The slider can be horizontal, vertical, or rotary, and can optionally have
  31936. a text-box inside it to show an editable display of the current value.
  31937. To use it, create a Slider object and use the setSliderStyle() method
  31938. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  31939. To define the values that it can be set to, see the setRange() and setValue() methods.
  31940. There are also lots of custom tweaks you can do by subclassing and overriding
  31941. some of the virtual methods, such as changing the scaling, changing the format of
  31942. the text display, custom ways of limiting the values, etc.
  31943. You can register SliderListeners with a slider, which will be informed when the value
  31944. changes, or a subclass can override valueChanged() to be informed synchronously.
  31945. @see SliderListener
  31946. */
  31947. class JUCE_API Slider : public Component,
  31948. public SettableTooltipClient,
  31949. private AsyncUpdater,
  31950. private ButtonListener,
  31951. private LabelListener
  31952. {
  31953. public:
  31954. /** Creates a slider.
  31955. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  31956. setRange(), etc.
  31957. */
  31958. Slider (const String& componentName);
  31959. /** Destructor. */
  31960. ~Slider();
  31961. /** The types of slider available.
  31962. @see setSliderStyle, setRotaryParameters
  31963. */
  31964. enum SliderStyle
  31965. {
  31966. LinearHorizontal, /**< A traditional horizontal slider. */
  31967. LinearVertical, /**< A traditional vertical slider. */
  31968. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  31969. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  31970. @see setRotaryParameters */
  31971. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  31972. @see setRotaryParameters */
  31973. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  31974. @see setRotaryParameters */
  31975. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  31976. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  31977. @see setMinValue, setMaxValue */
  31978. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  31979. @see setMinValue, setMaxValue */
  31980. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  31981. value, with the current value being somewhere between them.
  31982. @see setMinValue, setMaxValue */
  31983. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  31984. value, with the current value being somewhere between them.
  31985. @see setMinValue, setMaxValue */
  31986. };
  31987. /** Changes the type of slider interface being used.
  31988. @param newStyle the type of interface
  31989. @see setRotaryParameters, setVelocityBasedMode,
  31990. */
  31991. void setSliderStyle (const SliderStyle newStyle);
  31992. /** Returns the slider's current style.
  31993. @see setSliderStyle
  31994. */
  31995. SliderStyle getSliderStyle() const throw() { return style; }
  31996. /** Changes the properties of a rotary slider.
  31997. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  31998. the slider's minimum value is represented
  31999. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  32000. the slider's maximum value is represented. This must be
  32001. greater than startAngleRadians
  32002. @param stopAtEnd if true, then when the slider is dragged around past the
  32003. minimum or maximum, it'll stop there; if false, it'll wrap
  32004. back to the opposite value
  32005. */
  32006. void setRotaryParameters (const float startAngleRadians,
  32007. const float endAngleRadians,
  32008. const bool stopAtEnd);
  32009. /** Sets the distance the mouse has to move to drag the slider across
  32010. the full extent of its range.
  32011. This only applies when in modes like RotaryHorizontalDrag, where it's using
  32012. relative mouse movements to adjust the slider.
  32013. */
  32014. void setMouseDragSensitivity (const int distanceForFullScaleDrag);
  32015. /** Changes the way the the mouse is used when dragging the slider.
  32016. If true, this will turn on velocity-sensitive dragging, so that
  32017. the faster the mouse moves, the bigger the movement to the slider. This
  32018. helps when making accurate adjustments if the slider's range is quite large.
  32019. If false, the slider will just try to snap to wherever the mouse is.
  32020. */
  32021. void setVelocityBasedMode (const bool isVelocityBased) throw();
  32022. /** Returns true if velocity-based mode is active.
  32023. @see setVelocityBasedMode
  32024. */
  32025. bool getVelocityBasedMode() const throw() { return isVelocityBased; }
  32026. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  32027. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  32028. or if you're holding down ctrl.
  32029. @param sensitivity higher values than 1.0 increase the range of acceleration used
  32030. @param threshold the minimum number of pixels that the mouse needs to move for it
  32031. to be treated as a movement
  32032. @param offset values greater than 0.0 increase the minimum speed that will be used when
  32033. the threshold is reached
  32034. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  32035. key to toggle velocity-sensitive mode
  32036. */
  32037. void setVelocityModeParameters (const double sensitivity = 1.0,
  32038. const int threshold = 1,
  32039. const double offset = 0.0,
  32040. const bool userCanPressKeyToSwapMode = true) throw();
  32041. /** Returns the velocity sensitivity setting.
  32042. @see setVelocityModeParameters
  32043. */
  32044. double getVelocitySensitivity() const throw() { return velocityModeSensitivity; }
  32045. /** Returns the velocity threshold setting.
  32046. @see setVelocityModeParameters
  32047. */
  32048. int getVelocityThreshold() const throw() { return velocityModeThreshold; }
  32049. /** Returns the velocity offset setting.
  32050. @see setVelocityModeParameters
  32051. */
  32052. double getVelocityOffset() const throw() { return velocityModeOffset; }
  32053. /** Returns the velocity user key setting.
  32054. @see setVelocityModeParameters
  32055. */
  32056. bool getVelocityModeIsSwappable() const throw() { return userKeyOverridesVelocity; }
  32057. /** Sets up a skew factor to alter the way values are distributed.
  32058. You may want to use a range of values on the slider where more accuracy
  32059. is required towards one end of the range, so this will logarithmically
  32060. spread the values across the length of the slider.
  32061. If the factor is < 1.0, the lower end of the range will fill more of the
  32062. slider's length; if the factor is > 1.0, the upper end of the range
  32063. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  32064. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  32065. method instead.
  32066. @see getSkewFactor, setSkewFactorFromMidPoint
  32067. */
  32068. void setSkewFactor (const double factor) throw();
  32069. /** Sets up a skew factor to alter the way values are distributed.
  32070. This allows you to specify the slider value that should appear in the
  32071. centre of the slider's visible range.
  32072. @see setSkewFactor, getSkewFactor
  32073. */
  32074. void setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw();
  32075. /** Returns the current skew factor.
  32076. See setSkewFactor for more info.
  32077. @see setSkewFactor, setSkewFactorFromMidPoint
  32078. */
  32079. double getSkewFactor() const throw() { return skewFactor; }
  32080. /** Used by setIncDecButtonsMode().
  32081. */
  32082. enum IncDecButtonMode
  32083. {
  32084. incDecButtonsNotDraggable,
  32085. incDecButtonsDraggable_AutoDirection,
  32086. incDecButtonsDraggable_Horizontal,
  32087. incDecButtonsDraggable_Vertical
  32088. };
  32089. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  32090. can be dragged on the buttons to drag the values.
  32091. By default this is turned off. When enabled, clicking on the buttons still works
  32092. them as normal, but by holding down the mouse on a button and dragging it a little
  32093. distance, it flips into a mode where the value can be dragged. The drag direction can
  32094. either be set explicitly to be vertical or horizontal, or can be set to
  32095. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  32096. are side-by-side or above each other.
  32097. */
  32098. void setIncDecButtonsMode (const IncDecButtonMode mode);
  32099. /** The position of the slider's text-entry box.
  32100. @see setTextBoxStyle
  32101. */
  32102. enum TextEntryBoxPosition
  32103. {
  32104. NoTextBox, /**< Doesn't display a text box. */
  32105. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  32106. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  32107. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  32108. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  32109. };
  32110. /** Changes the location and properties of the text-entry box.
  32111. @param newPosition where it should go (or NoTextBox to not have one at all)
  32112. @param isReadOnly if true, it's a read-only display
  32113. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  32114. room for the slider as well!
  32115. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  32116. room for the slider as well!
  32117. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  32118. */
  32119. void setTextBoxStyle (const TextEntryBoxPosition newPosition,
  32120. const bool isReadOnly,
  32121. const int textEntryBoxWidth,
  32122. const int textEntryBoxHeight);
  32123. /** Returns the status of the text-box.
  32124. @see setTextBoxStyle
  32125. */
  32126. const TextEntryBoxPosition getTextBoxPosition() const throw() { return textBoxPos; }
  32127. /** Returns the width used for the text-box.
  32128. @see setTextBoxStyle
  32129. */
  32130. int getTextBoxWidth() const throw() { return textBoxWidth; }
  32131. /** Returns the height used for the text-box.
  32132. @see setTextBoxStyle
  32133. */
  32134. int getTextBoxHeight() const throw() { return textBoxHeight; }
  32135. /** Makes the text-box editable.
  32136. By default this is true, and the user can enter values into the textbox,
  32137. but it can be turned off if that's not suitable.
  32138. @see setTextBoxStyle, getValueFromText, getTextFromValue
  32139. */
  32140. void setTextBoxIsEditable (const bool shouldBeEditable) throw();
  32141. /** Returns true if the text-box is read-only.
  32142. @see setTextBoxStyle
  32143. */
  32144. bool isTextBoxEditable() const throw() { return editableText; }
  32145. /** If the text-box is editable, this will give it the focus so that the user can
  32146. type directly into it.
  32147. This is basically the effect as the user clicking on it.
  32148. */
  32149. void showTextBox();
  32150. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  32151. focus away from it.
  32152. @param discardCurrentEditorContents if true, the slider's value will be left
  32153. unchanged; if false, the current contents of the
  32154. text editor will be used to set the slider position
  32155. before it is hidden.
  32156. */
  32157. void hideTextBox (const bool discardCurrentEditorContents);
  32158. /** Changes the slider's current value.
  32159. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  32160. that are registered, and will synchronously call the valueChanged() method in case subclasses
  32161. want to handle it.
  32162. @param newValue the new value to set - this will be restricted by the
  32163. minimum and maximum range, and will be snapped to the
  32164. nearest interval if one has been set
  32165. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  32166. any SliderListeners or the valueChanged() method
  32167. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  32168. synchronously; if false, it will be asynchronous
  32169. */
  32170. void setValue (double newValue,
  32171. const bool sendUpdateMessage = true,
  32172. const bool sendMessageSynchronously = false);
  32173. /** Returns the slider's current value. */
  32174. double getValue() const throw();
  32175. /** Sets the limits that the slider's value can take.
  32176. @param newMinimum the lowest value allowed
  32177. @param newMaximum the highest value allowed
  32178. @param newInterval the steps in which the value is allowed to increase - if this
  32179. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  32180. */
  32181. void setRange (const double newMinimum,
  32182. const double newMaximum,
  32183. const double newInterval = 0);
  32184. /** Returns the current maximum value.
  32185. @see setRange
  32186. */
  32187. double getMaximum() const throw() { return maximum; }
  32188. /** Returns the current minimum value.
  32189. @see setRange
  32190. */
  32191. double getMinimum() const throw() { return minimum; }
  32192. /** Returns the current step-size for values.
  32193. @see setRange
  32194. */
  32195. double getInterval() const throw() { return interval; }
  32196. /** For a slider with two or three thumbs, this returns the lower of its values.
  32197. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  32198. A slider with three values also uses the normal getValue() and setValue() methods to
  32199. control the middle value.
  32200. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  32201. */
  32202. double getMinValue() const throw();
  32203. /** For a slider with two or three thumbs, this sets the lower of its values.
  32204. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  32205. that are registered, and will synchronously call the valueChanged() method in case subclasses
  32206. want to handle it.
  32207. @param newValue the new value to set - this will be restricted by the
  32208. minimum and maximum range, and will be snapped to the nearest
  32209. interval if one has been set.
  32210. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  32211. any SliderListeners or the valueChanged() method
  32212. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  32213. synchronously; if false, it will be asynchronous
  32214. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  32215. max value (in a two-value slider) or the mid value (in a three-value
  32216. slider). If false, then if this value goes beyond those values,
  32217. it will push them along with it.
  32218. @see getMinValue, setMaxValue, setValue
  32219. */
  32220. void setMinValue (double newValue,
  32221. const bool sendUpdateMessage = true,
  32222. const bool sendMessageSynchronously = false,
  32223. const bool allowNudgingOfOtherValues = false);
  32224. /** For a slider with two or three thumbs, this returns the higher of its values.
  32225. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  32226. A slider with three values also uses the normal getValue() and setValue() methods to
  32227. control the middle value.
  32228. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  32229. */
  32230. double getMaxValue() const throw();
  32231. /** For a slider with two or three thumbs, this sets the lower of its values.
  32232. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  32233. that are registered, and will synchronously call the valueChanged() method in case subclasses
  32234. want to handle it.
  32235. @param newValue the new value to set - this will be restricted by the
  32236. minimum and maximum range, and will be snapped to the nearest
  32237. interval if one has been set.
  32238. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  32239. any SliderListeners or the valueChanged() method
  32240. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  32241. synchronously; if false, it will be asynchronous
  32242. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  32243. min value (in a two-value slider) or the mid value (in a three-value
  32244. slider). If false, then if this value goes beyond those values,
  32245. it will push them along with it.
  32246. @see getMaxValue, setMinValue, setValue
  32247. */
  32248. void setMaxValue (double newValue,
  32249. const bool sendUpdateMessage = true,
  32250. const bool sendMessageSynchronously = false,
  32251. const bool allowNudgingOfOtherValues = false);
  32252. /** Adds a listener to be called when this slider's value changes. */
  32253. void addListener (SliderListener* const listener) throw();
  32254. /** Removes a previously-registered listener. */
  32255. void removeListener (SliderListener* const listener) throw();
  32256. /** This lets you choose whether double-clicking moves the slider to a given position.
  32257. By default this is turned off, but it's handy if you want a double-click to act
  32258. as a quick way of resetting a slider. Just pass in the value you want it to
  32259. go to when double-clicked.
  32260. @see getDoubleClickReturnValue
  32261. */
  32262. void setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  32263. const double valueToSetOnDoubleClick) throw();
  32264. /** Returns the values last set by setDoubleClickReturnValue() method.
  32265. Sets isEnabled to true if double-click is enabled, and returns the value
  32266. that was set.
  32267. @see setDoubleClickReturnValue
  32268. */
  32269. double getDoubleClickReturnValue (bool& isEnabled) const throw();
  32270. /** Tells the slider whether to keep sending change messages while the user
  32271. is dragging the slider.
  32272. If set to true, a change message will only be sent when the user has
  32273. dragged the slider and let go. If set to false (the default), then messages
  32274. will be continuously sent as they drag it while the mouse button is still
  32275. held down.
  32276. */
  32277. void setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw();
  32278. /** This lets you change whether the slider thumb jumps to the mouse position
  32279. when you click.
  32280. By default, this is true. If it's false, then the slider moves with relative
  32281. motion when you drag it.
  32282. This only applies to linear bars, and won't affect two- or three- value
  32283. sliders.
  32284. */
  32285. void setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw();
  32286. /** If enabled, this gives the slider a pop-up bubble which appears while the
  32287. slider is being dragged.
  32288. This can be handy if your slider doesn't have a text-box, so that users can
  32289. see the value just when they're changing it.
  32290. If you pass a component as the parentComponentToUse parameter, the pop-up
  32291. bubble will be added as a child of that component when it's needed. If you
  32292. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  32293. transparent window, so if you're using an OS that can't do transparent windows
  32294. you'll have to add it to a parent component instead).
  32295. */
  32296. void setPopupDisplayEnabled (const bool isEnabled,
  32297. Component* const parentComponentToUse) throw();
  32298. /** If this is set to true, then right-clicking on the slider will pop-up
  32299. a menu to let the user change the way it works.
  32300. By default this is turned off, but when turned on, the menu will include
  32301. things like velocity sensitivity, and for rotary sliders, whether they
  32302. use a linear or rotary mouse-drag to move them.
  32303. */
  32304. void setPopupMenuEnabled (const bool menuEnabled) throw();
  32305. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  32306. By default it's enabled.
  32307. */
  32308. void setScrollWheelEnabled (const bool enabled) throw();
  32309. /** Returns a number to indicate which thumb is currently being dragged by the
  32310. mouse.
  32311. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  32312. the maximum-value thumb, or -1 if none is currently down.
  32313. */
  32314. int getThumbBeingDragged() const throw() { return sliderBeingDragged; }
  32315. /** Callback to indicate that the user is about to start dragging the slider.
  32316. @see SliderListener::sliderDragStarted
  32317. */
  32318. virtual void startedDragging();
  32319. /** Callback to indicate that the user has just stopped dragging the slider.
  32320. @see SliderListener::sliderDragEnded
  32321. */
  32322. virtual void stoppedDragging();
  32323. /** Callback to indicate that the user has just moved the slider.
  32324. @see SliderListener::sliderValueChanged
  32325. */
  32326. virtual void valueChanged();
  32327. /** Callback to indicate that the user has just moved the slider.
  32328. Note - the valueChanged() method has changed its format and now no longer has
  32329. any parameters. Update your code to use the new version.
  32330. This version has been left here with an int as its return value to cause
  32331. a syntax error if you've got existing code that uses the old version.
  32332. */
  32333. virtual int valueChanged (double) { jassertfalse; return 0; }
  32334. /** Subclasses can override this to convert a text string to a value.
  32335. When the user enters something into the text-entry box, this method is
  32336. called to convert it to a value.
  32337. The default routine just tries to convert it to a double.
  32338. @see getTextFromValue
  32339. */
  32340. virtual double getValueFromText (const String& text);
  32341. /** Turns the slider's current value into a text string.
  32342. Subclasses can override this to customise the formatting of the text-entry box.
  32343. The default implementation just turns the value into a string, using
  32344. a number of decimal places based on the range interval. If a suffix string
  32345. has been set using setTextValueSuffix(), this will be appended to the text.
  32346. @see getValueFromText
  32347. */
  32348. virtual const String getTextFromValue (double value);
  32349. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  32350. a string.
  32351. This is used by the default implementation of getTextFromValue(), and is just
  32352. appended to the numeric value. For more advanced formatting, you can override
  32353. getTextFromValue() and do something else.
  32354. */
  32355. void setTextValueSuffix (const String& suffix);
  32356. /** Allows a user-defined mapping of distance along the slider to its value.
  32357. The default implementation for this performs the skewing operation that
  32358. can be set up in the setSkewFactor() method. Override it if you need
  32359. some kind of custom mapping instead, but make sure you also implement the
  32360. inverse function in valueToProportionOfLength().
  32361. @param proportion a value 0 to 1.0, indicating a distance along the slider
  32362. @returns the slider value that is represented by this position
  32363. @see valueToProportionOfLength
  32364. */
  32365. virtual double proportionOfLengthToValue (double proportion);
  32366. /** Allows a user-defined mapping of value to the position of the slider along its length.
  32367. The default implementation for this performs the skewing operation that
  32368. can be set up in the setSkewFactor() method. Override it if you need
  32369. some kind of custom mapping instead, but make sure you also implement the
  32370. inverse function in proportionOfLengthToValue().
  32371. @param value a valid slider value, between the range of values specified in
  32372. setRange()
  32373. @returns a value 0 to 1.0 indicating the distance along the slider that
  32374. represents this value
  32375. @see proportionOfLengthToValue
  32376. */
  32377. virtual double valueToProportionOfLength (double value);
  32378. /** Returns the X or Y coordinate of a value along the slider's length.
  32379. If the slider is horizontal, this will be the X coordinate of the given
  32380. value, relative to the left of the slider. If it's vertical, then this will
  32381. be the Y coordinate, relative to the top of the slider.
  32382. If the slider is rotary, this will throw an assertion and return 0. If the
  32383. value is out-of-range, it will be constrained to the length of the slider.
  32384. */
  32385. float getPositionOfValue (const double value);
  32386. /** This can be overridden to allow the slider to snap to user-definable values.
  32387. If overridden, it will be called when the user tries to move the slider to
  32388. a given position, and allows a subclass to sanity-check this value, possibly
  32389. returning a different value to use instead.
  32390. @param attemptedValue the value the user is trying to enter
  32391. @param userIsDragging true if the user is dragging with the mouse; false if
  32392. they are entering the value using the text box
  32393. @returns the value to use instead
  32394. */
  32395. virtual double snapValue (double attemptedValue, const bool userIsDragging);
  32396. /** This can be called to force the text box to update its contents.
  32397. (Not normally needed, as this is done automatically).
  32398. */
  32399. void updateText();
  32400. /** True if the slider moves horizontally. */
  32401. bool isHorizontal() const throw();
  32402. /** True if the slider moves vertically. */
  32403. bool isVertical() const throw();
  32404. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  32405. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32406. methods.
  32407. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32408. */
  32409. enum ColourIds
  32410. {
  32411. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  32412. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  32413. and feel class how this is used. */
  32414. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  32415. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  32416. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  32417. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  32418. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  32419. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  32420. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  32421. };
  32422. juce_UseDebuggingNewOperator
  32423. protected:
  32424. /** @internal */
  32425. void labelTextChanged (Label*);
  32426. /** @internal */
  32427. void paint (Graphics& g);
  32428. /** @internal */
  32429. void resized();
  32430. /** @internal */
  32431. void mouseDown (const MouseEvent& e);
  32432. /** @internal */
  32433. void mouseUp (const MouseEvent& e);
  32434. /** @internal */
  32435. void mouseDrag (const MouseEvent& e);
  32436. /** @internal */
  32437. void mouseDoubleClick (const MouseEvent& e);
  32438. /** @internal */
  32439. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  32440. /** @internal */
  32441. void modifierKeysChanged (const ModifierKeys& modifiers);
  32442. /** @internal */
  32443. void buttonClicked (Button* button);
  32444. /** @internal */
  32445. void lookAndFeelChanged();
  32446. /** @internal */
  32447. void enablementChanged();
  32448. /** @internal */
  32449. void focusOfChildComponentChanged (FocusChangeType cause);
  32450. /** @internal */
  32451. void handleAsyncUpdate();
  32452. /** @internal */
  32453. void colourChanged();
  32454. private:
  32455. SortedSet <void*> listeners;
  32456. double currentValue, valueMin, valueMax;
  32457. double minimum, maximum, interval, doubleClickReturnValue;
  32458. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  32459. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  32460. int velocityModeThreshold;
  32461. float rotaryStart, rotaryEnd;
  32462. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  32463. int mouseDragStartX, mouseDragStartY;
  32464. int sliderRegionStart, sliderRegionSize;
  32465. int sliderBeingDragged;
  32466. int pixelsForFullDragExtent;
  32467. Rectangle sliderRect;
  32468. String textSuffix;
  32469. SliderStyle style;
  32470. TextEntryBoxPosition textBoxPos;
  32471. int textBoxWidth, textBoxHeight;
  32472. IncDecButtonMode incDecButtonMode;
  32473. bool editableText : 1, doubleClickToValue : 1;
  32474. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  32475. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  32476. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  32477. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  32478. Font font;
  32479. Label* valueBox;
  32480. Button* incButton;
  32481. Button* decButton;
  32482. ScopedPointer <Component> popupDisplay;
  32483. Component* parentForPopupDisplay;
  32484. float getLinearSliderPos (const double value);
  32485. void restoreMouseIfHidden();
  32486. void sendDragStart();
  32487. void sendDragEnd();
  32488. double constrainedValue (double value) const throw();
  32489. void triggerChangeMessage (const bool synchronous);
  32490. bool incDecDragDirectionIsHorizontal() const throw();
  32491. Slider (const Slider&);
  32492. const Slider& operator= (const Slider&);
  32493. };
  32494. #endif // __JUCE_SLIDER_JUCEHEADER__
  32495. /********* End of inlined file: juce_Slider.h *********/
  32496. #endif
  32497. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  32498. #endif
  32499. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  32500. /********* Start of inlined file: juce_TableHeaderComponent.h *********/
  32501. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  32502. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  32503. class TableHeaderComponent;
  32504. /**
  32505. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  32506. You can register one of these objects for table events using TableHeaderComponent::addListener()
  32507. and TableHeaderComponent::removeListener().
  32508. @see TableHeaderComponent
  32509. */
  32510. class JUCE_API TableHeaderListener
  32511. {
  32512. public:
  32513. TableHeaderListener() {}
  32514. /** Destructor. */
  32515. virtual ~TableHeaderListener() {}
  32516. /** This is called when some of the table's columns are added, removed, hidden,
  32517. or rearranged.
  32518. */
  32519. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  32520. /** This is called when one or more of the table's columns are resized.
  32521. */
  32522. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  32523. /** This is called when the column by which the table should be sorted is changed.
  32524. */
  32525. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  32526. /** This is called when the user begins or ends dragging one of the columns around.
  32527. When the user starts dragging a column, this is called with the ID of that
  32528. column. When they finish dragging, it is called again with 0 as the ID.
  32529. */
  32530. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  32531. int columnIdNowBeingDragged);
  32532. };
  32533. /**
  32534. A component that displays a strip of column headings for a table, and allows these
  32535. to be resized, dragged around, etc.
  32536. This is just the component that goes at the top of a table. You can use it
  32537. directly for custom components, or to create a simple table, use the
  32538. TableListBox class.
  32539. To use one of these, create it and use addColumn() to add all the columns that you need.
  32540. Each column must be given a unique ID number that's used to refer to it.
  32541. @see TableListBox, TableHeaderListener
  32542. */
  32543. class JUCE_API TableHeaderComponent : public Component,
  32544. private AsyncUpdater
  32545. {
  32546. public:
  32547. /** Creates an empty table header.
  32548. */
  32549. TableHeaderComponent();
  32550. /** Destructor. */
  32551. ~TableHeaderComponent();
  32552. /** A combination of these flags are passed into the addColumn() method to specify
  32553. the properties of a column.
  32554. */
  32555. enum ColumnPropertyFlags
  32556. {
  32557. 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. */
  32558. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  32559. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  32560. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  32561. 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. */
  32562. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  32563. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  32564. /** This set of default flags is used as the default parameter value in addColumn(). */
  32565. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  32566. /** A quick way of combining flags for a column that's not resizable. */
  32567. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  32568. /** A quick way of combining flags for a column that's not resizable or sortable. */
  32569. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  32570. /** A quick way of combining flags for a column that's not sortable. */
  32571. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  32572. };
  32573. /** Adds a column to the table.
  32574. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  32575. registered listeners.
  32576. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  32577. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  32578. a unique ID. This is used to identify the column later on, after the user may have
  32579. changed the order that they appear in
  32580. @param width the initial width of the column, in pixels
  32581. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  32582. if the 'resizable' flag is specified for this column
  32583. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  32584. if the 'resizable' flag is specified for this column
  32585. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  32586. properties of this column
  32587. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  32588. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  32589. all columns, not just the index amongst those that are currently visible
  32590. */
  32591. void addColumn (const String& columnName,
  32592. const int columnId,
  32593. const int width,
  32594. const int minimumWidth = 30,
  32595. const int maximumWidth = -1,
  32596. const int propertyFlags = defaultFlags,
  32597. const int insertIndex = -1);
  32598. /** Removes a column with the given ID.
  32599. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  32600. registered listeners.
  32601. */
  32602. void removeColumn (const int columnIdToRemove);
  32603. /** Deletes all columns from the table.
  32604. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  32605. registered listeners.
  32606. */
  32607. void removeAllColumns();
  32608. /** Returns the number of columns in the table.
  32609. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  32610. return the total number of columns, including hidden ones.
  32611. @see isColumnVisible
  32612. */
  32613. int getNumColumns (const bool onlyCountVisibleColumns) const throw();
  32614. /** Returns the name for a column.
  32615. @see setColumnName
  32616. */
  32617. const String getColumnName (const int columnId) const throw();
  32618. /** Changes the name of a column. */
  32619. void setColumnName (const int columnId, const String& newName);
  32620. /** Moves a column to a different index in the table.
  32621. @param columnId the column to move
  32622. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  32623. */
  32624. void moveColumn (const int columnId, int newVisibleIndex);
  32625. /** Returns the width of one of the columns.
  32626. */
  32627. int getColumnWidth (const int columnId) const throw();
  32628. /** Changes the width of a column.
  32629. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  32630. */
  32631. void setColumnWidth (const int columnId, const int newWidth);
  32632. /** Shows or hides a column.
  32633. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  32634. @see isColumnVisible
  32635. */
  32636. void setColumnVisible (const int columnId, const bool shouldBeVisible);
  32637. /** Returns true if this column is currently visible.
  32638. @see setColumnVisible
  32639. */
  32640. bool isColumnVisible (const int columnId) const;
  32641. /** Changes the column which is the sort column.
  32642. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  32643. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  32644. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  32645. @see getSortColumnId, isSortedForwards, reSortTable
  32646. */
  32647. void setSortColumnId (const int columnId, const bool sortForwards);
  32648. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  32649. @see setSortColumnId, isSortedForwards
  32650. */
  32651. int getSortColumnId() const throw();
  32652. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  32653. @see setSortColumnId
  32654. */
  32655. bool isSortedForwards() const throw();
  32656. /** Triggers a re-sort of the table according to the current sort-column.
  32657. If you modifiy the table's contents, you can call this to signal that the table needs
  32658. to be re-sorted.
  32659. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  32660. tableSortOrderChanged() method of any listeners).
  32661. */
  32662. void reSortTable();
  32663. /** Returns the total width of all the visible columns in the table.
  32664. */
  32665. int getTotalWidth() const throw();
  32666. /** Returns the index of a given column.
  32667. If there's no such column ID, this will return -1.
  32668. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  32669. otherwise it'll return the index amongst all the columns, including any hidden ones.
  32670. */
  32671. int getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw();
  32672. /** Returns the ID of the column at a given index.
  32673. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  32674. otherwise it'll count it amongst all the columns, including any hidden ones.
  32675. If the index is out-of-range, it'll return 0.
  32676. */
  32677. int getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw();
  32678. /** Returns the rectangle containing of one of the columns.
  32679. The index is an index from 0 to the number of columns that are currently visible (hidden
  32680. ones are not counted). It returns a rectangle showing the position of the column relative
  32681. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  32682. */
  32683. const Rectangle getColumnPosition (const int index) const throw();
  32684. /** Finds the column ID at a given x-position in the component.
  32685. If there is a column at this point this returns its ID, or if not, it will return 0.
  32686. */
  32687. int getColumnIdAtX (const int xToFind) const throw();
  32688. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  32689. entire width of the component.
  32690. By default this is disabled. Turning it on also means that when resizing a column, those
  32691. on the right will be squashed to fit.
  32692. */
  32693. void setStretchToFitActive (const bool shouldStretchToFit);
  32694. /** Returns true if stretch-to-fit has been enabled.
  32695. @see setStretchToFitActive
  32696. */
  32697. bool isStretchToFitActive() const throw();
  32698. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  32699. specified width, keeping their relative proportions the same.
  32700. If the minimum widths of the columns are too wide to fit into this space, it may
  32701. actually end up wider.
  32702. */
  32703. void resizeAllColumnsToFit (int targetTotalWidth);
  32704. /** Enables or disables the pop-up menu.
  32705. The default menu allows the user to show or hide columns. You can add custom
  32706. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  32707. By default the menu is enabled.
  32708. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  32709. */
  32710. void setPopupMenuActive (const bool hasMenu);
  32711. /** Returns true if the pop-up menu is enabled.
  32712. @see setPopupMenuActive
  32713. */
  32714. bool isPopupMenuActive() const throw();
  32715. /** Returns a string that encapsulates the table's current layout.
  32716. This can be restored later using restoreFromString(). It saves the order of
  32717. the columns, the currently-sorted column, and the widths.
  32718. @see restoreFromString
  32719. */
  32720. const String toString() const;
  32721. /** Restores the state of the table, based on a string previously created with
  32722. toString().
  32723. @see toString
  32724. */
  32725. void restoreFromString (const String& storedVersion);
  32726. /** Adds a listener to be informed about things that happen to the header. */
  32727. void addListener (TableHeaderListener* const newListener) throw();
  32728. /** Removes a previously-registered listener. */
  32729. void removeListener (TableHeaderListener* const listenerToRemove) throw();
  32730. /** This can be overridden to handle a mouse-click on one of the column headers.
  32731. The default implementation will use this click to call getSortColumnId() and
  32732. change the sort order.
  32733. */
  32734. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  32735. /** This can be overridden to add custom items to the pop-up menu.
  32736. If you override this, you should call the superclass's method to add its
  32737. column show/hide items, if you want them on the menu as well.
  32738. Then to handle the result, override reactToMenuItem().
  32739. @see reactToMenuItem
  32740. */
  32741. virtual void addMenuItems (PopupMenu& menu, const int columnIdClicked);
  32742. /** Override this to handle any custom items that you have added to the
  32743. pop-up menu with an addMenuItems() override.
  32744. If the menuReturnId isn't one of your own custom menu items, you'll need to
  32745. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  32746. handle the items that it had added.
  32747. @see addMenuItems
  32748. */
  32749. virtual void reactToMenuItem (const int menuReturnId, const int columnIdClicked);
  32750. /** @internal */
  32751. void paint (Graphics& g);
  32752. /** @internal */
  32753. void resized();
  32754. /** @internal */
  32755. void mouseMove (const MouseEvent&);
  32756. /** @internal */
  32757. void mouseEnter (const MouseEvent&);
  32758. /** @internal */
  32759. void mouseExit (const MouseEvent&);
  32760. /** @internal */
  32761. void mouseDown (const MouseEvent&);
  32762. /** @internal */
  32763. void mouseDrag (const MouseEvent&);
  32764. /** @internal */
  32765. void mouseUp (const MouseEvent&);
  32766. /** @internal */
  32767. const MouseCursor getMouseCursor();
  32768. /** Can be overridden for more control over the pop-up menu behaviour. */
  32769. virtual void showColumnChooserMenu (const int columnIdClicked);
  32770. juce_UseDebuggingNewOperator
  32771. private:
  32772. struct ColumnInfo
  32773. {
  32774. String name;
  32775. int id, propertyFlags, width, minimumWidth, maximumWidth;
  32776. double lastDeliberateWidth;
  32777. bool isVisible() const throw();
  32778. };
  32779. OwnedArray <ColumnInfo> columns;
  32780. Array <TableHeaderListener*> listeners;
  32781. ScopedPointer <Component> dragOverlayComp;
  32782. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  32783. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  32784. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  32785. ColumnInfo* getInfoForId (const int columnId) const throw();
  32786. int visibleIndexToTotalIndex (const int visibleIndex) const throw();
  32787. void sendColumnsChanged();
  32788. void handleAsyncUpdate();
  32789. void beginDrag (const MouseEvent&);
  32790. void endDrag (const int finalIndex);
  32791. int getResizeDraggerAt (const int mouseX) const throw();
  32792. void updateColumnUnderMouse (int x, int y);
  32793. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  32794. TableHeaderComponent (const TableHeaderComponent&);
  32795. const TableHeaderComponent operator= (const TableHeaderComponent&);
  32796. };
  32797. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  32798. /********* End of inlined file: juce_TableHeaderComponent.h *********/
  32799. #endif
  32800. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  32801. /********* Start of inlined file: juce_TableListBox.h *********/
  32802. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  32803. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  32804. /**
  32805. One of these is used by a TableListBox as the data model for the table's contents.
  32806. The virtual methods that you override in this class take care of drawing the
  32807. table cells, and reacting to events.
  32808. @see TableListBox
  32809. */
  32810. class JUCE_API TableListBoxModel
  32811. {
  32812. public:
  32813. TableListBoxModel() {}
  32814. /** Destructor. */
  32815. virtual ~TableListBoxModel() {}
  32816. /** This must return the number of rows currently in the table.
  32817. If the number of rows changes, you must call TableListBox::updateContent() to
  32818. cause it to refresh the list.
  32819. */
  32820. virtual int getNumRows() = 0;
  32821. /** This must draw the background behind one of the rows in the table.
  32822. The graphics context has its origin at the row's top-left, and your method
  32823. should fill the area specified by the width and height parameters.
  32824. */
  32825. virtual void paintRowBackground (Graphics& g,
  32826. int rowNumber,
  32827. int width, int height,
  32828. bool rowIsSelected) = 0;
  32829. /** This must draw one of the cells.
  32830. The graphics context's origin will already be set to the top-left of the cell,
  32831. whose size is specified by (width, height).
  32832. */
  32833. virtual void paintCell (Graphics& g,
  32834. int rowNumber,
  32835. int columnId,
  32836. int width, int height,
  32837. bool rowIsSelected) = 0;
  32838. /** This is used to create or update a custom component to go in a cell.
  32839. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  32840. and handle mouse clicks with cellClicked().
  32841. This method will be called whenever a custom component might need to be updated - e.g.
  32842. when the table is changed, or TableListBox::updateContent() is called.
  32843. If you don't need a custom component for the specified cell, then return 0.
  32844. If you do want a custom component, and the existingComponentToUpdate is null, then
  32845. this method must create a new component suitable for the cell, and return it.
  32846. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  32847. by this method. In this case, the method must either update it to make sure it's correctly representing
  32848. the given cell (which may be different from the one that the component was created for), or it can
  32849. delete this component and return a new one.
  32850. */
  32851. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  32852. Component* existingComponentToUpdate);
  32853. /** This callback is made when the user clicks on one of the cells in the table.
  32854. The mouse event's coordinates will be relative to the entire table row.
  32855. @see cellDoubleClicked, backgroundClicked
  32856. */
  32857. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  32858. /** This callback is made when the user clicks on one of the cells in the table.
  32859. The mouse event's coordinates will be relative to the entire table row.
  32860. @see cellClicked, backgroundClicked
  32861. */
  32862. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  32863. /** This can be overridden to react to the user double-clicking on a part of the list where
  32864. there are no rows.
  32865. @see cellClicked
  32866. */
  32867. virtual void backgroundClicked();
  32868. /** This callback is made when the table's sort order is changed.
  32869. This could be because the user has clicked a column header, or because the
  32870. TableHeaderComponent::setSortColumnId() method was called.
  32871. If you implement this, your method should re-sort the table using the given
  32872. column as the key.
  32873. */
  32874. virtual void sortOrderChanged (int newSortColumnId, const bool isForwards);
  32875. /** Returns the best width for one of the columns.
  32876. If you implement this method, you should measure the width of all the items
  32877. in this column, and return the best size.
  32878. Returning 0 means that the column shouldn't be changed.
  32879. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  32880. */
  32881. virtual int getColumnAutoSizeWidth (int columnId);
  32882. /** Returns a tooltip for a particular cell in the table.
  32883. */
  32884. virtual const String getCellTooltip (int rowNumber, int columnId);
  32885. /** Override this to be informed when rows are selected or deselected.
  32886. @see ListBox::selectedRowsChanged()
  32887. */
  32888. virtual void selectedRowsChanged (int lastRowSelected);
  32889. /** Override this to be informed when the delete key is pressed.
  32890. @see ListBox::deleteKeyPressed()
  32891. */
  32892. virtual void deleteKeyPressed (int lastRowSelected);
  32893. /** Override this to be informed when the return key is pressed.
  32894. @see ListBox::returnKeyPressed()
  32895. */
  32896. virtual void returnKeyPressed (int lastRowSelected);
  32897. /** Override this to be informed when the list is scrolled.
  32898. This might be caused by the user moving the scrollbar, or by programmatic changes
  32899. to the list position.
  32900. */
  32901. virtual void listWasScrolled();
  32902. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  32903. If this returns a non-empty name then when the user drags a row, the table will try to
  32904. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  32905. drag-and-drop operation, using this string as the source description, and the listbox
  32906. itself as the source component.
  32907. @see DragAndDropContainer::startDragging
  32908. */
  32909. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  32910. };
  32911. /**
  32912. A table of cells, using a TableHeaderComponent as its header.
  32913. This component makes it easy to create a table by providing a TableListBoxModel as
  32914. the data source.
  32915. @see TableListBoxModel, TableHeaderComponent
  32916. */
  32917. class JUCE_API TableListBox : public ListBox,
  32918. private ListBoxModel,
  32919. private TableHeaderListener
  32920. {
  32921. public:
  32922. /** Creates a TableListBox.
  32923. The model pointer passed-in can be null, in which case you can set it later
  32924. with setModel().
  32925. */
  32926. TableListBox (const String& componentName,
  32927. TableListBoxModel* const model);
  32928. /** Destructor. */
  32929. ~TableListBox();
  32930. /** Changes the TableListBoxModel that is being used for this table.
  32931. */
  32932. void setModel (TableListBoxModel* const newModel);
  32933. /** Returns the model currently in use. */
  32934. TableListBoxModel* getModel() const throw() { return model; }
  32935. /** Returns the header component being used in this table. */
  32936. TableHeaderComponent* getHeader() const throw() { return header; }
  32937. /** Changes the height of the table header component.
  32938. @see getHeaderHeight
  32939. */
  32940. void setHeaderHeight (const int newHeight);
  32941. /** Returns the height of the table header.
  32942. @see setHeaderHeight
  32943. */
  32944. int getHeaderHeight() const throw();
  32945. /** Resizes a column to fit its contents.
  32946. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  32947. and applies that to the column.
  32948. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  32949. */
  32950. void autoSizeColumn (const int columnId);
  32951. /** Calls autoSizeColumn() for all columns in the table. */
  32952. void autoSizeAllColumns();
  32953. /** Enables or disables the auto size options on the popup menu.
  32954. By default, these are enabled.
  32955. */
  32956. void setAutoSizeMenuOptionShown (const bool shouldBeShown);
  32957. /** True if the auto-size options should be shown on the menu.
  32958. @see setAutoSizeMenuOptionsShown
  32959. */
  32960. bool isAutoSizeMenuOptionShown() const throw();
  32961. /** Returns the position of one of the cells in the table.
  32962. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  32963. the table component's top-left. The row number isn't checked to see if it's
  32964. in-range, but the column ID must exist or this will return an empty rectangle.
  32965. If relativeToComponentTopLeft is false, the co-ords are relative to the
  32966. top-left of the table's top-left cell.
  32967. */
  32968. const Rectangle getCellPosition (const int columnId,
  32969. const int rowNumber,
  32970. const bool relativeToComponentTopLeft) const;
  32971. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  32972. @see ListBox::scrollToEnsureRowIsOnscreen
  32973. */
  32974. void scrollToEnsureColumnIsOnscreen (const int columnId);
  32975. /** @internal */
  32976. int getNumRows();
  32977. /** @internal */
  32978. void paintListBoxItem (int, Graphics&, int, int, bool);
  32979. /** @internal */
  32980. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  32981. /** @internal */
  32982. void selectedRowsChanged (int lastRowSelected);
  32983. /** @internal */
  32984. void deleteKeyPressed (int currentSelectedRow);
  32985. /** @internal */
  32986. void returnKeyPressed (int currentSelectedRow);
  32987. /** @internal */
  32988. void backgroundClicked();
  32989. /** @internal */
  32990. void listWasScrolled();
  32991. /** @internal */
  32992. void tableColumnsChanged (TableHeaderComponent*);
  32993. /** @internal */
  32994. void tableColumnsResized (TableHeaderComponent*);
  32995. /** @internal */
  32996. void tableSortOrderChanged (TableHeaderComponent*);
  32997. /** @internal */
  32998. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  32999. /** @internal */
  33000. void resized();
  33001. juce_UseDebuggingNewOperator
  33002. private:
  33003. TableHeaderComponent* header;
  33004. TableListBoxModel* model;
  33005. int columnIdNowBeingDragged;
  33006. bool autoSizeOptionsShown;
  33007. void updateColumnComponents() const;
  33008. TableListBox (const TableListBox&);
  33009. const TableListBox& operator= (const TableListBox&);
  33010. };
  33011. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  33012. /********* End of inlined file: juce_TableListBox.h *********/
  33013. #endif
  33014. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  33015. #endif
  33016. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  33017. #endif
  33018. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33019. #endif
  33020. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33021. /********* Start of inlined file: juce_ToolbarItemFactory.h *********/
  33022. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33023. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33024. /**
  33025. A factory object which can create ToolbarItemComponent objects.
  33026. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  33027. that it can create.
  33028. Each type of item is identified by a unique ID, and multiple instances of an
  33029. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  33030. bars).
  33031. @see Toolbar, ToolbarItemComponent, ToolbarButton
  33032. */
  33033. class JUCE_API ToolbarItemFactory
  33034. {
  33035. public:
  33036. ToolbarItemFactory();
  33037. /** Destructor. */
  33038. virtual ~ToolbarItemFactory();
  33039. /** A set of reserved item ID values, used for the built-in item types.
  33040. */
  33041. enum SpecialItemIds
  33042. {
  33043. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  33044. can be placed between sets of items to break them into groups. */
  33045. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  33046. items.*/
  33047. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  33048. either side of it, filling any available space. */
  33049. };
  33050. /** Must return a list of the IDs for all the item types that this factory can create.
  33051. The ids should be added to the array that is passed-in.
  33052. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  33053. and the predefined IDs in the SpecialItemIds enum.
  33054. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  33055. to this list if you want your toolbar to be able to contain those items.
  33056. The list returned here is used by the ToolbarItemPalette class to obtain its list
  33057. of available items, and their order on the palette will reflect the order in which
  33058. they appear on this list.
  33059. @see ToolbarItemPalette
  33060. */
  33061. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  33062. /** Must return the set of items that should be added to a toolbar as its default set.
  33063. This method is used by Toolbar::addDefaultItems() to determine which items to
  33064. create.
  33065. The items that your method adds to the array that is passed-in will be added to the
  33066. toolbar in the same order. Items can appear in the list more than once.
  33067. */
  33068. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  33069. /** Must create an instance of one of the items that the factory lists in its
  33070. getAllToolbarItemIds() method.
  33071. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  33072. method, except for the built-in item types from the SpecialItemIds enum, which
  33073. are created internally by the toolbar code.
  33074. Try not to keep a pointer to the object that is returned, as it will be deleted
  33075. automatically by the toolbar, and remember that multiple instances of the same
  33076. item type are likely to exist at the same time.
  33077. */
  33078. virtual ToolbarItemComponent* createItem (const int itemId) = 0;
  33079. };
  33080. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  33081. /********* End of inlined file: juce_ToolbarItemFactory.h *********/
  33082. #endif
  33083. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33084. /********* Start of inlined file: juce_ToolbarItemPalette.h *********/
  33085. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33086. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33087. /**
  33088. A component containing a list of toolbar items, which the user can drag onto
  33089. a toolbar to add them.
  33090. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  33091. which automatically shows one of these in a dialog box with lots of extra controls.
  33092. @see Toolbar
  33093. */
  33094. class JUCE_API ToolbarItemPalette : public Component,
  33095. public DragAndDropContainer
  33096. {
  33097. public:
  33098. /** Creates a palette of items for a given factory, with the aim of adding them
  33099. to the specified toolbar.
  33100. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  33101. set of items that are shown in this palette.
  33102. The toolbar and factory must not be deleted while this object exists.
  33103. */
  33104. ToolbarItemPalette (ToolbarItemFactory& factory,
  33105. Toolbar* const toolbar);
  33106. /** Destructor. */
  33107. ~ToolbarItemPalette();
  33108. /** @internal */
  33109. void resized();
  33110. juce_UseDebuggingNewOperator
  33111. private:
  33112. ToolbarItemFactory& factory;
  33113. Toolbar* toolbar;
  33114. Viewport* viewport;
  33115. friend class Toolbar;
  33116. void replaceComponent (ToolbarItemComponent* const comp);
  33117. ToolbarItemPalette (const ToolbarItemPalette&);
  33118. const ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  33119. };
  33120. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  33121. /********* End of inlined file: juce_ToolbarItemPalette.h *********/
  33122. #endif
  33123. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  33124. /********* Start of inlined file: juce_TreeView.h *********/
  33125. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  33126. #define __JUCE_TREEVIEW_JUCEHEADER__
  33127. /********* Start of inlined file: juce_FileDragAndDropTarget.h *********/
  33128. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33129. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33130. /**
  33131. Components derived from this class can have files dropped onto them by an external application.
  33132. @see DragAndDropContainer
  33133. */
  33134. class JUCE_API FileDragAndDropTarget
  33135. {
  33136. public:
  33137. /** Destructor. */
  33138. virtual ~FileDragAndDropTarget() {}
  33139. /** Callback to check whether this target is interested in the set of files being offered.
  33140. Note that this will be called repeatedly when the user is dragging the mouse around over your
  33141. component, so don't do anything time-consuming in here, like opening the files to have a look
  33142. inside them!
  33143. @param files the set of (absolute) pathnames of the files that the user is dragging
  33144. @returns true if this component wants to receive the other callbacks regarging this
  33145. type of object; if it returns false, no other callbacks will be made.
  33146. */
  33147. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  33148. /** Callback to indicate that some files are being dragged over this component.
  33149. This gets called when the user moves the mouse into this component while dragging.
  33150. Use this callback as a trigger to make your component repaint itself to give the
  33151. user feedback about whether the files can be dropped here or not.
  33152. @param files the set of (absolute) pathnames of the files that the user is dragging
  33153. @param x the mouse x position, relative to this component
  33154. @param y the mouse y position, relative to this component
  33155. */
  33156. virtual void fileDragEnter (const StringArray& files, int x, int y);
  33157. /** Callback to indicate that the user is dragging some files over this component.
  33158. This gets called when the user moves the mouse over this component while dragging.
  33159. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  33160. this lets you know what happens in-between.
  33161. @param files the set of (absolute) pathnames of the files that the user is dragging
  33162. @param x the mouse x position, relative to this component
  33163. @param y the mouse y position, relative to this component
  33164. */
  33165. virtual void fileDragMove (const StringArray& files, int x, int y);
  33166. /** Callback to indicate that the mouse has moved away from this component.
  33167. This gets called when the user moves the mouse out of this component while dragging
  33168. the files.
  33169. If you've used fileDragEnter() to repaint your component and give feedback, use this
  33170. as a signal to repaint it in its normal state.
  33171. @param files the set of (absolute) pathnames of the files that the user is dragging
  33172. */
  33173. virtual void fileDragExit (const StringArray& files);
  33174. /** Callback to indicate that the user has dropped the files onto this component.
  33175. When the user drops the files, this get called, and you can use the files in whatever
  33176. way is appropriate.
  33177. Note that after this is called, the fileDragExit method may not be called, so you should
  33178. clean up in here if there's anything you need to do when the drag finishes.
  33179. @param files the set of (absolute) pathnames of the files that the user is dragging
  33180. @param x the mouse x position, relative to this component
  33181. @param y the mouse y position, relative to this component
  33182. */
  33183. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  33184. };
  33185. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  33186. /********* End of inlined file: juce_FileDragAndDropTarget.h *********/
  33187. class TreeView;
  33188. /**
  33189. An item in a treeview.
  33190. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  33191. own sub-items.
  33192. To implement an item that contains sub-items, override the itemOpennessChanged()
  33193. method so that when it is opened, it adds the new sub-items to itself using the
  33194. addSubItem method. Depending on the nature of the item it might choose to only
  33195. do this the first time it's opened, or it might want to refresh itself each time.
  33196. It also has the option of deleting its sub-items when it is closed, or leaving them
  33197. in place.
  33198. */
  33199. class JUCE_API TreeViewItem
  33200. {
  33201. public:
  33202. /** Constructor. */
  33203. TreeViewItem();
  33204. /** Destructor. */
  33205. virtual ~TreeViewItem();
  33206. /** Returns the number of sub-items that have been added to this item.
  33207. Note that this doesn't mean much if the node isn't open.
  33208. @see getSubItem, mightContainSubItems, addSubItem
  33209. */
  33210. int getNumSubItems() const throw();
  33211. /** Returns one of the item's sub-items.
  33212. Remember that the object returned might get deleted at any time when its parent
  33213. item is closed or refreshed, depending on the nature of the items you're using.
  33214. @see getNumSubItems
  33215. */
  33216. TreeViewItem* getSubItem (const int index) const throw();
  33217. /** Removes any sub-items. */
  33218. void clearSubItems();
  33219. /** Adds a sub-item.
  33220. @param newItem the object to add to the item's sub-item list. Once added, these can be
  33221. found using getSubItem(). When the items are later removed with
  33222. removeSubItem() (or when this item is deleted), they will be deleted.
  33223. @param insertPosition the index which the new item should have when it's added. If this
  33224. value is less than 0, the item will be added to the end of the list.
  33225. */
  33226. void addSubItem (TreeViewItem* const newItem,
  33227. const int insertPosition = -1);
  33228. /** Removes one of the sub-items.
  33229. @param index the item to remove
  33230. @param deleteItem if true, the item that is removed will also be deleted.
  33231. */
  33232. void removeSubItem (const int index,
  33233. const bool deleteItem = true);
  33234. /** Returns the TreeView to which this item belongs. */
  33235. TreeView* getOwnerView() const throw() { return ownerView; }
  33236. /** Returns the item within which this item is contained. */
  33237. TreeViewItem* getParentItem() const throw() { return parentItem; }
  33238. /** True if this item is currently open in the treeview. */
  33239. bool isOpen() const throw();
  33240. /** Opens or closes the item.
  33241. When opened or closed, the item's itemOpennessChanged() method will be called,
  33242. and a subclass should use this callback to create and add any sub-items that
  33243. it needs to.
  33244. @see itemOpennessChanged, mightContainSubItems
  33245. */
  33246. void setOpen (const bool shouldBeOpen);
  33247. /** True if this item is currently selected.
  33248. Use this when painting the node, to decide whether to draw it as selected or not.
  33249. */
  33250. bool isSelected() const throw();
  33251. /** Selects or deselects the item.
  33252. This will cause a callback to itemSelectionChanged()
  33253. */
  33254. void setSelected (const bool shouldBeSelected,
  33255. const bool deselectOtherItemsFirst);
  33256. /** Returns the rectangle that this item occupies.
  33257. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  33258. top-left of the TreeView comp, so this will depend on the scroll-position of
  33259. the tree. If false, it is relative to the top-left of the topmost item in the
  33260. tree (so this would be unaffected by scrolling the view).
  33261. */
  33262. const Rectangle getItemPosition (const bool relativeToTreeViewTopLeft) const throw();
  33263. /** Sends a signal to the treeview to make it refresh itself.
  33264. Call this if your items have changed and you want the tree to update to reflect
  33265. this.
  33266. */
  33267. void treeHasChanged() const throw();
  33268. /** Sends a repaint message to redraw just this item.
  33269. Note that you should only call this if you want to repaint a superficial change. If
  33270. you're altering the tree's nodes, you should instead call treeHasChanged().
  33271. */
  33272. void repaintItem() const;
  33273. /** Returns the row number of this item in the tree.
  33274. The row number of an item will change according to which items are open.
  33275. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  33276. */
  33277. int getRowNumberInTree() const throw();
  33278. /** Returns true if all the item's parent nodes are open.
  33279. This is useful to check whether the item might actually be visible or not.
  33280. */
  33281. bool areAllParentsOpen() const throw();
  33282. /** Changes whether lines are drawn to connect any sub-items to this item.
  33283. By default, line-drawing is turned on.
  33284. */
  33285. void setLinesDrawnForSubItems (const bool shouldDrawLines) throw();
  33286. /** Tells the tree whether this item can potentially be opened.
  33287. If your item could contain sub-items, this should return true; if it returns
  33288. false then the tree will not try to open the item. This determines whether or
  33289. not the item will be drawn with a 'plus' button next to it.
  33290. */
  33291. virtual bool mightContainSubItems() = 0;
  33292. /** Returns a string to uniquely identify this item.
  33293. If you're planning on using the TreeView::getOpennessState() method, then
  33294. these strings will be used to identify which nodes are open. The string
  33295. should be unique amongst the item's sibling items, but it's ok for there
  33296. to be duplicates at other levels of the tree.
  33297. If you're not going to store the state, then it's ok not to bother implementing
  33298. this method.
  33299. */
  33300. virtual const String getUniqueName() const;
  33301. /** Called when an item is opened or closed.
  33302. When setOpen() is called and the item has specified that it might
  33303. have sub-items with the mightContainSubItems() method, this method
  33304. is called to let the item create or manage its sub-items.
  33305. So when this is called with isNowOpen set to true (i.e. when the item is being
  33306. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  33307. refresh its sub-item list.
  33308. When this is called with isNowOpen set to false, the subclass might want
  33309. to use clearSubItems() to save on space, or it might choose to leave them,
  33310. depending on the nature of the tree.
  33311. You could also use this callback as a trigger to start a background process
  33312. which asynchronously creates sub-items and adds them, if that's more
  33313. appropriate for the task in hand.
  33314. @see mightContainSubItems
  33315. */
  33316. virtual void itemOpennessChanged (bool isNowOpen);
  33317. /** Must return the width required by this item.
  33318. If your item needs to have a particular width in pixels, return that value; if
  33319. you'd rather have it just fill whatever space is available in the treeview,
  33320. return -1.
  33321. If all your items return -1, no horizontal scrollbar will be shown, but if any
  33322. items have fixed widths and extend beyond the width of the treeview, a
  33323. scrollbar will appear.
  33324. Each item can be a different width, but if they change width, you should call
  33325. treeHasChanged() to update the tree.
  33326. */
  33327. virtual int getItemWidth() const { return -1; }
  33328. /** Must return the height required by this item.
  33329. This is the height in pixels that the item will take up. Items in the tree
  33330. can be different heights, but if they change height, you should call
  33331. treeHasChanged() to update the tree.
  33332. */
  33333. virtual int getItemHeight() const { return 20; }
  33334. /** You can override this method to return false if you don't want to allow the
  33335. user to select this item.
  33336. */
  33337. virtual bool canBeSelected() const { return true; }
  33338. /** Creates a component that will be used to represent this item.
  33339. You don't have to implement this method - if it returns 0 then no component
  33340. will be used for the item, and you can just draw it using the paintItem()
  33341. callback. But if you do return a component, it will be positioned in the
  33342. treeview so that it can be used to represent this item.
  33343. The component returned will be managed by the treeview, so always return
  33344. a new component, and don't keep a reference to it, as the treeview will
  33345. delete it later when it goes off the screen or is no longer needed. Also
  33346. bear in mind that if the component keeps a reference to the item that
  33347. created it, that item could be deleted before the component. Its position
  33348. and size will be completely managed by the tree, so don't attempt to move it
  33349. around.
  33350. Something you may want to do with your component is to give it a pointer to
  33351. the TreeView that created it. This is perfectly safe, and there's no danger
  33352. of it becoming a dangling pointer because the TreeView will always delete
  33353. the component before it is itself deleted.
  33354. As long as you stick to these rules you can return whatever kind of
  33355. component you like. It's most useful if you're doing things like drag-and-drop
  33356. of items, or want to use a Label component to edit item names, etc.
  33357. */
  33358. virtual Component* createItemComponent() { return 0; }
  33359. /** Draws the item's contents.
  33360. You can choose to either implement this method and draw each item, or you
  33361. can use createItemComponent() to create a component that will represent the
  33362. item.
  33363. If all you need in your tree is to be able to draw the items and detect when
  33364. the user selects or double-clicks one of them, it's probably enough to
  33365. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  33366. complicated interactions, you may need to use createItemComponent() instead.
  33367. @param g the graphics context to draw into
  33368. @param width the width of the area available for drawing
  33369. @param height the height of the area available for drawing
  33370. */
  33371. virtual void paintItem (Graphics& g, int width, int height);
  33372. /** Draws the item's open/close button.
  33373. If you don't implement this method, the default behaviour is to
  33374. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  33375. it for custom effects.
  33376. */
  33377. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  33378. /** Called when the user clicks on this item.
  33379. If you're using createItemComponent() to create a custom component for the
  33380. item, the mouse-clicks might not make it through to the treeview, but this
  33381. is how you find out about clicks when just drawing each item individually.
  33382. The associated mouse-event details are passed in, so you can find out about
  33383. which button, where it was, etc.
  33384. @see itemDoubleClicked
  33385. */
  33386. virtual void itemClicked (const MouseEvent& e);
  33387. /** Called when the user double-clicks on this item.
  33388. If you're using createItemComponent() to create a custom component for the
  33389. item, the mouse-clicks might not make it through to the treeview, but this
  33390. is how you find out about clicks when just drawing each item individually.
  33391. The associated mouse-event details are passed in, so you can find out about
  33392. which button, where it was, etc.
  33393. If not overridden, the base class method here will open or close the item as
  33394. if the 'plus' button had been clicked.
  33395. @see itemClicked
  33396. */
  33397. virtual void itemDoubleClicked (const MouseEvent& e);
  33398. /** Called when the item is selected or deselected.
  33399. Use this if you want to do something special when the item's selectedness
  33400. changes. By default it'll get repainted when this happens.
  33401. */
  33402. virtual void itemSelectionChanged (bool isNowSelected);
  33403. /** The item can return a tool tip string here if it wants to.
  33404. @see TooltipClient
  33405. */
  33406. virtual const String getTooltip();
  33407. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  33408. If this returns a non-empty name then when the user drags an item, the treeview will
  33409. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  33410. a drag-and-drop operation, using this string as the source description, with the treeview
  33411. itself as the source component.
  33412. If you need more complex drag-and-drop behaviour, you can use custom components for
  33413. the items, and use those to trigger the drag.
  33414. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  33415. isInterestedInFileDrag(), etc.
  33416. @see DragAndDropContainer::startDragging
  33417. */
  33418. virtual const String getDragSourceDescription();
  33419. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  33420. method and return true.
  33421. If you return true and allow some files to be dropped, you'll also need to implement the
  33422. filesDropped() method to do something with them.
  33423. Note that this will be called often, so make your implementation very quick! There's
  33424. certainly no time to try opening the files and having a think about what's inside them!
  33425. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  33426. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  33427. */
  33428. virtual bool isInterestedInFileDrag (const StringArray& files);
  33429. /** When files are dropped into this item, this callback is invoked.
  33430. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  33431. The insertIndex value indicates where in the list of sub-items the files were dropped.
  33432. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  33433. */
  33434. virtual void filesDropped (const StringArray& files, int insertIndex);
  33435. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  33436. If you implement this method, you'll also need to implement itemDropped() in order to handle
  33437. the items when they are dropped.
  33438. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  33439. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  33440. */
  33441. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  33442. /** When a things are dropped into this item, this callback is invoked.
  33443. For this to work, you need to have also implemented isInterestedInDragSource().
  33444. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  33445. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  33446. */
  33447. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  33448. /** Sets a flag to indicate that the item wants to be allowed
  33449. to draw all the way across to the left edge of the treeview.
  33450. By default this is false, which means that when the paintItem()
  33451. method is called, its graphics context is clipped to only allow
  33452. drawing within the item's rectangle. If this flag is set to true,
  33453. then the graphics context isn't clipped on its left side, so it
  33454. can draw all the way across to the left margin. Note that the
  33455. context will still have its origin in the same place though, so
  33456. the coordinates of anything to its left will be negative. It's
  33457. mostly useful if you want to draw a wider bar behind the
  33458. highlighted item.
  33459. */
  33460. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  33461. /** Saves the current state of open/closed nodes so it can be restored later.
  33462. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  33463. and records it as XML. To identify node objects it uses the
  33464. TreeViewItem::getUniqueName() method to create named paths. This
  33465. means that the same state of open/closed nodes can be restored to a
  33466. completely different instance of the tree, as long as it contains nodes
  33467. whose unique names are the same.
  33468. You'd normally want to use TreeView::getOpennessState() rather than call it
  33469. for a specific item, but this can be handy if you need to briefly save the state
  33470. for a section of the tree.
  33471. The caller is responsible for deleting the object that is returned.
  33472. @see TreeView::getOpennessState, restoreOpennessState
  33473. */
  33474. XmlElement* getOpennessState() const throw();
  33475. /** Restores the openness of this item and all its sub-items from a saved state.
  33476. See TreeView::restoreOpennessState for more details.
  33477. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  33478. for a specific item, but this can be handy if you need to briefly save the state
  33479. for a section of the tree.
  33480. @see TreeView::restoreOpennessState, getOpennessState
  33481. */
  33482. void restoreOpennessState (const XmlElement& xml) throw();
  33483. /** Returns the index of this item in its parent's sub-items. */
  33484. int getIndexInParent() const throw();
  33485. /** Returns true if this item is the last of its parent's sub-itens. */
  33486. bool isLastOfSiblings() const throw();
  33487. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  33488. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  33489. The string takes the form of a path, constructed from the getUniqueName() of this
  33490. item and all its parents, so these must all be correctly implemented for it to work.
  33491. @see TreeView::findItemFromIdentifierString, getUniqueName
  33492. */
  33493. const String getItemIdentifierString() const;
  33494. juce_UseDebuggingNewOperator
  33495. private:
  33496. TreeView* ownerView;
  33497. TreeViewItem* parentItem;
  33498. OwnedArray <TreeViewItem> subItems;
  33499. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  33500. int uid;
  33501. bool selected : 1;
  33502. bool redrawNeeded : 1;
  33503. bool drawLinesInside : 1;
  33504. bool drawsInLeftMargin : 1;
  33505. unsigned int openness : 2;
  33506. friend class TreeView;
  33507. friend class TreeViewContentComponent;
  33508. void updatePositions (int newY);
  33509. int getIndentX() const throw();
  33510. void setOwnerView (TreeView* const newOwner) throw();
  33511. void paintRecursively (Graphics& g, int width);
  33512. TreeViewItem* getTopLevelItem() throw();
  33513. TreeViewItem* findItemRecursively (int y) throw();
  33514. TreeViewItem* getDeepestOpenParentItem() throw();
  33515. int getNumRows() const throw();
  33516. TreeViewItem* getItemOnRow (int index) throw();
  33517. void deselectAllRecursively();
  33518. int countSelectedItemsRecursively() const throw();
  33519. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  33520. TreeViewItem* getNextVisibleItem (const bool recurse) const throw();
  33521. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  33522. TreeViewItem (const TreeViewItem&);
  33523. const TreeViewItem& operator= (const TreeViewItem&);
  33524. };
  33525. /**
  33526. A tree-view component.
  33527. Use one of these to hold and display a structure of TreeViewItem objects.
  33528. */
  33529. class JUCE_API TreeView : public Component,
  33530. public SettableTooltipClient,
  33531. public FileDragAndDropTarget,
  33532. public DragAndDropTarget,
  33533. private AsyncUpdater
  33534. {
  33535. public:
  33536. /** Creates an empty treeview.
  33537. Once you've got a treeview component, you'll need to give it something to
  33538. display, using the setRootItem() method.
  33539. */
  33540. TreeView (const String& componentName = String::empty);
  33541. /** Destructor. */
  33542. ~TreeView();
  33543. /** Sets the item that is displayed in the treeview.
  33544. A tree has a single root item which contains as many sub-items as it needs. If
  33545. you want the tree to contain a number of root items, you should still use a single
  33546. root item above these, but hide it using setRootItemVisible().
  33547. You can pass in 0 to this method to clear the tree and remove its current root item.
  33548. The object passed in will not be deleted by the treeview, it's up to the caller
  33549. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  33550. this item until you've removed it from the tree, either by calling setRootItem (0),
  33551. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  33552. to delete it.
  33553. */
  33554. void setRootItem (TreeViewItem* const newRootItem);
  33555. /** Returns the tree's root item.
  33556. This will be the last object passed to setRootItem(), or 0 if none has been set.
  33557. */
  33558. TreeViewItem* getRootItem() const throw() { return rootItem; }
  33559. /** This will remove and delete the current root item.
  33560. It's a convenient way of deleting the item and calling setRootItem (0).
  33561. */
  33562. void deleteRootItem();
  33563. /** Changes whether the tree's root item is shown or not.
  33564. If the root item is hidden, only its sub-items will be shown in the treeview - this
  33565. lets you make the tree look as if it's got many root items. If it's hidden, this call
  33566. will also make sure the root item is open (otherwise the treeview would look empty).
  33567. */
  33568. void setRootItemVisible (const bool shouldBeVisible);
  33569. /** Returns true if the root item is visible.
  33570. @see setRootItemVisible
  33571. */
  33572. bool isRootItemVisible() const throw() { return rootItemVisible; }
  33573. /** Sets whether items are open or closed by default.
  33574. Normally, items are closed until the user opens them, but you can use this
  33575. to make them default to being open until explicitly closed.
  33576. @see areItemsOpenByDefault
  33577. */
  33578. void setDefaultOpenness (const bool isOpenByDefault);
  33579. /** Returns true if the tree's items default to being open.
  33580. @see setDefaultOpenness
  33581. */
  33582. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  33583. /** This sets a flag to indicate that the tree can be used for multi-selection.
  33584. You can always select multiple items internally by calling the
  33585. TreeViewItem::setSelected() method, but this flag indicates whether the user
  33586. is allowed to multi-select by clicking on the tree.
  33587. By default it is disabled.
  33588. @see isMultiSelectEnabled
  33589. */
  33590. void setMultiSelectEnabled (const bool canMultiSelect);
  33591. /** Returns whether multi-select has been enabled for the tree.
  33592. @see setMultiSelectEnabled
  33593. */
  33594. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  33595. /** Sets a flag to indicate whether to hide the open/close buttons.
  33596. @see areOpenCloseButtonsVisible
  33597. */
  33598. void setOpenCloseButtonsVisible (const bool shouldBeVisible);
  33599. /** Returns whether open/close buttons are shown.
  33600. @see setOpenCloseButtonsVisible
  33601. */
  33602. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  33603. /** Deselects any items that are currently selected. */
  33604. void clearSelectedItems();
  33605. /** Returns the number of items that are currently selected.
  33606. @see getSelectedItem, clearSelectedItems
  33607. */
  33608. int getNumSelectedItems() const throw();
  33609. /** Returns one of the selected items in the tree.
  33610. @param index the index, 0 to (getNumSelectedItems() - 1)
  33611. */
  33612. TreeViewItem* getSelectedItem (const int index) const throw();
  33613. /** Returns the number of rows the tree is using.
  33614. This will depend on which items are open.
  33615. @see TreeViewItem::getRowNumberInTree()
  33616. */
  33617. int getNumRowsInTree() const;
  33618. /** Returns the item on a particular row of the tree.
  33619. If the index is out of range, this will return 0.
  33620. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  33621. */
  33622. TreeViewItem* getItemOnRow (int index) const;
  33623. /** Returns the item that contains a given y position.
  33624. The y is relative to the top of the TreeView component.
  33625. */
  33626. TreeViewItem* getItemAt (int yPosition) const throw();
  33627. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  33628. void scrollToKeepItemVisible (TreeViewItem* item);
  33629. /** Returns the treeview's Viewport object. */
  33630. Viewport* getViewport() const throw() { return viewport; }
  33631. /** Returns the number of pixels by which each nested level of the tree is indented.
  33632. @see setIndentSize
  33633. */
  33634. int getIndentSize() const throw() { return indentSize; }
  33635. /** Changes the distance by which each nested level of the tree is indented.
  33636. @see getIndentSize
  33637. */
  33638. void setIndentSize (const int newIndentSize);
  33639. /** Searches the tree for an item with the specified identifier.
  33640. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  33641. If no such item exists, this will return false. If the item is found, all of its items
  33642. will be automatically opened.
  33643. */
  33644. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  33645. /** Saves the current state of open/closed nodes so it can be restored later.
  33646. This takes a snapshot of which nodes have been explicitly opened or closed,
  33647. and records it as XML. To identify node objects it uses the
  33648. TreeViewItem::getUniqueName() method to create named paths. This
  33649. means that the same state of open/closed nodes can be restored to a
  33650. completely different instance of the tree, as long as it contains nodes
  33651. whose unique names are the same.
  33652. The caller is responsible for deleting the object that is returned.
  33653. @param alsoIncludeScrollPosition if this is true, the state will also
  33654. include information about where the
  33655. tree has been scrolled to vertically,
  33656. so this can also be restored
  33657. @see restoreOpennessState
  33658. */
  33659. XmlElement* getOpennessState (const bool alsoIncludeScrollPosition) const;
  33660. /** Restores a previously saved arrangement of open/closed nodes.
  33661. This will try to restore a snapshot of the tree's state that was created by
  33662. the getOpennessState() method. If any of the nodes named in the original
  33663. XML aren't present in this tree, they will be ignored.
  33664. @see getOpennessState
  33665. */
  33666. void restoreOpennessState (const XmlElement& newState);
  33667. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  33668. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33669. methods.
  33670. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33671. */
  33672. enum ColourIds
  33673. {
  33674. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  33675. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  33676. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  33677. };
  33678. /** @internal */
  33679. void paint (Graphics& g);
  33680. /** @internal */
  33681. void resized();
  33682. /** @internal */
  33683. bool keyPressed (const KeyPress& key);
  33684. /** @internal */
  33685. void colourChanged();
  33686. /** @internal */
  33687. void enablementChanged();
  33688. /** @internal */
  33689. bool isInterestedInFileDrag (const StringArray& files);
  33690. /** @internal */
  33691. void fileDragEnter (const StringArray& files, int x, int y);
  33692. /** @internal */
  33693. void fileDragMove (const StringArray& files, int x, int y);
  33694. /** @internal */
  33695. void fileDragExit (const StringArray& files);
  33696. /** @internal */
  33697. void filesDropped (const StringArray& files, int x, int y);
  33698. /** @internal */
  33699. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  33700. /** @internal */
  33701. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33702. /** @internal */
  33703. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33704. /** @internal */
  33705. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  33706. /** @internal */
  33707. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  33708. juce_UseDebuggingNewOperator
  33709. private:
  33710. friend class TreeViewItem;
  33711. friend class TreeViewContentComponent;
  33712. Viewport* viewport;
  33713. CriticalSection nodeAlterationLock;
  33714. TreeViewItem* rootItem;
  33715. Component* dragInsertPointHighlight;
  33716. Component* dragTargetGroupHighlight;
  33717. int indentSize;
  33718. bool defaultOpenness : 1;
  33719. bool needsRecalculating : 1;
  33720. bool rootItemVisible : 1;
  33721. bool multiSelectEnabled : 1;
  33722. bool openCloseButtonsVisible : 1;
  33723. void itemsChanged() throw();
  33724. void handleAsyncUpdate();
  33725. void moveSelectedRow (int delta);
  33726. void updateButtonUnderMouse (const MouseEvent& e);
  33727. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  33728. void hideDragHighlight() throw();
  33729. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  33730. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  33731. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  33732. const StringArray& files, const String& sourceDescription,
  33733. Component* sourceComponent) const throw();
  33734. TreeView (const TreeView&);
  33735. const TreeView& operator= (const TreeView&);
  33736. };
  33737. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  33738. /********* End of inlined file: juce_TreeView.h *********/
  33739. #endif
  33740. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  33741. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  33742. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  33743. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  33744. /********* Start of inlined file: juce_DirectoryContentsList.h *********/
  33745. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  33746. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  33747. /********* Start of inlined file: juce_FileFilter.h *********/
  33748. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  33749. #define __JUCE_FILEFILTER_JUCEHEADER__
  33750. /**
  33751. Interface for deciding which files are suitable for something.
  33752. For example, this is used by DirectoryContentsList to select which files
  33753. go into the list.
  33754. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  33755. */
  33756. class JUCE_API FileFilter
  33757. {
  33758. public:
  33759. /** Creates a filter with the given description.
  33760. The description can be returned later with the getDescription() method.
  33761. */
  33762. FileFilter (const String& filterDescription);
  33763. /** Destructor. */
  33764. virtual ~FileFilter();
  33765. /** Returns the description that the filter was created with. */
  33766. const String& getDescription() const throw();
  33767. /** Should return true if this file is suitable for inclusion in whatever context
  33768. the object is being used.
  33769. */
  33770. virtual bool isFileSuitable (const File& file) const = 0;
  33771. /** Should return true if this directory is suitable for inclusion in whatever context
  33772. the object is being used.
  33773. */
  33774. virtual bool isDirectorySuitable (const File& file) const = 0;
  33775. protected:
  33776. String description;
  33777. };
  33778. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  33779. /********* End of inlined file: juce_FileFilter.h *********/
  33780. /********* Start of inlined file: juce_Image.h *********/
  33781. #ifndef __JUCE_IMAGE_JUCEHEADER__
  33782. #define __JUCE_IMAGE_JUCEHEADER__
  33783. /**
  33784. Holds a fixed-size bitmap.
  33785. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  33786. To draw into an image, create a Graphics object for it.
  33787. e.g. @code
  33788. // create a transparent 500x500 image..
  33789. Image myImage (Image::RGB, 500, 500, true);
  33790. Graphics g (myImage);
  33791. g.setColour (Colours::red);
  33792. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  33793. @endcode
  33794. Other useful ways to create an image are with the ImageCache class, or the
  33795. ImageFileFormat, which provides a way to load common image files.
  33796. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  33797. */
  33798. class JUCE_API Image
  33799. {
  33800. public:
  33801. enum PixelFormat
  33802. {
  33803. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  33804. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  33805. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  33806. };
  33807. /** Creates an in-memory image with a specified size and format.
  33808. To create an image that can use native OS rendering methods, see createNativeImage().
  33809. @param format the number of colour channels in the image
  33810. @param imageWidth the desired width of the image, in pixels - this value must be
  33811. greater than zero (otherwise a width of 1 will be used)
  33812. @param imageHeight the desired width of the image, in pixels - this value must be
  33813. greater than zero (otherwise a height of 1 will be used)
  33814. @param clearImage if true, the image will initially be cleared to black or transparent
  33815. black. If false, the image may contain random data, and the
  33816. user will have to deal with this
  33817. */
  33818. Image (const PixelFormat format,
  33819. const int imageWidth,
  33820. const int imageHeight,
  33821. const bool clearImage);
  33822. /** Creates a copy of another image.
  33823. @see createCopy
  33824. */
  33825. Image (const Image& other);
  33826. /** Destructor. */
  33827. virtual ~Image();
  33828. /** Tries to create an image that is uses native drawing methods when you render
  33829. onto it.
  33830. On some platforms this will just return a normal software-based image.
  33831. */
  33832. static Image* createNativeImage (const PixelFormat format,
  33833. const int imageWidth,
  33834. const int imageHeight,
  33835. const bool clearImage);
  33836. /** Returns the image's width (in pixels). */
  33837. int getWidth() const throw() { return imageWidth; }
  33838. /** Returns the image's height (in pixels). */
  33839. int getHeight() const throw() { return imageHeight; }
  33840. /** Returns a rectangle with the same size as this image.
  33841. The rectangle is always at position (0, 0).
  33842. */
  33843. const Rectangle getBounds() const throw() { return Rectangle (0, 0, imageWidth, imageHeight); }
  33844. /** Returns the image's pixel format. */
  33845. PixelFormat getFormat() const throw() { return format; }
  33846. /** True if the image's format is ARGB. */
  33847. bool isARGB() const throw() { return format == ARGB; }
  33848. /** True if the image's format is RGB. */
  33849. bool isRGB() const throw() { return format == RGB; }
  33850. /** True if the image contains an alpha-channel. */
  33851. bool hasAlphaChannel() const throw() { return format != RGB; }
  33852. /** Clears a section of the image with a given colour.
  33853. This won't do any alpha-blending - it just sets all pixels in the image to
  33854. the given colour (which may be non-opaque if the image has an alpha channel).
  33855. */
  33856. virtual void clear (int x, int y, int w, int h,
  33857. const Colour& colourToClearTo = Colour (0x00000000));
  33858. /** Returns a new image that's a copy of this one.
  33859. A new size for the copied image can be specified, or values less than
  33860. zero can be passed-in to use the image's existing dimensions.
  33861. It's up to the caller to delete the image when no longer needed.
  33862. */
  33863. virtual Image* createCopy (int newWidth = -1,
  33864. int newHeight = -1,
  33865. const Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  33866. /** Returns a new single-channel image which is a copy of the alpha-channel of this image.
  33867. */
  33868. virtual Image* createCopyOfAlphaChannel() const;
  33869. /** Returns the colour of one of the pixels in the image.
  33870. If the co-ordinates given are beyond the image's boundaries, this will
  33871. return Colours::transparentBlack.
  33872. (0, 0) is the image's top-left corner.
  33873. @see getAlphaAt, setPixelAt, blendPixelAt
  33874. */
  33875. virtual const Colour getPixelAt (const int x, const int y) const;
  33876. /** Sets the colour of one of the image's pixels.
  33877. If the co-ordinates are beyond the image's boundaries, then nothing will
  33878. happen.
  33879. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  33880. just replace the existing pixel with the given one. The colour's opacity
  33881. will be ignored if this image doesn't have an alpha-channel.
  33882. (0, 0) is the image's top-left corner.
  33883. @see blendPixelAt
  33884. */
  33885. virtual void setPixelAt (const int x, const int y, const Colour& colour);
  33886. /** Changes the opacity of a pixel.
  33887. This only has an effect if the image has an alpha channel and if the
  33888. given co-ordinates are inside the image's boundary.
  33889. The multiplier must be in the range 0 to 1.0, and the current alpha
  33890. at the given co-ordinates will be multiplied by this value.
  33891. @see getAlphaAt, setPixelAt
  33892. */
  33893. virtual void multiplyAlphaAt (const int x, const int y, const float multiplier);
  33894. /** Changes the overall opacity of the image.
  33895. This will multiply the alpha value of each pixel in the image by the given
  33896. amount (limiting the resulting alpha values between 0 and 255). This allows
  33897. you to make an image more or less transparent.
  33898. If the image doesn't have an alpha channel, this won't have any effect.
  33899. */
  33900. virtual void multiplyAllAlphas (const float amountToMultiplyBy);
  33901. /** Changes all the colours to be shades of grey, based on their current luminosity.
  33902. */
  33903. virtual void desaturate();
  33904. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  33905. You should only use this class as a last resort - messing about with the internals of
  33906. an image is only recommended for people who really know what they're doing!
  33907. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  33908. hanging around while the image is being used elsewhere.
  33909. Depending on the way the image class is implemented, this may create a temporary buffer
  33910. which is copied back to the image when the object is deleted, or it may just get a pointer
  33911. directly into the image's raw data.
  33912. You can use the stride and data values in this class directly, but don't alter them!
  33913. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  33914. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  33915. */
  33916. class BitmapData
  33917. {
  33918. public:
  33919. BitmapData (Image& image, int x, int y, int w, int h, const bool needsToBeWritable) throw();
  33920. BitmapData (const Image& image, int x, int y, int w, int h) throw();
  33921. ~BitmapData() throw();
  33922. /** Returns a pointer to the start of a line in the image.
  33923. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  33924. sure it's not out-of-range.
  33925. */
  33926. inline uint8* getLinePointer (const int y) const throw() { return data + y * lineStride; }
  33927. /** Returns a pointer to a pixel in the image.
  33928. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  33929. not out-of-range.
  33930. */
  33931. inline uint8* getPixelPointer (const int x, const int y) const throw() { return data + y * lineStride + x * pixelStride; }
  33932. uint8* data;
  33933. int lineStride, pixelStride, width, height;
  33934. private:
  33935. BitmapData (const BitmapData&);
  33936. const BitmapData& operator= (const BitmapData&);
  33937. };
  33938. /** Copies some pixel values to a rectangle of the image.
  33939. The format of the pixel data must match that of the image itself, and the
  33940. rectangle supplied must be within the image's bounds.
  33941. */
  33942. virtual void setPixelData (int destX, int destY, int destW, int destH,
  33943. const uint8* sourcePixelData, int sourceLineStride);
  33944. /** Copies a section of the image to somewhere else within itself.
  33945. */
  33946. virtual void moveImageSection (int destX, int destY,
  33947. int sourceX, int sourceY,
  33948. int width, int height);
  33949. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  33950. of the image.
  33951. @param result the list that will have the area added to it
  33952. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  33953. above this level will be considered opaque
  33954. */
  33955. void createSolidAreaMask (RectangleList& result,
  33956. const float alphaThreshold = 0.5f) const;
  33957. juce_UseDebuggingNewOperator
  33958. /** Creates a context suitable for drawing onto this image.
  33959. Don't call this method directly! It's used internally by the Graphics class.
  33960. */
  33961. virtual LowLevelGraphicsContext* createLowLevelContext();
  33962. protected:
  33963. friend class BitmapData;
  33964. const PixelFormat format;
  33965. const int imageWidth, imageHeight;
  33966. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  33967. Image (const PixelFormat format,
  33968. const int imageWidth,
  33969. const int imageHeight);
  33970. int pixelStride, lineStride;
  33971. HeapBlock <uint8> imageDataAllocated;
  33972. uint8* imageData;
  33973. private:
  33974. const Image& operator= (const Image&);
  33975. };
  33976. #endif // __JUCE_IMAGE_JUCEHEADER__
  33977. /********* End of inlined file: juce_Image.h *********/
  33978. /**
  33979. A class to asynchronously scan for details about the files in a directory.
  33980. This keeps a list of files and some information about them, using a background
  33981. thread to scan for more files. As files are found, it broadcasts change messages
  33982. to tell any listeners.
  33983. @see FileListComponent, FileBrowserComponent
  33984. */
  33985. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  33986. public TimeSliceClient
  33987. {
  33988. public:
  33989. /** Creates a directory list.
  33990. To set the directory it should point to, use setDirectory(), which will
  33991. also start it scanning for files on the background thread.
  33992. When the background thread finds and adds new files to this list, the
  33993. ChangeBroadcaster class will send a change message, so you can register
  33994. listeners and update them when the list changes.
  33995. @param fileFilter an optional filter to select which files are
  33996. included in the list. If this is 0, then all files
  33997. and directories are included. Make sure that the
  33998. filter doesn't get deleted during the lifetime of this
  33999. object
  34000. @param threadToUse a thread object that this list can use
  34001. to scan for files as a background task. Make sure
  34002. that the thread you give it has been started, or you
  34003. won't get any files!
  34004. */
  34005. DirectoryContentsList (const FileFilter* const fileFilter,
  34006. TimeSliceThread& threadToUse);
  34007. /** Destructor. */
  34008. ~DirectoryContentsList();
  34009. /** Sets the directory to look in for files.
  34010. If the directory that's passed in is different to the current one, this will
  34011. also start the background thread scanning it for files.
  34012. */
  34013. void setDirectory (const File& directory,
  34014. const bool includeDirectories,
  34015. const bool includeFiles);
  34016. /** Returns the directory that's currently being used. */
  34017. const File& getDirectory() const throw();
  34018. /** Clears the list, and stops the thread scanning for files. */
  34019. void clear();
  34020. /** Clears the list and restarts scanning the directory for files. */
  34021. void refresh();
  34022. /** True if the background thread hasn't yet finished scanning for files. */
  34023. bool isStillLoading() const;
  34024. /** Tells the list whether or not to ignore hidden files.
  34025. By default these are ignored.
  34026. */
  34027. void setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles);
  34028. /** Returns true if hidden files are ignored.
  34029. @see setIgnoresHiddenFiles
  34030. */
  34031. bool ignoresHiddenFiles() const throw() { return ignoreHiddenFiles; }
  34032. /** Contains cached information about one of the files in a DirectoryContentsList.
  34033. */
  34034. struct FileInfo
  34035. {
  34036. /** The filename.
  34037. This isn't a full pathname, it's just the last part of the path, same as you'd
  34038. get from File::getFileName().
  34039. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  34040. */
  34041. String filename;
  34042. /** File size in bytes. */
  34043. int64 fileSize;
  34044. /** File modification time.
  34045. As supplied by File::getLastModificationTime().
  34046. */
  34047. Time modificationTime;
  34048. /** File creation time.
  34049. As supplied by File::getCreationTime().
  34050. */
  34051. Time creationTime;
  34052. /** True if the file is a directory. */
  34053. bool isDirectory;
  34054. /** True if the file is read-only. */
  34055. bool isReadOnly;
  34056. };
  34057. /** Returns the number of files currently available in the list.
  34058. The info about one of these files can be retrieved with getFileInfo() or
  34059. getFile().
  34060. Obviously as the background thread runs and scans the directory for files, this
  34061. number will change.
  34062. @see getFileInfo, getFile
  34063. */
  34064. int getNumFiles() const;
  34065. /** Returns the cached information about one of the files in the list.
  34066. If the index is in-range, this will return true and will copy the file's details
  34067. to the structure that is passed-in.
  34068. If it returns false, then the index wasn't in range, and the structure won't
  34069. be affected.
  34070. @see getNumFiles, getFile
  34071. */
  34072. bool getFileInfo (const int index,
  34073. FileInfo& resultInfo) const;
  34074. /** Returns one of the files in the list.
  34075. @param index should be less than getNumFiles(). If this is out-of-range, the
  34076. return value will be File::nonexistent
  34077. @see getNumFiles, getFileInfo
  34078. */
  34079. const File getFile (const int index) const;
  34080. /** Returns the file filter being used.
  34081. The filter is specified in the constructor.
  34082. */
  34083. const FileFilter* getFilter() const throw() { return fileFilter; }
  34084. /** @internal */
  34085. bool useTimeSlice();
  34086. /** @internal */
  34087. TimeSliceThread& getTimeSliceThread() throw() { return thread; }
  34088. /** @internal */
  34089. static int compareElements (const DirectoryContentsList::FileInfo* const first,
  34090. const DirectoryContentsList::FileInfo* const second) throw();
  34091. juce_UseDebuggingNewOperator
  34092. private:
  34093. File root;
  34094. const FileFilter* fileFilter;
  34095. TimeSliceThread& thread;
  34096. bool includeDirectories, includeFiles, ignoreHiddenFiles;
  34097. CriticalSection fileListLock;
  34098. OwnedArray <FileInfo> files;
  34099. void* volatile fileFindHandle;
  34100. bool volatile shouldStop;
  34101. void changed();
  34102. bool checkNextFile (bool& hasChanged);
  34103. bool addFile (const String& filename, const bool isDir, const bool isHidden,
  34104. const int64 fileSize, const Time& modTime,
  34105. const Time& creationTime, const bool isReadOnly);
  34106. DirectoryContentsList (const DirectoryContentsList&);
  34107. const DirectoryContentsList& operator= (const DirectoryContentsList&);
  34108. };
  34109. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  34110. /********* End of inlined file: juce_DirectoryContentsList.h *********/
  34111. /********* Start of inlined file: juce_FileBrowserListener.h *********/
  34112. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  34113. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  34114. /**
  34115. A listener for user selection events in a file browser.
  34116. This is used by a FileBrowserComponent or FileListComponent.
  34117. */
  34118. class JUCE_API FileBrowserListener
  34119. {
  34120. public:
  34121. /** Destructor. */
  34122. virtual ~FileBrowserListener();
  34123. /** Callback when the user selects a different file in the browser. */
  34124. virtual void selectionChanged() = 0;
  34125. /** Callback when the user clicks on a file in the browser. */
  34126. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  34127. /** Callback when the user double-clicks on a file in the browser. */
  34128. virtual void fileDoubleClicked (const File& file) = 0;
  34129. };
  34130. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  34131. /********* End of inlined file: juce_FileBrowserListener.h *********/
  34132. /**
  34133. A base class for components that display a list of the files in a directory.
  34134. @see DirectoryContentsList
  34135. */
  34136. class JUCE_API DirectoryContentsDisplayComponent
  34137. {
  34138. public:
  34139. /**
  34140. */
  34141. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  34142. /** Destructor. */
  34143. virtual ~DirectoryContentsDisplayComponent();
  34144. /** Returns the number of files the user has got selected.
  34145. @see getSelectedFile
  34146. */
  34147. virtual int getNumSelectedFiles() const = 0;
  34148. /** Returns one of the files that the user has currently selected.
  34149. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  34150. @see getNumSelectedFiles
  34151. */
  34152. virtual const File getSelectedFile (int index) const = 0;
  34153. /** Scrolls this view to the top. */
  34154. virtual void scrollToTop() = 0;
  34155. /** Adds a listener to be told when files are selected or clicked.
  34156. @see removeListener
  34157. */
  34158. void addListener (FileBrowserListener* const listener) throw();
  34159. /** Removes a listener.
  34160. @see addListener
  34161. */
  34162. void removeListener (FileBrowserListener* const listener) throw();
  34163. /** A set of colour IDs to use to change the colour of various aspects of the label.
  34164. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34165. methods.
  34166. Note that you can also use the constants from TextEditor::ColourIds to change the
  34167. colour of the text editor that is opened when a label is editable.
  34168. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34169. */
  34170. enum ColourIds
  34171. {
  34172. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  34173. textColourId = 0x1000541, /**< The colour for the text. */
  34174. };
  34175. /** @internal */
  34176. void sendSelectionChangeMessage();
  34177. /** @internal */
  34178. void sendDoubleClickMessage (const File& file);
  34179. /** @internal */
  34180. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  34181. juce_UseDebuggingNewOperator
  34182. protected:
  34183. DirectoryContentsList& fileList;
  34184. SortedSet <void*> listeners;
  34185. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  34186. const DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  34187. };
  34188. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  34189. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.h *********/
  34190. #endif
  34191. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  34192. #endif
  34193. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  34194. /********* Start of inlined file: juce_FileBrowserComponent.h *********/
  34195. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  34196. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  34197. /********* Start of inlined file: juce_FilePreviewComponent.h *********/
  34198. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  34199. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  34200. /**
  34201. Base class for components that live inside a file chooser dialog box and
  34202. show previews of the files that get selected.
  34203. One of these allows special extra information to be displayed for files
  34204. in a dialog box as the user selects them. Each time the current file or
  34205. directory is changed, the selectedFileChanged() method will be called
  34206. to allow it to update itself appropriately.
  34207. @see FileChooser, ImagePreviewComponent
  34208. */
  34209. class JUCE_API FilePreviewComponent : public Component
  34210. {
  34211. public:
  34212. /** Creates a FilePreviewComponent. */
  34213. FilePreviewComponent();
  34214. /** Destructor. */
  34215. ~FilePreviewComponent();
  34216. /** Called to indicate that the user's currently selected file has changed.
  34217. @param newSelectedFile the newly selected file or directory, which may be
  34218. File::nonexistent if none is selected.
  34219. */
  34220. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  34221. juce_UseDebuggingNewOperator
  34222. private:
  34223. FilePreviewComponent (const FilePreviewComponent&);
  34224. const FilePreviewComponent& operator= (const FilePreviewComponent&);
  34225. };
  34226. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  34227. /********* End of inlined file: juce_FilePreviewComponent.h *********/
  34228. /**
  34229. A component for browsing and selecting a file or directory to open or save.
  34230. This contains a FileListComponent and adds various boxes and controls for
  34231. navigating and selecting a file. It can work in different modes so that it can
  34232. be used for loading or saving a file, or for choosing a directory.
  34233. @see FileChooserDialogBox, FileChooser, FileListComponent
  34234. */
  34235. class JUCE_API FileBrowserComponent : public Component,
  34236. public ChangeBroadcaster,
  34237. private FileBrowserListener,
  34238. private TextEditorListener,
  34239. private ButtonListener,
  34240. private ComboBoxListener,
  34241. private FileFilter
  34242. {
  34243. public:
  34244. /** Various options for the browser.
  34245. A combination of these is passed into the FileBrowserComponent constructor.
  34246. */
  34247. enum FileChooserFlags
  34248. {
  34249. openMode = 1, /**< specifies that the component should allow the user to
  34250. choose an existing file with the intention of opening it. */
  34251. saveMode = 2, /**< specifies that the component should allow the user to specify
  34252. the name of a file that will be used to save something. */
  34253. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  34254. conjunction with canSelectDirectories). */
  34255. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  34256. conjuction with canSelectFiles). */
  34257. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  34258. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  34259. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  34260. };
  34261. /** Creates a FileBrowserComponent.
  34262. @param flags A combination of flags from the FileChooserFlags enumeration,
  34263. used to specify the component's behaviour. The flags must contain
  34264. either openMode or saveMode, and canSelectFiles and/or
  34265. canSelectDirectories.
  34266. @param initialFileOrDirectory The file or directory that should be selected when
  34267. the component begins. If this is File::nonexistent,
  34268. a default directory will be chosen.
  34269. @param fileFilter an optional filter to use to determine which files
  34270. are shown. If this is 0 then all files are displayed. Note
  34271. that a pointer is kept internally to this object, so
  34272. make sure that it is not deleted before the browser object
  34273. is deleted.
  34274. @param previewComp an optional preview component that will be used to
  34275. show previews of files that the user selects
  34276. */
  34277. FileBrowserComponent (int flags,
  34278. const File& initialFileOrDirectory,
  34279. const FileFilter* fileFilter,
  34280. FilePreviewComponent* previewComp);
  34281. /** Destructor. */
  34282. ~FileBrowserComponent();
  34283. /** Returns the number of files that the user has got selected.
  34284. If multiple select isn't active, this will only be 0 or 1. To get the complete
  34285. list of files they've chosen, pass an index to getCurrentFile().
  34286. */
  34287. int getNumSelectedFiles() const throw();
  34288. /** Returns one of the files that the user has chosen.
  34289. If the box has multi-select enabled, the index lets you specify which of the files
  34290. to get - see getNumSelectedFiles() to find out how many files were chosen.
  34291. @see getHighlightedFile
  34292. */
  34293. const File getSelectedFile (int index) const throw();
  34294. /** Returns true if the currently selected file(s) are usable.
  34295. This can be used to decide whether the user can press "ok" for the
  34296. current file. What it does depends on the mode, so for example in an "open"
  34297. mode, this only returns true if a file has been selected and if it exists.
  34298. In a "save" mode, a non-existent file would also be valid.
  34299. */
  34300. bool currentFileIsValid() const;
  34301. /** This returns the last item in the view that the user has highlighted.
  34302. This may be different from getCurrentFile(), which returns the value
  34303. that is shown in the filename box, and if there are multiple selections,
  34304. this will only return one of them.
  34305. @see getCurrentFile
  34306. */
  34307. const File getHighlightedFile() const throw();
  34308. /** Returns the directory whose contents are currently being shown in the listbox. */
  34309. const File getRoot() const;
  34310. /** Changes the directory that's being shown in the listbox. */
  34311. void setRoot (const File& newRootDirectory);
  34312. /** Equivalent to pressing the "up" button to browse the parent directory. */
  34313. void goUp();
  34314. /** Refreshes the directory that's currently being listed. */
  34315. void refresh();
  34316. /** Returns a verb to describe what should happen when the file is accepted.
  34317. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  34318. mode, it'll be "Save", etc.
  34319. */
  34320. virtual const String getActionVerb() const;
  34321. /** Returns true if the saveMode flag was set when this component was created.
  34322. */
  34323. bool isSaveMode() const throw();
  34324. /** Adds a listener to be told when the user selects and clicks on files.
  34325. @see removeListener
  34326. */
  34327. void addListener (FileBrowserListener* const listener) throw();
  34328. /** Removes a listener.
  34329. @see addListener
  34330. */
  34331. void removeListener (FileBrowserListener* const listener) throw();
  34332. /** @internal */
  34333. void resized();
  34334. /** @internal */
  34335. void buttonClicked (Button* b);
  34336. /** @internal */
  34337. void comboBoxChanged (ComboBox*);
  34338. /** @internal */
  34339. void textEditorTextChanged (TextEditor& editor);
  34340. /** @internal */
  34341. void textEditorReturnKeyPressed (TextEditor& editor);
  34342. /** @internal */
  34343. void textEditorEscapeKeyPressed (TextEditor& editor);
  34344. /** @internal */
  34345. void textEditorFocusLost (TextEditor& editor);
  34346. /** @internal */
  34347. bool keyPressed (const KeyPress& key);
  34348. /** @internal */
  34349. void selectionChanged();
  34350. /** @internal */
  34351. void fileClicked (const File& f, const MouseEvent& e);
  34352. /** @internal */
  34353. void fileDoubleClicked (const File& f);
  34354. /** @internal */
  34355. bool isFileSuitable (const File& file) const;
  34356. /** @internal */
  34357. bool isDirectorySuitable (const File&) const;
  34358. /** @internal */
  34359. FilePreviewComponent* getPreviewComponent() const throw();
  34360. juce_UseDebuggingNewOperator
  34361. protected:
  34362. virtual const BitArray getRoots (StringArray& rootNames, StringArray& rootPaths);
  34363. private:
  34364. ScopedPointer <DirectoryContentsList> fileList;
  34365. const FileFilter* fileFilter;
  34366. int flags;
  34367. File currentRoot;
  34368. OwnedArray <File> chosenFiles;
  34369. SortedSet <void*> listeners;
  34370. DirectoryContentsDisplayComponent* fileListComponent;
  34371. FilePreviewComponent* previewComp;
  34372. ComboBox* currentPathBox;
  34373. TextEditor* filenameBox;
  34374. Button* goUpButton;
  34375. TimeSliceThread thread;
  34376. void sendListenerChangeMessage();
  34377. bool isFileOrDirSuitable (const File& f) const;
  34378. FileBrowserComponent (const FileBrowserComponent&);
  34379. const FileBrowserComponent& operator= (const FileBrowserComponent&);
  34380. };
  34381. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  34382. /********* End of inlined file: juce_FileBrowserComponent.h *********/
  34383. #endif
  34384. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  34385. #endif
  34386. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  34387. /********* Start of inlined file: juce_FileChooser.h *********/
  34388. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  34389. #define __JUCE_FILECHOOSER_JUCEHEADER__
  34390. /**
  34391. Creates a dialog box to choose a file or directory to load or save.
  34392. To use a FileChooser:
  34393. - create one (as a local stack variable is the neatest way)
  34394. - call one of its browseFor.. methods
  34395. - if this returns true, the user has selected a file, so you can retrieve it
  34396. with the getResult() method.
  34397. e.g. @code
  34398. void loadMooseFile()
  34399. {
  34400. FileChooser myChooser ("Please select the moose you want to load...",
  34401. File::getSpecialLocation (File::userHomeDirectory),
  34402. "*.moose");
  34403. if (myChooser.browseForFileToOpen())
  34404. {
  34405. File mooseFile (myChooser.getResult());
  34406. loadMoose (mooseFile);
  34407. }
  34408. }
  34409. @endcode
  34410. */
  34411. class JUCE_API FileChooser
  34412. {
  34413. public:
  34414. /** Creates a FileChooser.
  34415. After creating one of these, use one of the browseFor... methods to display it.
  34416. @param dialogBoxTitle a text string to display in the dialog box to
  34417. tell the user what's going on
  34418. @param initialFileOrDirectory the file or directory that should be selected when
  34419. the dialog box opens. If this parameter is set to
  34420. File::nonexistent, a sensible default directory
  34421. will be used instead.
  34422. @param filePatternsAllowed a set of file patterns to specify which files can be
  34423. selected - each pattern should be separated by a
  34424. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  34425. empty string means that all files are allowed
  34426. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  34427. possible; if false, then a Juce-based browser dialog
  34428. box will always be used
  34429. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  34430. */
  34431. FileChooser (const String& dialogBoxTitle,
  34432. const File& initialFileOrDirectory = File::nonexistent,
  34433. const String& filePatternsAllowed = String::empty,
  34434. const bool useOSNativeDialogBox = true);
  34435. /** Destructor. */
  34436. ~FileChooser();
  34437. /** Shows a dialog box to choose a file to open.
  34438. This will display the dialog box modally, using an "open file" mode, so that
  34439. it won't allow non-existent files or directories to be chosen.
  34440. @param previewComponent an optional component to display inside the dialog
  34441. box to show special info about the files that the user
  34442. is browsing. The component will not be deleted by this
  34443. object, so the caller must take care of it.
  34444. @returns true if the user selected a file, in which case, use the getResult()
  34445. method to find out what it was. Returns false if they cancelled instead.
  34446. @see browseForFileToSave, browseForDirectory
  34447. */
  34448. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  34449. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  34450. The files that are returned can be obtained by calling getResults(). See
  34451. browseForFileToOpen() for more info about the behaviour of this method.
  34452. */
  34453. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  34454. /** Shows a dialog box to choose a file to save.
  34455. This will display the dialog box modally, using an "save file" mode, so it
  34456. will allow non-existent files to be chosen, but not directories.
  34457. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  34458. the user if they're sure they want to overwrite a file that already
  34459. exists
  34460. @returns true if the user chose a file and pressed 'ok', in which case, use
  34461. the getResult() method to find out what the file was. Returns false
  34462. if they cancelled instead.
  34463. @see browseForFileToOpen, browseForDirectory
  34464. */
  34465. bool browseForFileToSave (const bool warnAboutOverwritingExistingFiles);
  34466. /** Shows a dialog box to choose a directory.
  34467. This will display the dialog box modally, using an "open directory" mode, so it
  34468. will only allow directories to be returned, not files.
  34469. @returns true if the user chose a directory and pressed 'ok', in which case, use
  34470. the getResult() method to find out what they chose. Returns false
  34471. if they cancelled instead.
  34472. @see browseForFileToOpen, browseForFileToSave
  34473. */
  34474. bool browseForDirectory();
  34475. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  34476. The files that are returned can be obtained by calling getResults(). See
  34477. browseForFileToOpen() for more info about the behaviour of this method.
  34478. */
  34479. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  34480. /** Returns the last file that was chosen by one of the browseFor methods.
  34481. After calling the appropriate browseFor... method, this method lets you
  34482. find out what file or directory they chose.
  34483. Note that the file returned is only valid if the browse method returned true (i.e.
  34484. if the user pressed 'ok' rather than cancelling).
  34485. If you're using a multiple-file select, then use the getResults() method instead,
  34486. to obtain the list of all files chosen.
  34487. @see getResults
  34488. */
  34489. const File getResult() const;
  34490. /** Returns a list of all the files that were chosen during the last call to a
  34491. browse method.
  34492. This array may be empty if no files were chosen, or can contain multiple entries
  34493. if multiple files were chosen.
  34494. @see getResult
  34495. */
  34496. const OwnedArray <File>& getResults() const;
  34497. juce_UseDebuggingNewOperator
  34498. private:
  34499. String title, filters;
  34500. File startingFile;
  34501. OwnedArray <File> results;
  34502. bool useNativeDialogBox;
  34503. bool showDialog (const bool selectsDirectories,
  34504. const bool selectsFiles,
  34505. const bool isSave,
  34506. const bool warnAboutOverwritingExistingFiles,
  34507. const bool selectMultipleFiles,
  34508. FilePreviewComponent* const previewComponent);
  34509. static void showPlatformDialog (OwnedArray<File>& results,
  34510. const String& title,
  34511. const File& file,
  34512. const String& filters,
  34513. bool selectsDirectories,
  34514. bool selectsFiles,
  34515. bool isSave,
  34516. bool warnAboutOverwritingExistingFiles,
  34517. bool selectMultipleFiles,
  34518. FilePreviewComponent* previewComponent);
  34519. };
  34520. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  34521. /********* End of inlined file: juce_FileChooser.h *********/
  34522. #endif
  34523. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  34524. /********* Start of inlined file: juce_FileChooserDialogBox.h *********/
  34525. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  34526. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  34527. /********* Start of inlined file: juce_ResizableWindow.h *********/
  34528. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  34529. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  34530. /********* Start of inlined file: juce_TopLevelWindow.h *********/
  34531. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  34532. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  34533. /********* Start of inlined file: juce_DropShadower.h *********/
  34534. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  34535. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  34536. /**
  34537. Adds a drop-shadow to a component.
  34538. This object creates and manages a set of components which sit around a
  34539. component, creating a gaussian shadow around it. The components will track
  34540. the position of the component and if it's brought to the front they'll also
  34541. follow this.
  34542. For desktop windows you don't need to use this class directly - just
  34543. set the Component::windowHasDropShadow flag when calling
  34544. Component::addToDesktop(), and the system will create one of these if it's
  34545. needed (which it obviously isn't on the Mac, for example).
  34546. */
  34547. class JUCE_API DropShadower : public ComponentListener
  34548. {
  34549. public:
  34550. /** Creates a DropShadower.
  34551. @param alpha the opacity of the shadows, from 0 to 1.0
  34552. @param xOffset the horizontal displacement of the shadow, in pixels
  34553. @param yOffset the vertical displacement of the shadow, in pixels
  34554. @param blurRadius the radius of the blur to use for creating the shadow
  34555. */
  34556. DropShadower (const float alpha = 0.5f,
  34557. const int xOffset = 1,
  34558. const int yOffset = 5,
  34559. const float blurRadius = 10.0f);
  34560. /** Destructor. */
  34561. virtual ~DropShadower();
  34562. /** Attaches the DropShadower to the component you want to shadow. */
  34563. void setOwner (Component* componentToFollow);
  34564. /** @internal */
  34565. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  34566. /** @internal */
  34567. void componentBroughtToFront (Component& component);
  34568. /** @internal */
  34569. void componentChildrenChanged (Component& component);
  34570. /** @internal */
  34571. void componentParentHierarchyChanged (Component& component);
  34572. /** @internal */
  34573. void componentVisibilityChanged (Component& component);
  34574. juce_UseDebuggingNewOperator
  34575. private:
  34576. Component* owner;
  34577. int numShadows;
  34578. Component* shadowWindows[4];
  34579. Image* shadowImageSections[12];
  34580. const int shadowEdge, xOffset, yOffset;
  34581. const float alpha, blurRadius;
  34582. bool inDestructor, reentrant;
  34583. void updateShadows();
  34584. void setShadowImage (Image* const src,
  34585. const int num,
  34586. const int w, const int h,
  34587. const int sx, const int sy) throw();
  34588. void bringShadowWindowsToFront();
  34589. void deleteShadowWindows();
  34590. DropShadower (const DropShadower&);
  34591. const DropShadower& operator= (const DropShadower&);
  34592. };
  34593. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  34594. /********* End of inlined file: juce_DropShadower.h *********/
  34595. /**
  34596. A base class for top-level windows.
  34597. This class is used for components that are considered a major part of your
  34598. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  34599. etc. Things like menus that pop up briefly aren't derived from it.
  34600. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  34601. could itself be the child of another component.
  34602. The class manages a list of all instances of top-level windows that are in use,
  34603. and each one is also given the concept of being "active". The active window is
  34604. one that is actively being used by the user. This isn't quite the same as the
  34605. component with the keyboard focus, because there may be a popup menu or other
  34606. temporary window which gets keyboard focus while the active top level window is
  34607. unchanged.
  34608. A top-level window also has an optional drop-shadow.
  34609. @see ResizableWindow, DocumentWindow, DialogWindow
  34610. */
  34611. class JUCE_API TopLevelWindow : public Component
  34612. {
  34613. public:
  34614. /** Creates a TopLevelWindow.
  34615. @param name the name to give the component
  34616. @param addToDesktop if true, the window will be automatically added to the
  34617. desktop; if false, you can use it as a child component
  34618. */
  34619. TopLevelWindow (const String& name,
  34620. const bool addToDesktop);
  34621. /** Destructor. */
  34622. ~TopLevelWindow();
  34623. /** True if this is currently the TopLevelWindow that is actively being used.
  34624. This isn't quite the same as having keyboard focus, because the focus may be
  34625. on a child component or a temporary pop-up menu, etc, while this window is
  34626. still considered to be active.
  34627. @see activeWindowStatusChanged
  34628. */
  34629. bool isActiveWindow() const throw() { return windowIsActive_; }
  34630. /** This will set the bounds of the window so that it's centred in front of another
  34631. window.
  34632. If your app has a few windows open and want to pop up a dialog box for one of
  34633. them, you can use this to show it in front of the relevent parent window, which
  34634. is a bit neater than just having it appear in the middle of the screen.
  34635. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  34636. be used instead. If no window is focused, it'll just default to the middle of the
  34637. screen.
  34638. */
  34639. void centreAroundComponent (Component* componentToCentreAround,
  34640. const int width, const int height);
  34641. /** Turns the drop-shadow on and off. */
  34642. void setDropShadowEnabled (const bool useShadow);
  34643. /** Sets whether an OS-native title bar will be used, or a Juce one.
  34644. @see isUsingNativeTitleBar
  34645. */
  34646. void setUsingNativeTitleBar (const bool useNativeTitleBar);
  34647. /** Returns true if the window is currently using an OS-native title bar.
  34648. @see setUsingNativeTitleBar
  34649. */
  34650. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  34651. /** Returns the number of TopLevelWindow objects currently in use.
  34652. @see getTopLevelWindow
  34653. */
  34654. static int getNumTopLevelWindows() throw();
  34655. /** Returns one of the TopLevelWindow objects currently in use.
  34656. The index is 0 to (getNumTopLevelWindows() - 1).
  34657. */
  34658. static TopLevelWindow* getTopLevelWindow (const int index) throw();
  34659. /** Returns the currently-active top level window.
  34660. There might not be one, of course, so this can return 0.
  34661. */
  34662. static TopLevelWindow* getActiveTopLevelWindow() throw();
  34663. juce_UseDebuggingNewOperator
  34664. /** @internal */
  34665. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  34666. protected:
  34667. /** This callback happens when this window becomes active or inactive.
  34668. @see isActiveWindow
  34669. */
  34670. virtual void activeWindowStatusChanged();
  34671. /** @internal */
  34672. void focusOfChildComponentChanged (FocusChangeType cause);
  34673. /** @internal */
  34674. void parentHierarchyChanged();
  34675. /** @internal */
  34676. void visibilityChanged();
  34677. /** @internal */
  34678. virtual int getDesktopWindowStyleFlags() const;
  34679. /** @internal */
  34680. void recreateDesktopWindow();
  34681. private:
  34682. friend class TopLevelWindowManager;
  34683. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  34684. ScopedPointer <DropShadower> shadower;
  34685. void setWindowActive (const bool isNowActive) throw();
  34686. TopLevelWindow (const TopLevelWindow&);
  34687. const TopLevelWindow& operator= (const TopLevelWindow&);
  34688. };
  34689. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  34690. /********* End of inlined file: juce_TopLevelWindow.h *********/
  34691. /********* Start of inlined file: juce_ComponentDragger.h *********/
  34692. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34693. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34694. /********* Start of inlined file: juce_ComponentBoundsConstrainer.h *********/
  34695. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34696. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34697. /**
  34698. A class that imposes restrictions on a Component's size or position.
  34699. This is used by classes such as ResizableCornerComponent,
  34700. ResizableBorderComponent and ResizableWindow.
  34701. The base class can impose some basic size and position limits, but you can
  34702. also subclass this for custom uses.
  34703. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  34704. */
  34705. class JUCE_API ComponentBoundsConstrainer
  34706. {
  34707. public:
  34708. /** When first created, the object will not impose any restrictions on the components. */
  34709. ComponentBoundsConstrainer() throw();
  34710. /** Destructor. */
  34711. virtual ~ComponentBoundsConstrainer();
  34712. /** Imposes a minimum width limit. */
  34713. void setMinimumWidth (const int minimumWidth) throw();
  34714. /** Returns the current minimum width. */
  34715. int getMinimumWidth() const throw() { return minW; }
  34716. /** Imposes a maximum width limit. */
  34717. void setMaximumWidth (const int maximumWidth) throw();
  34718. /** Returns the current maximum width. */
  34719. int getMaximumWidth() const throw() { return maxW; }
  34720. /** Imposes a minimum height limit. */
  34721. void setMinimumHeight (const int minimumHeight) throw();
  34722. /** Returns the current minimum height. */
  34723. int getMinimumHeight() const throw() { return minH; }
  34724. /** Imposes a maximum height limit. */
  34725. void setMaximumHeight (const int maximumHeight) throw();
  34726. /** Returns the current maximum height. */
  34727. int getMaximumHeight() const throw() { return maxH; }
  34728. /** Imposes a minimum width and height limit. */
  34729. void setMinimumSize (const int minimumWidth,
  34730. const int minimumHeight) throw();
  34731. /** Imposes a maximum width and height limit. */
  34732. void setMaximumSize (const int maximumWidth,
  34733. const int maximumHeight) throw();
  34734. /** Set all the maximum and minimum dimensions. */
  34735. void setSizeLimits (const int minimumWidth,
  34736. const int minimumHeight,
  34737. const int maximumWidth,
  34738. const int maximumHeight) throw();
  34739. /** Sets the amount by which the component is allowed to go off-screen.
  34740. The values indicate how many pixels must remain on-screen when dragged off
  34741. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  34742. when the component goes off the top of the screen, its y-position will be
  34743. clipped so that there are always at least 10 pixels on-screen. In other words,
  34744. the lowest y-position it can take would be (10 - the component's height).
  34745. If you pass 0 or less for one of these amounts, the component is allowed
  34746. to move beyond that edge completely, with no restrictions at all.
  34747. If you pass a very large number (i.e. larger that the dimensions of the
  34748. component itself), then the component won't be allowed to overlap that
  34749. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  34750. the component will bump into the left side of the screen and go no further.
  34751. */
  34752. void setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  34753. const int minimumWhenOffTheLeft,
  34754. const int minimumWhenOffTheBottom,
  34755. const int minimumWhenOffTheRight) throw();
  34756. /** Specifies a width-to-height ratio that the resizer should always maintain.
  34757. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  34758. will always be maintained as this multiple of the height.
  34759. @see setResizeLimits
  34760. */
  34761. void setFixedAspectRatio (const double widthOverHeight) throw();
  34762. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  34763. If no aspect ratio is being enforced, this will return 0.
  34764. */
  34765. double getFixedAspectRatio() const throw();
  34766. /** This callback changes the given co-ordinates to impose whatever the current
  34767. constraints are set to be.
  34768. @param x the x position that should be examined and adjusted
  34769. @param y the y position that should be examined and adjusted
  34770. @param w the width that should be examined and adjusted
  34771. @param h the height that should be examined and adjusted
  34772. @param previousBounds the component's current size
  34773. @param limits the region in which the component can be positioned
  34774. @param isStretchingTop whether the top edge of the component is being resized
  34775. @param isStretchingLeft whether the left edge of the component is being resized
  34776. @param isStretchingBottom whether the bottom edge of the component is being resized
  34777. @param isStretchingRight whether the right edge of the component is being resized
  34778. */
  34779. virtual void checkBounds (int& x, int& y, int& w, int& h,
  34780. const Rectangle& previousBounds,
  34781. const Rectangle& limits,
  34782. const bool isStretchingTop,
  34783. const bool isStretchingLeft,
  34784. const bool isStretchingBottom,
  34785. const bool isStretchingRight);
  34786. /** This callback happens when the resizer is about to start dragging. */
  34787. virtual void resizeStart();
  34788. /** This callback happens when the resizer has finished dragging. */
  34789. virtual void resizeEnd();
  34790. /** Checks the given bounds, and then sets the component to the corrected size. */
  34791. void setBoundsForComponent (Component* const component,
  34792. int x, int y, int w, int h,
  34793. const bool isStretchingTop,
  34794. const bool isStretchingLeft,
  34795. const bool isStretchingBottom,
  34796. const bool isStretchingRight);
  34797. /** Performs a check on the current size of a component, and moves or resizes
  34798. it if it fails the constraints.
  34799. */
  34800. void checkComponentBounds (Component* component);
  34801. /** Called by setBoundsForComponent() to apply a new constrained size to a
  34802. component.
  34803. By default this just calls setBounds(), but it virtual in case it's needed for
  34804. extremely cunning purposes.
  34805. */
  34806. virtual void applyBoundsToComponent (Component* component,
  34807. int x, int y, int w, int h);
  34808. juce_UseDebuggingNewOperator
  34809. private:
  34810. int minW, maxW, minH, maxH;
  34811. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  34812. double aspectRatio;
  34813. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  34814. const ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  34815. };
  34816. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  34817. /********* End of inlined file: juce_ComponentBoundsConstrainer.h *********/
  34818. /**
  34819. An object to take care of the logic for dragging components around with the mouse.
  34820. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  34821. then in your mouseDrag() callback, call dragComponent().
  34822. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  34823. to limit the component's position and keep it on-screen.
  34824. e.g. @code
  34825. class MyDraggableComp
  34826. {
  34827. ComponentDragger myDragger;
  34828. void mouseDown (const MouseEvent& e)
  34829. {
  34830. myDragger.startDraggingComponent (this, 0);
  34831. }
  34832. void mouseDrag (const MouseEvent& e)
  34833. {
  34834. myDragger.dragComponent (this, e);
  34835. }
  34836. };
  34837. @endcode
  34838. */
  34839. class JUCE_API ComponentDragger
  34840. {
  34841. public:
  34842. /** Creates a ComponentDragger. */
  34843. ComponentDragger();
  34844. /** Destructor. */
  34845. virtual ~ComponentDragger();
  34846. /** Call this from your component's mouseDown() method, to prepare for dragging.
  34847. @param componentToDrag the component that you want to drag
  34848. @param constrainer a constrainer object to use to keep the component
  34849. from going offscreen
  34850. @see dragComponent
  34851. */
  34852. void startDraggingComponent (Component* const componentToDrag,
  34853. ComponentBoundsConstrainer* constrainer);
  34854. /** Call this from your mouseDrag() callback to move the component.
  34855. This will move the component, but will first check the validity of the
  34856. component's new position using the checkPosition() method, which you
  34857. can override if you need to enforce special positioning limits on the
  34858. component.
  34859. @param componentToDrag the component that you want to drag
  34860. @param e the current mouse-drag event
  34861. @see dragComponent
  34862. */
  34863. void dragComponent (Component* const componentToDrag,
  34864. const MouseEvent& e);
  34865. juce_UseDebuggingNewOperator
  34866. private:
  34867. ComponentBoundsConstrainer* constrainer;
  34868. int originalX, originalY;
  34869. };
  34870. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  34871. /********* End of inlined file: juce_ComponentDragger.h *********/
  34872. /********* Start of inlined file: juce_ResizableBorderComponent.h *********/
  34873. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  34874. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  34875. /**
  34876. A component that resizes its parent window when dragged.
  34877. This component forms a frame around the edge of a component, allowing it to
  34878. be dragged by the edges or corners to resize it - like the way windows are
  34879. resized in MSWindows or Linux.
  34880. To use it, just add it to your component, making it fill the entire parent component
  34881. (there's a mouse hit-test that only traps mouse-events which land around the
  34882. edge of the component, so it's even ok to put it on top of any other components
  34883. you're using). Make sure you rescale the resizer component to fill the parent
  34884. each time the parent's size changes.
  34885. @see ResizableCornerComponent
  34886. */
  34887. class JUCE_API ResizableBorderComponent : public Component
  34888. {
  34889. public:
  34890. /** Creates a resizer.
  34891. Pass in the target component which you want to be resized when this one is
  34892. dragged.
  34893. The target component will usually be a parent of the resizer component, but this
  34894. isn't mandatory.
  34895. Remember that when the target component is resized, it'll need to move and
  34896. resize this component to keep it in place, as this won't happen automatically.
  34897. If the constrainer parameter is non-zero, then this object will be used to enforce
  34898. limits on the size and position that the component can be stretched to. Make sure
  34899. that the constrainer isn't deleted while still in use by this object.
  34900. @see ComponentBoundsConstrainer
  34901. */
  34902. ResizableBorderComponent (Component* const componentToResize,
  34903. ComponentBoundsConstrainer* const constrainer);
  34904. /** Destructor. */
  34905. ~ResizableBorderComponent();
  34906. /** Specifies how many pixels wide the draggable edges of this component are.
  34907. @see getBorderThickness
  34908. */
  34909. void setBorderThickness (const BorderSize& newBorderSize) throw();
  34910. /** Returns the number of pixels wide that the draggable edges of this component are.
  34911. @see setBorderThickness
  34912. */
  34913. const BorderSize getBorderThickness() const throw();
  34914. juce_UseDebuggingNewOperator
  34915. protected:
  34916. /** @internal */
  34917. void paint (Graphics& g);
  34918. /** @internal */
  34919. void mouseEnter (const MouseEvent& e);
  34920. /** @internal */
  34921. void mouseMove (const MouseEvent& e);
  34922. /** @internal */
  34923. void mouseDown (const MouseEvent& e);
  34924. /** @internal */
  34925. void mouseDrag (const MouseEvent& e);
  34926. /** @internal */
  34927. void mouseUp (const MouseEvent& e);
  34928. /** @internal */
  34929. bool hitTest (int x, int y);
  34930. private:
  34931. Component* const component;
  34932. ComponentBoundsConstrainer* constrainer;
  34933. BorderSize borderSize;
  34934. int originalX, originalY, originalW, originalH;
  34935. int mouseZone;
  34936. void updateMouseZone (const MouseEvent& e) throw();
  34937. ResizableBorderComponent (const ResizableBorderComponent&);
  34938. const ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  34939. };
  34940. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  34941. /********* End of inlined file: juce_ResizableBorderComponent.h *********/
  34942. /********* Start of inlined file: juce_ResizableCornerComponent.h *********/
  34943. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  34944. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  34945. /** A component that resizes a parent window when dragged.
  34946. This is the small triangular stripey resizer component you get in the bottom-right
  34947. of windows (more commonly on the Mac than Windows). Put one in the corner of
  34948. a larger component and it will automatically resize its parent when it gets dragged
  34949. around.
  34950. @see ResizableFrameComponent
  34951. */
  34952. class JUCE_API ResizableCornerComponent : public Component
  34953. {
  34954. public:
  34955. /** Creates a resizer.
  34956. Pass in the target component which you want to be resized when this one is
  34957. dragged.
  34958. The target component will usually be a parent of the resizer component, but this
  34959. isn't mandatory.
  34960. Remember that when the target component is resized, it'll need to move and
  34961. resize this component to keep it in place, as this won't happen automatically.
  34962. If the constrainer parameter is non-zero, then this object will be used to enforce
  34963. limits on the size and position that the component can be stretched to. Make sure
  34964. that the constrainer isn't deleted while still in use by this object. If you
  34965. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  34966. @see ComponentBoundsConstrainer
  34967. */
  34968. ResizableCornerComponent (Component* const componentToResize,
  34969. ComponentBoundsConstrainer* const constrainer);
  34970. /** Destructor. */
  34971. ~ResizableCornerComponent();
  34972. juce_UseDebuggingNewOperator
  34973. protected:
  34974. /** @internal */
  34975. void paint (Graphics& g);
  34976. /** @internal */
  34977. void mouseDown (const MouseEvent& e);
  34978. /** @internal */
  34979. void mouseDrag (const MouseEvent& e);
  34980. /** @internal */
  34981. void mouseUp (const MouseEvent& e);
  34982. /** @internal */
  34983. bool hitTest (int x, int y);
  34984. private:
  34985. Component* const component;
  34986. ComponentBoundsConstrainer* constrainer;
  34987. int originalX, originalY, originalW, originalH;
  34988. ResizableCornerComponent (const ResizableCornerComponent&);
  34989. const ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  34990. };
  34991. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  34992. /********* End of inlined file: juce_ResizableCornerComponent.h *********/
  34993. /**
  34994. A base class for top-level windows that can be dragged around and resized.
  34995. To add content to the window, use its setContentComponent() method to
  34996. give it a component that will remain positioned inside it (leaving a gap around
  34997. the edges for a border).
  34998. It's not advisable to add child components directly to a ResizableWindow: put them
  34999. inside your content component instead. And overriding methods like resized(), moved(), etc
  35000. is also not recommended - instead override these methods for your content component.
  35001. (If for some obscure reason you do need to override these methods, always remember to
  35002. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  35003. decorations correctly).
  35004. By default resizing isn't enabled - use the setResizable() method to enable it and
  35005. to choose the style of resizing to use.
  35006. @see TopLevelWindow
  35007. */
  35008. class JUCE_API ResizableWindow : public TopLevelWindow
  35009. {
  35010. public:
  35011. /** Creates a ResizableWindow.
  35012. This constructor doesn't specify a background colour, so the LookAndFeel's default
  35013. background colour will be used.
  35014. @param name the name to give the component
  35015. @param addToDesktop if true, the window will be automatically added to the
  35016. desktop; if false, you can use it as a child component
  35017. */
  35018. ResizableWindow (const String& name,
  35019. const bool addToDesktop);
  35020. /** Creates a ResizableWindow.
  35021. @param name the name to give the component
  35022. @param backgroundColour the colour to use for filling the window's background.
  35023. @param addToDesktop if true, the window will be automatically added to the
  35024. desktop; if false, you can use it as a child component
  35025. */
  35026. ResizableWindow (const String& name,
  35027. const Colour& backgroundColour,
  35028. const bool addToDesktop);
  35029. /** Destructor.
  35030. If a content component has been set with setContentComponent(), it
  35031. will be deleted.
  35032. */
  35033. ~ResizableWindow();
  35034. /** Returns the colour currently being used for the window's background.
  35035. As a convenience the window will fill itself with this colour, but you
  35036. can override the paint() method if you need more customised behaviour.
  35037. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  35038. @see setBackgroundColour
  35039. */
  35040. const Colour getBackgroundColour() const throw();
  35041. /** Changes the colour currently being used for the window's background.
  35042. As a convenience the window will fill itself with this colour, but you
  35043. can override the paint() method if you need more customised behaviour.
  35044. Note that the opaque state of this window is altered by this call to reflect
  35045. the opacity of the colour passed-in. On window systems which can't support
  35046. semi-transparent windows this might cause problems, (though it's unlikely you'll
  35047. be using this class as a base for a semi-transparent component anyway).
  35048. You can also use the ResizableWindow::backgroundColourId colour id to set
  35049. this colour.
  35050. @see getBackgroundColour
  35051. */
  35052. void setBackgroundColour (const Colour& newColour);
  35053. /** Make the window resizable or fixed.
  35054. @param shouldBeResizable whether it's resizable at all
  35055. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  35056. bottom-right; if false, it'll use a ResizableBorderComponent
  35057. around the edge
  35058. @see setResizeLimits, isResizable
  35059. */
  35060. void setResizable (const bool shouldBeResizable,
  35061. const bool useBottomRightCornerResizer);
  35062. /** True if resizing is enabled.
  35063. @see setResizable
  35064. */
  35065. bool isResizable() const throw();
  35066. /** This sets the maximum and minimum sizes for the window.
  35067. If the window's current size is outside these limits, it will be resized to
  35068. make sure it's within them.
  35069. Calling setBounds() on the component will bypass any size checking - it's only when
  35070. the window is being resized by the user that these values are enforced.
  35071. @see setResizable, setFixedAspectRatio
  35072. */
  35073. void setResizeLimits (const int newMinimumWidth,
  35074. const int newMinimumHeight,
  35075. const int newMaximumWidth,
  35076. const int newMaximumHeight) throw();
  35077. /** Returns the bounds constrainer object that this window is using.
  35078. You can access this to change its properties.
  35079. */
  35080. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  35081. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  35082. A pointer to the object you pass in will be kept, but it won't be deleted
  35083. by this object, so it's the caller's responsiblity to manage it.
  35084. If you pass 0, then no contraints will be placed on the positioning of the window.
  35085. */
  35086. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  35087. /** Calls the window's setBounds method, after first checking these bounds
  35088. with the current constrainer.
  35089. @see setConstrainer
  35090. */
  35091. void setBoundsConstrained (int x, int y, int width, int height);
  35092. /** Returns true if the window is currently in full-screen mode.
  35093. @see setFullScreen
  35094. */
  35095. bool isFullScreen() const;
  35096. /** Puts the window into full-screen mode, or restores it to its normal size.
  35097. If true, the window will become full-screen; if false, it will return to the
  35098. last size it was before being made full-screen.
  35099. @see isFullScreen
  35100. */
  35101. void setFullScreen (const bool shouldBeFullScreen);
  35102. /** Returns true if the window is currently minimised.
  35103. @see setMinimised
  35104. */
  35105. bool isMinimised() const;
  35106. /** Minimises the window, or restores it to its previous position and size.
  35107. When being un-minimised, it'll return to the last position and size it
  35108. was in before being minimised.
  35109. @see isMinimised
  35110. */
  35111. void setMinimised (const bool shouldMinimise);
  35112. /** Returns a string which encodes the window's current size and position.
  35113. This string will encapsulate the window's size, position, and whether it's
  35114. in full-screen mode. It's intended for letting your application save and
  35115. restore a window's position.
  35116. Use the restoreWindowStateFromString() to restore from a saved state.
  35117. @see restoreWindowStateFromString
  35118. */
  35119. const String getWindowStateAsString();
  35120. /** Restores the window to a previously-saved size and position.
  35121. This restores the window's size, positon and full-screen status from an
  35122. string that was previously created with the getWindowStateAsString()
  35123. method.
  35124. @returns false if the string wasn't a valid window state
  35125. @see getWindowStateAsString
  35126. */
  35127. bool restoreWindowStateFromString (const String& previousState);
  35128. /** Returns the current content component.
  35129. This will be the component set by setContentComponent(), or 0 if none
  35130. has yet been specified.
  35131. @see setContentComponent
  35132. */
  35133. Component* getContentComponent() const throw() { return contentComponent; }
  35134. /** Changes the current content component.
  35135. This sets a component that will be placed in the centre of the ResizableWindow,
  35136. (leaving a space around the edge for the border).
  35137. You should never add components directly to a ResizableWindow (or any of its subclasses)
  35138. with addChildComponent(). Instead, add them to the content component.
  35139. @param newContentComponent the new component to use (or null to not use one) - this
  35140. component will be deleted either when replaced by another call
  35141. to this method, or when the ResizableWindow is deleted.
  35142. To remove a content component without deleting it, use
  35143. setContentComponent (0, false).
  35144. @param deleteOldOne if true, the previous content component will be deleted; if
  35145. false, the previous component will just be removed without
  35146. deleting it.
  35147. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  35148. it always fits around the size of the content component. If false, the
  35149. new content will be resized to fit the current space available.
  35150. */
  35151. void setContentComponent (Component* const newContentComponent,
  35152. const bool deleteOldOne = true,
  35153. const bool resizeToFit = false);
  35154. /** Changes the window so that the content component ends up with the specified size.
  35155. This is basically a setSize call on the window, but which adds on the borders,
  35156. so you can specify the content component's target size.
  35157. */
  35158. void setContentComponentSize (int width, int height);
  35159. /** A set of colour IDs to use to change the colour of various aspects of the window.
  35160. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35161. methods.
  35162. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35163. */
  35164. enum ColourIds
  35165. {
  35166. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  35167. };
  35168. juce_UseDebuggingNewOperator
  35169. protected:
  35170. /** @internal */
  35171. void paint (Graphics& g);
  35172. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35173. void moved();
  35174. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  35175. void resized();
  35176. /** @internal */
  35177. void mouseDown (const MouseEvent& e);
  35178. /** @internal */
  35179. void mouseDrag (const MouseEvent& e);
  35180. /** @internal */
  35181. void lookAndFeelChanged();
  35182. /** @internal */
  35183. void childBoundsChanged (Component* child);
  35184. /** @internal */
  35185. void parentSizeChanged();
  35186. /** @internal */
  35187. void visibilityChanged();
  35188. /** @internal */
  35189. void activeWindowStatusChanged();
  35190. /** @internal */
  35191. int getDesktopWindowStyleFlags() const;
  35192. /** Returns the width of the border to use around the window.
  35193. @see getContentComponentBorder
  35194. */
  35195. virtual const BorderSize getBorderThickness();
  35196. /** Returns the insets to use when positioning the content component.
  35197. @see getBorderThickness
  35198. */
  35199. virtual const BorderSize getContentComponentBorder();
  35200. #ifdef JUCE_DEBUG
  35201. /** Overridden to warn people about adding components directly to this component
  35202. instead of using setContentComponent().
  35203. If you know what you're doing and are sure you really want to add a component, specify
  35204. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35205. */
  35206. void addChildComponent (Component* const child, int zOrder = -1);
  35207. /** Overridden to warn people about adding components directly to this component
  35208. instead of using setContentComponent().
  35209. If you know what you're doing and are sure you really want to add a component, specify
  35210. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  35211. */
  35212. void addAndMakeVisible (Component* const child, int zOrder = -1);
  35213. #endif
  35214. ScopedPointer <ResizableCornerComponent> resizableCorner;
  35215. ScopedPointer <ResizableBorderComponent> resizableBorder;
  35216. private:
  35217. ScopedPointer <Component> contentComponent;
  35218. bool resizeToFitContent, fullscreen;
  35219. ComponentDragger dragger;
  35220. Rectangle lastNonFullScreenPos;
  35221. ComponentBoundsConstrainer defaultConstrainer;
  35222. ComponentBoundsConstrainer* constrainer;
  35223. #ifdef JUCE_DEBUG
  35224. bool hasBeenResized;
  35225. #endif
  35226. void updateLastPos();
  35227. ResizableWindow (const ResizableWindow&);
  35228. const ResizableWindow& operator= (const ResizableWindow&);
  35229. // (xxx remove these eventually)
  35230. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35231. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  35232. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  35233. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  35234. };
  35235. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  35236. /********* End of inlined file: juce_ResizableWindow.h *********/
  35237. /********* Start of inlined file: juce_GlyphArrangement.h *********/
  35238. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  35239. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  35240. /**
  35241. A glyph from a particular font, with a particular size, style,
  35242. typeface and position.
  35243. @see GlyphArrangement, Font
  35244. */
  35245. class JUCE_API PositionedGlyph
  35246. {
  35247. public:
  35248. /** Returns the character the glyph represents. */
  35249. juce_wchar getCharacter() const throw() { return character; }
  35250. /** Checks whether the glyph is actually empty. */
  35251. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (character); }
  35252. /** Returns the position of the glyph's left-hand edge. */
  35253. float getLeft() const throw() { return x; }
  35254. /** Returns the position of the glyph's right-hand edge. */
  35255. float getRight() const throw() { return x + w; }
  35256. /** Returns the y position of the glyph's baseline. */
  35257. float getBaselineY() const throw() { return y; }
  35258. /** Returns the y position of the top of the glyph. */
  35259. float getTop() const throw() { return y - font.getAscent(); }
  35260. /** Returns the y position of the bottom of the glyph. */
  35261. float getBottom() const throw() { return y + font.getDescent(); }
  35262. /** Shifts the glyph's position by a relative amount. */
  35263. void moveBy (const float deltaX,
  35264. const float deltaY) throw();
  35265. /** Draws the glyph into a graphics context. */
  35266. void draw (const Graphics& g) const throw();
  35267. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  35268. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  35269. /** Returns the path for this glyph.
  35270. @param path the glyph's outline will be appended to this path
  35271. */
  35272. void createPath (Path& path) const throw();
  35273. /** Checks to see if a point lies within this glyph. */
  35274. bool hitTest (float x, float y) const throw();
  35275. juce_UseDebuggingNewOperator
  35276. private:
  35277. friend class GlyphArrangement;
  35278. float x, y, w;
  35279. Font font;
  35280. juce_wchar character;
  35281. int glyph;
  35282. PositionedGlyph() throw();
  35283. };
  35284. /**
  35285. A set of glyphs, each with a position.
  35286. You can create a GlyphArrangement, text to it and then draw it onto a
  35287. graphics context. It's used internally by the text methods in the
  35288. Graphics class, but can be used directly if more control is needed.
  35289. @see Font, PositionedGlyph
  35290. */
  35291. class JUCE_API GlyphArrangement
  35292. {
  35293. public:
  35294. /** Creates an empty arrangement. */
  35295. GlyphArrangement() throw();
  35296. /** Takes a copy of another arrangement. */
  35297. GlyphArrangement (const GlyphArrangement& other) throw();
  35298. /** Copies another arrangement onto this one.
  35299. To add another arrangement without clearing this one, use addGlyphArrangement().
  35300. */
  35301. const GlyphArrangement& operator= (const GlyphArrangement& other) throw();
  35302. /** Destructor. */
  35303. ~GlyphArrangement() throw();
  35304. /** Returns the total number of glyphs in the arrangement. */
  35305. int getNumGlyphs() const throw() { return glyphs.size(); }
  35306. /** Returns one of the glyphs from the arrangement.
  35307. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  35308. careful not to pass an out-of-range index here, as it
  35309. doesn't do any bounds-checking.
  35310. */
  35311. PositionedGlyph& getGlyph (const int index) const throw();
  35312. /** Clears all text from the arrangement and resets it.
  35313. */
  35314. void clear() throw();
  35315. /** Appends a line of text to the arrangement.
  35316. This will add the text as a single line, where x is the left-hand edge of the
  35317. first character, and y is the position for the text's baseline.
  35318. If the text contains new-lines or carriage-returns, this will ignore them - use
  35319. addJustifiedText() to add multi-line arrangements.
  35320. */
  35321. void addLineOfText (const Font& font,
  35322. const String& text,
  35323. const float x,
  35324. const float y) throw();
  35325. /** Adds a line of text, truncating it if it's wider than a specified size.
  35326. This is the same as addLineOfText(), but if the line's width exceeds the value
  35327. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  35328. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  35329. */
  35330. void addCurtailedLineOfText (const Font& font,
  35331. const String& text,
  35332. float x,
  35333. const float y,
  35334. const float maxWidthPixels,
  35335. const bool useEllipsis) throw();
  35336. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  35337. This will add text to the arrangement, breaking it into new lines either where there
  35338. is a new-line or carriage-return character in the text, or where a line's width
  35339. exceeds the value set in maxLineWidth.
  35340. Each line that is added will be laid out using the flags set in horizontalLayout, so
  35341. the lines can be left- or right-justified, or centred horizontally in the space
  35342. between x and (x + maxLineWidth).
  35343. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  35344. lines will be placed below it, separated by a distance of font.getHeight().
  35345. */
  35346. void addJustifiedText (const Font& font,
  35347. const String& text,
  35348. float x, float y,
  35349. const float maxLineWidth,
  35350. const Justification& horizontalLayout) throw();
  35351. /** Tries to fit some text withing a given space.
  35352. This does its best to make the given text readable within the specified rectangle,
  35353. so it useful for labelling things.
  35354. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  35355. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  35356. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  35357. it's been truncated.
  35358. A Justification parameter lets you specify how the text is laid out within the rectangle,
  35359. both horizontally and vertically.
  35360. @see Graphics::drawFittedText
  35361. */
  35362. void addFittedText (const Font& font,
  35363. const String& text,
  35364. const float x, const float y,
  35365. const float width, const float height,
  35366. const Justification& layout,
  35367. int maximumLinesToUse,
  35368. const float minimumHorizontalScale = 0.7f) throw();
  35369. /** Appends another glyph arrangement to this one. */
  35370. void addGlyphArrangement (const GlyphArrangement& other) throw();
  35371. /** Draws this glyph arrangement to a graphics context.
  35372. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  35373. method, which renders the glyphs as filled vectors.
  35374. */
  35375. void draw (const Graphics& g) const throw();
  35376. /** Draws this glyph arrangement to a graphics context.
  35377. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  35378. method for non-transformed arrangements.
  35379. */
  35380. void draw (const Graphics& g, const AffineTransform& transform) const throw();
  35381. /** Converts the set of glyphs into a path.
  35382. @param path the glyphs' outlines will be appended to this path
  35383. */
  35384. void createPath (Path& path) const throw();
  35385. /** Looks for a glyph that contains the given co-ordinate.
  35386. @returns the index of the glyph, or -1 if none were found.
  35387. */
  35388. int findGlyphIndexAt (float x, float y) const throw();
  35389. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  35390. @param startIndex the first glyph to test
  35391. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  35392. startIndex will be included
  35393. @param left on return, the leftmost co-ordinate of the rectangle
  35394. @param top on return, the top co-ordinate of the rectangle
  35395. @param right on return, the rightmost co-ordinate of the rectangle
  35396. @param bottom on return, the bottom co-ordinate of the rectangle
  35397. @param includeWhitespace if true, the extent of any whitespace characters will also
  35398. be taken into account
  35399. */
  35400. void getBoundingBox (int startIndex,
  35401. int numGlyphs,
  35402. float& left,
  35403. float& top,
  35404. float& right,
  35405. float& bottom,
  35406. const bool includeWhitespace) const throw();
  35407. /** Shifts a set of glyphs by a given amount.
  35408. @param startIndex the first glyph to transform
  35409. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  35410. startIndex will be used
  35411. @param deltaX the amount to add to their x-positions
  35412. @param deltaY the amount to add to their y-positions
  35413. */
  35414. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  35415. const float deltaX,
  35416. const float deltaY) throw();
  35417. /** Removes a set of glyphs from the arrangement.
  35418. @param startIndex the first glyph to remove
  35419. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  35420. startIndex will be deleted
  35421. */
  35422. void removeRangeOfGlyphs (int startIndex, int numGlyphs) throw();
  35423. /** Expands or compresses a set of glyphs horizontally.
  35424. @param startIndex the first glyph to transform
  35425. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  35426. startIndex will be used
  35427. @param horizontalScaleFactor how much to scale their horizontal width by
  35428. */
  35429. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  35430. const float horizontalScaleFactor) throw();
  35431. /** Justifies a set of glyphs within a given space.
  35432. This moves the glyphs as a block so that the whole thing is located within the
  35433. given rectangle with the specified layout.
  35434. If the Justification::horizontallyJustified flag is specified, each line will
  35435. be stretched out to fill the specified width.
  35436. */
  35437. void justifyGlyphs (const int startIndex, const int numGlyphs,
  35438. const float x,
  35439. const float y,
  35440. const float width,
  35441. const float height,
  35442. const Justification& justification) throw();
  35443. juce_UseDebuggingNewOperator
  35444. private:
  35445. OwnedArray <PositionedGlyph> glyphs;
  35446. int insertEllipsis (const Font& font, const float maxXPos, const int startIndex, int endIndex) throw();
  35447. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  35448. const Justification& justification, float minimumHorizontalScale) throw();
  35449. void spreadOutLine (const int start, const int numGlyphs, const float targetWidth) throw();
  35450. };
  35451. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  35452. /********* End of inlined file: juce_GlyphArrangement.h *********/
  35453. /**
  35454. A file open/save dialog box.
  35455. This is a Juce-based file dialog box; to use a native file chooser, see the
  35456. FileChooser class.
  35457. To use one of these, create it and call its show() method. e.g.
  35458. @code
  35459. {
  35460. WildcardFileFilter wildcardFilter (T("*.foo"), T("Foo files"));
  35461. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  35462. File::nonexistent,
  35463. &wildcardFilter,
  35464. 0);
  35465. FileChooserDialogBox dialogBox (T("Open some kind of file"),
  35466. T("Please choose some kind of file that you want to open..."),
  35467. browser,
  35468. getLookAndFeel().alertWindowBackground);
  35469. if (dialogBox.show())
  35470. {
  35471. File selectedFile = browser.getCurrentFile();
  35472. ...
  35473. }
  35474. }
  35475. @endcode
  35476. @see FileChooser
  35477. */
  35478. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  35479. public ButtonListener,
  35480. public FileBrowserListener
  35481. {
  35482. public:
  35483. /** Creates a file chooser box.
  35484. @param title the main title to show at the top of the box
  35485. @param instructions an optional longer piece of text to show below the title in
  35486. a smaller font, describing in more detail what's required.
  35487. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  35488. box. Make sure you delete this after (but not before!) the
  35489. dialog box has been deleted.
  35490. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  35491. if they try to select a file that already exists. (This
  35492. flag is only used when saving files)
  35493. @param backgroundColour the background colour for the top level window
  35494. @see FileBrowserComponent, FilePreviewComponent
  35495. */
  35496. FileChooserDialogBox (const String& title,
  35497. const String& instructions,
  35498. FileBrowserComponent& browserComponent,
  35499. const bool warnAboutOverwritingExistingFiles,
  35500. const Colour& backgroundColour);
  35501. /** Destructor. */
  35502. ~FileChooserDialogBox();
  35503. /** Displays and runs the dialog box modally.
  35504. This will show the box with the specified size, returning true if the user
  35505. pressed 'ok', or false if they cancelled.
  35506. Leave the width or height as 0 to use the default size
  35507. */
  35508. bool show (int width = 0,int height = 0);
  35509. /** @internal */
  35510. void buttonClicked (Button* button);
  35511. /** @internal */
  35512. void closeButtonPressed();
  35513. /** @internal */
  35514. void selectionChanged();
  35515. /** @internal */
  35516. void fileClicked (const File& file, const MouseEvent& e);
  35517. /** @internal */
  35518. void fileDoubleClicked (const File& file);
  35519. juce_UseDebuggingNewOperator
  35520. private:
  35521. class ContentComponent : public Component
  35522. {
  35523. public:
  35524. ContentComponent();
  35525. ~ContentComponent();
  35526. void paint (Graphics& g);
  35527. void resized();
  35528. String instructions;
  35529. GlyphArrangement text;
  35530. FileBrowserComponent* chooserComponent;
  35531. FilePreviewComponent* previewComponent;
  35532. TextButton* okButton;
  35533. TextButton* cancelButton;
  35534. };
  35535. ContentComponent* content;
  35536. const bool warnAboutOverwritingExistingFiles;
  35537. FileChooserDialogBox (const FileChooserDialogBox&);
  35538. const FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  35539. };
  35540. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  35541. /********* End of inlined file: juce_FileChooserDialogBox.h *********/
  35542. #endif
  35543. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  35544. #endif
  35545. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  35546. /********* Start of inlined file: juce_FileListComponent.h *********/
  35547. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  35548. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  35549. /**
  35550. A component that displays the files in a directory as a listbox.
  35551. This implements the DirectoryContentsDisplayComponent base class so that
  35552. it can be used in a FileBrowserComponent.
  35553. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  35554. class and the FileBrowserListener class.
  35555. @see DirectoryContentsList, FileTreeComponent
  35556. */
  35557. class JUCE_API FileListComponent : public ListBox,
  35558. public DirectoryContentsDisplayComponent,
  35559. private ListBoxModel,
  35560. private ChangeListener
  35561. {
  35562. public:
  35563. /** Creates a listbox to show the contents of a specified directory.
  35564. */
  35565. FileListComponent (DirectoryContentsList& listToShow);
  35566. /** Destructor. */
  35567. ~FileListComponent();
  35568. /** Returns the number of files the user has got selected.
  35569. @see getSelectedFile
  35570. */
  35571. int getNumSelectedFiles() const;
  35572. /** Returns one of the files that the user has currently selected.
  35573. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  35574. @see getNumSelectedFiles
  35575. */
  35576. const File getSelectedFile (int index = 0) const;
  35577. /** Scrolls to the top of the list. */
  35578. void scrollToTop();
  35579. /** @internal */
  35580. void changeListenerCallback (void*);
  35581. /** @internal */
  35582. int getNumRows();
  35583. /** @internal */
  35584. void paintListBoxItem (int, Graphics&, int, int, bool);
  35585. /** @internal */
  35586. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35587. /** @internal */
  35588. void selectedRowsChanged (int lastRowSelected);
  35589. /** @internal */
  35590. void deleteKeyPressed (int currentSelectedRow);
  35591. /** @internal */
  35592. void returnKeyPressed (int currentSelectedRow);
  35593. juce_UseDebuggingNewOperator
  35594. private:
  35595. FileListComponent (const FileListComponent&);
  35596. const FileListComponent& operator= (const FileListComponent&);
  35597. File lastDirectory;
  35598. };
  35599. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  35600. /********* End of inlined file: juce_FileListComponent.h *********/
  35601. #endif
  35602. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  35603. /********* Start of inlined file: juce_FilenameComponent.h *********/
  35604. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  35605. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  35606. class FilenameComponent;
  35607. /**
  35608. Listens for events happening to a FilenameComponent.
  35609. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  35610. register one of these objects for event callbacks when the filename is changed.
  35611. @see FilenameComponent
  35612. */
  35613. class JUCE_API FilenameComponentListener
  35614. {
  35615. public:
  35616. /** Destructor. */
  35617. virtual ~FilenameComponentListener() {}
  35618. /** This method is called after the FilenameComponent's file has been changed. */
  35619. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  35620. };
  35621. /**
  35622. Shows a filename as an editable text box, with a 'browse' button and a
  35623. drop-down list for recently selected files.
  35624. A handy component for dialogue boxes where you want the user to be able to
  35625. select a file or directory.
  35626. Attach an FilenameComponentListener using the addListener() method, and it will
  35627. get called each time the user changes the filename, either by browsing for a file
  35628. and clicking 'ok', or by typing a new filename into the box and pressing return.
  35629. @see FileChooser, ComboBox
  35630. */
  35631. class JUCE_API FilenameComponent : public Component,
  35632. public SettableTooltipClient,
  35633. public FileDragAndDropTarget,
  35634. private AsyncUpdater,
  35635. private ButtonListener,
  35636. private ComboBoxListener
  35637. {
  35638. public:
  35639. /** Creates a FilenameComponent.
  35640. @param name the name for this component.
  35641. @param currentFile the file to initially show in the box
  35642. @param canEditFilename if true, the user can manually edit the filename; if false,
  35643. they can only change it by browsing for a new file
  35644. @param isDirectory if true, the file will be treated as a directory, and
  35645. an appropriate directory browser used
  35646. @param isForSaving if true, the file browser will allow non-existent files to
  35647. be picked, as the file is assumed to be used for saving rather
  35648. than loading
  35649. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  35650. If an empty string is passed in, then the pattern is assumed to be "*"
  35651. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  35652. to any filenames that are entered or chosen
  35653. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  35654. will only appear if the initial file isn't valid)
  35655. */
  35656. FilenameComponent (const String& name,
  35657. const File& currentFile,
  35658. const bool canEditFilename,
  35659. const bool isDirectory,
  35660. const bool isForSaving,
  35661. const String& fileBrowserWildcard,
  35662. const String& enforcedSuffix,
  35663. const String& textWhenNothingSelected);
  35664. /** Destructor. */
  35665. ~FilenameComponent();
  35666. /** Returns the currently displayed filename. */
  35667. const File getCurrentFile() const;
  35668. /** Changes the current filename.
  35669. If addToRecentlyUsedList is true, the filename will also be added to the
  35670. drop-down list of recent files.
  35671. If sendChangeNotification is false, then the listeners won't be told of the
  35672. change.
  35673. */
  35674. void setCurrentFile (File newFile,
  35675. const bool addToRecentlyUsedList,
  35676. const bool sendChangeNotification = true);
  35677. /** Changes whether the use can type into the filename box.
  35678. */
  35679. void setFilenameIsEditable (const bool shouldBeEditable);
  35680. /** Sets a file or directory to be the default starting point for the browser to show.
  35681. This is only used if the current file hasn't been set.
  35682. */
  35683. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  35684. /** Returns all the entries on the recent files list.
  35685. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  35686. state of this list.
  35687. @see setRecentlyUsedFilenames
  35688. */
  35689. const StringArray getRecentlyUsedFilenames() const;
  35690. /** Sets all the entries on the recent files list.
  35691. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  35692. state of this list.
  35693. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  35694. */
  35695. void setRecentlyUsedFilenames (const StringArray& filenames);
  35696. /** Adds an entry to the recently-used files dropdown list.
  35697. If the file is already in the list, it will be moved to the top. A limit
  35698. is also placed on the number of items that are kept in the list.
  35699. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  35700. */
  35701. void addRecentlyUsedFile (const File& file);
  35702. /** Changes the limit for the number of files that will be stored in the recent-file list.
  35703. */
  35704. void setMaxNumberOfRecentFiles (const int newMaximum);
  35705. /** Changes the text shown on the 'browse' button.
  35706. By default this button just says "..." but you can change it. The button itself
  35707. can be changed using the look-and-feel classes, so it might not actually have any
  35708. text on it.
  35709. */
  35710. void setBrowseButtonText (const String& browseButtonText);
  35711. /** Adds a listener that will be called when the selected file is changed. */
  35712. void addListener (FilenameComponentListener* const listener) throw();
  35713. /** Removes a previously-registered listener. */
  35714. void removeListener (FilenameComponentListener* const listener) throw();
  35715. /** Gives the component a tooltip. */
  35716. void setTooltip (const String& newTooltip);
  35717. /** @internal */
  35718. void paintOverChildren (Graphics& g);
  35719. /** @internal */
  35720. void resized();
  35721. /** @internal */
  35722. void lookAndFeelChanged();
  35723. /** @internal */
  35724. bool isInterestedInFileDrag (const StringArray& files);
  35725. /** @internal */
  35726. void filesDropped (const StringArray& files, int, int);
  35727. /** @internal */
  35728. void fileDragEnter (const StringArray& files, int, int);
  35729. /** @internal */
  35730. void fileDragExit (const StringArray& files);
  35731. juce_UseDebuggingNewOperator
  35732. private:
  35733. ComboBox* filenameBox;
  35734. String lastFilename;
  35735. Button* browseButton;
  35736. int maxRecentFiles;
  35737. bool isDir, isSaving, isFileDragOver;
  35738. String wildcard, enforcedSuffix, browseButtonText;
  35739. SortedSet <void*> listeners;
  35740. File defaultBrowseFile;
  35741. void comboBoxChanged (ComboBox*);
  35742. void buttonClicked (Button* button);
  35743. void handleAsyncUpdate();
  35744. FilenameComponent (const FilenameComponent&);
  35745. const FilenameComponent& operator= (const FilenameComponent&);
  35746. };
  35747. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  35748. /********* End of inlined file: juce_FilenameComponent.h *********/
  35749. #endif
  35750. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  35751. #endif
  35752. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  35753. /********* Start of inlined file: juce_FileSearchPathListComponent.h *********/
  35754. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  35755. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  35756. /**
  35757. Shows a set of file paths in a list, allowing them to be added, removed or
  35758. re-ordered.
  35759. @see FileSearchPath
  35760. */
  35761. class JUCE_API FileSearchPathListComponent : public Component,
  35762. public SettableTooltipClient,
  35763. public FileDragAndDropTarget,
  35764. private ButtonListener,
  35765. private ListBoxModel
  35766. {
  35767. public:
  35768. /** Creates an empty FileSearchPathListComponent.
  35769. */
  35770. FileSearchPathListComponent();
  35771. /** Destructor. */
  35772. ~FileSearchPathListComponent();
  35773. /** Returns the path as it is currently shown. */
  35774. const FileSearchPath& getPath() const throw() { return path; }
  35775. /** Changes the current path. */
  35776. void setPath (const FileSearchPath& newPath);
  35777. /** Sets a file or directory to be the default starting point for the browser to show.
  35778. This is only used if the current file hasn't been set.
  35779. */
  35780. void setDefaultBrowseTarget (const File& newDefaultDirectory) throw();
  35781. /** A set of colour IDs to use to change the colour of various aspects of the label.
  35782. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35783. methods.
  35784. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35785. */
  35786. enum ColourIds
  35787. {
  35788. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  35789. Make this transparent if you don't want the background to be filled. */
  35790. };
  35791. /** @internal */
  35792. int getNumRows();
  35793. /** @internal */
  35794. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  35795. /** @internal */
  35796. void deleteKeyPressed (int lastRowSelected);
  35797. /** @internal */
  35798. void returnKeyPressed (int lastRowSelected);
  35799. /** @internal */
  35800. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  35801. /** @internal */
  35802. void selectedRowsChanged (int lastRowSelected);
  35803. /** @internal */
  35804. void resized();
  35805. /** @internal */
  35806. void paint (Graphics& g);
  35807. /** @internal */
  35808. bool isInterestedInFileDrag (const StringArray& files);
  35809. /** @internal */
  35810. void filesDropped (const StringArray& files, int, int);
  35811. /** @internal */
  35812. void buttonClicked (Button* button);
  35813. juce_UseDebuggingNewOperator
  35814. private:
  35815. FileSearchPath path;
  35816. File defaultBrowseTarget;
  35817. ListBox* listBox;
  35818. Button* addButton;
  35819. Button* removeButton;
  35820. Button* changeButton;
  35821. Button* upButton;
  35822. Button* downButton;
  35823. void changed() throw();
  35824. void updateButtons() throw();
  35825. FileSearchPathListComponent (const FileSearchPathListComponent&);
  35826. const FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  35827. };
  35828. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  35829. /********* End of inlined file: juce_FileSearchPathListComponent.h *********/
  35830. #endif
  35831. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  35832. /********* Start of inlined file: juce_FileTreeComponent.h *********/
  35833. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  35834. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  35835. /**
  35836. A component that displays the files in a directory as a treeview.
  35837. This implements the DirectoryContentsDisplayComponent base class so that
  35838. it can be used in a FileBrowserComponent.
  35839. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  35840. class and the FileBrowserListener class.
  35841. @see DirectoryContentsList, FileListComponent
  35842. */
  35843. class JUCE_API FileTreeComponent : public TreeView,
  35844. public DirectoryContentsDisplayComponent
  35845. {
  35846. public:
  35847. /** Creates a listbox to show the contents of a specified directory.
  35848. */
  35849. FileTreeComponent (DirectoryContentsList& listToShow);
  35850. /** Destructor. */
  35851. ~FileTreeComponent();
  35852. /** Returns the number of files the user has got selected.
  35853. @see getSelectedFile
  35854. */
  35855. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  35856. /** Returns one of the files that the user has currently selected.
  35857. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  35858. @see getNumSelectedFiles
  35859. */
  35860. const File getSelectedFile (int index = 0) const;
  35861. /** Scrolls the list to the top. */
  35862. void scrollToTop();
  35863. /** Setting a name for this allows tree items to be dragged.
  35864. The string that you pass in here will be returned by the getDragSourceDescription()
  35865. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  35866. */
  35867. void setDragAndDropDescription (const String& description) throw();
  35868. /** Returns the last value that was set by setDragAndDropDescription().
  35869. */
  35870. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  35871. juce_UseDebuggingNewOperator
  35872. private:
  35873. String dragAndDropDescription;
  35874. FileTreeComponent (const FileTreeComponent&);
  35875. const FileTreeComponent& operator= (const FileTreeComponent&);
  35876. };
  35877. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  35878. /********* End of inlined file: juce_FileTreeComponent.h *********/
  35879. #endif
  35880. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  35881. /********* Start of inlined file: juce_ImagePreviewComponent.h *********/
  35882. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  35883. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  35884. /**
  35885. A simple preview component that shows thumbnails of image files.
  35886. @see FileChooserDialogBox, FilePreviewComponent
  35887. */
  35888. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  35889. private Timer
  35890. {
  35891. public:
  35892. /** Creates an ImagePreviewComponent. */
  35893. ImagePreviewComponent();
  35894. /** Destructor. */
  35895. ~ImagePreviewComponent();
  35896. /** @internal */
  35897. void selectedFileChanged (const File& newSelectedFile);
  35898. /** @internal */
  35899. void paint (Graphics& g);
  35900. /** @internal */
  35901. void timerCallback();
  35902. juce_UseDebuggingNewOperator
  35903. private:
  35904. File fileToLoad;
  35905. ScopedPointer <Image> currentThumbnail;
  35906. String currentDetails;
  35907. void getThumbSize (int& w, int& h) const;
  35908. ImagePreviewComponent (const ImagePreviewComponent&);
  35909. const ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  35910. };
  35911. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  35912. /********* End of inlined file: juce_ImagePreviewComponent.h *********/
  35913. #endif
  35914. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  35915. /********* Start of inlined file: juce_WildcardFileFilter.h *********/
  35916. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  35917. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  35918. /**
  35919. A type of FileFilter that works by wildcard pattern matching.
  35920. This filter only allows files that match one of the specified patterns, but
  35921. allows all directories through.
  35922. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  35923. */
  35924. class JUCE_API WildcardFileFilter : public FileFilter
  35925. {
  35926. public:
  35927. /**
  35928. Creates a wildcard filter for one or more patterns.
  35929. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  35930. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  35931. or .aiff.
  35932. The description is a name to show the user in a list of possible patterns, so
  35933. for the wav/aiff example, your description might be "audio files".
  35934. */
  35935. WildcardFileFilter (const String& fileWildcardPatterns,
  35936. const String& directoryWildcardPatterns,
  35937. const String& description);
  35938. /** Destructor. */
  35939. ~WildcardFileFilter();
  35940. /** Returns true if the filename matches one of the patterns specified. */
  35941. bool isFileSuitable (const File& file) const;
  35942. /** This always returns true. */
  35943. bool isDirectorySuitable (const File& file) const;
  35944. juce_UseDebuggingNewOperator
  35945. private:
  35946. StringArray fileWildcards, directoryWildcards;
  35947. static void parse (const String& pattern, StringArray& result) throw();
  35948. static bool match (const File& file, const StringArray& wildcards) throw();
  35949. };
  35950. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  35951. /********* End of inlined file: juce_WildcardFileFilter.h *********/
  35952. #endif
  35953. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  35954. #endif
  35955. #ifndef __JUCE_COMPONENTDELETIONWATCHER_JUCEHEADER__
  35956. #endif
  35957. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  35958. #endif
  35959. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  35960. #endif
  35961. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  35962. #endif
  35963. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  35964. #endif
  35965. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  35966. /********* Start of inlined file: juce_KeyMappingEditorComponent.h *********/
  35967. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  35968. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  35969. /********* Start of inlined file: juce_KeyPressMappingSet.h *********/
  35970. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  35971. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  35972. /**
  35973. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  35974. command in a ApplicationCommandManager.
  35975. Normally, you won't actually create a KeyPressMappingSet directly, because
  35976. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  35977. you'd create yourself an ApplicationCommandManager, and call its
  35978. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  35979. KeyPressMappingSet.
  35980. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  35981. to the top-level component for which you want to handle keystrokes. So for example:
  35982. @code
  35983. class MyMainWindow : public Component
  35984. {
  35985. ApplicationCommandManager* myCommandManager;
  35986. public:
  35987. MyMainWindow()
  35988. {
  35989. myCommandManager = new ApplicationCommandManager();
  35990. // first, make sure the command manager has registered all the commands that its
  35991. // targets can perform..
  35992. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  35993. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  35994. // this will use the command manager to initialise the KeyPressMappingSet with
  35995. // the default keypresses that were specified when the targets added their commands
  35996. // to the manager.
  35997. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  35998. // having set up the default key-mappings, you might now want to load the last set
  35999. // of mappings that the user configured.
  36000. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  36001. // Now tell our top-level window to send any keypresses that arrive to the
  36002. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  36003. addKeyListener (myCommandManager->getKeyMappings());
  36004. }
  36005. ...
  36006. }
  36007. @endcode
  36008. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  36009. register to be told when a command or mapping is added, removed, etc.
  36010. There's also a UI component called KeyMappingEditorComponent that can be used
  36011. to easily edit the key mappings.
  36012. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  36013. */
  36014. class JUCE_API KeyPressMappingSet : public KeyListener,
  36015. public ChangeBroadcaster,
  36016. public FocusChangeListener
  36017. {
  36018. public:
  36019. /** Creates a KeyPressMappingSet for a given command manager.
  36020. Normally, you won't actually create a KeyPressMappingSet directly, because
  36021. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  36022. best thing to do is to create your ApplicationCommandManager, and use the
  36023. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  36024. When a suitable keypress happens, the manager's invoke() method will be
  36025. used to invoke the appropriate command.
  36026. @see ApplicationCommandManager
  36027. */
  36028. KeyPressMappingSet (ApplicationCommandManager* const commandManager) throw();
  36029. /** Creates an copy of a KeyPressMappingSet. */
  36030. KeyPressMappingSet (const KeyPressMappingSet& other) throw();
  36031. /** Destructor. */
  36032. ~KeyPressMappingSet();
  36033. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  36034. /** Returns a list of keypresses that are assigned to a particular command.
  36035. @param commandID the command's ID
  36036. */
  36037. const Array <KeyPress> getKeyPressesAssignedToCommand (const CommandID commandID) const throw();
  36038. /** Assigns a keypress to a command.
  36039. If the keypress is already assigned to a different command, it will first be
  36040. removed from that command, to avoid it triggering multiple functions.
  36041. @param commandID the ID of the command that you want to add a keypress to. If
  36042. this is 0, the keypress will be removed from anything that it
  36043. was previously assigned to, but not re-assigned
  36044. @param newKeyPress the new key-press
  36045. @param insertIndex if this is less than zero, the key will be appended to the
  36046. end of the list of keypresses; otherwise the new keypress will
  36047. be inserted into the existing list at this index
  36048. */
  36049. void addKeyPress (const CommandID commandID,
  36050. const KeyPress& newKeyPress,
  36051. int insertIndex = -1) throw();
  36052. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  36053. @see resetToDefaultMapping
  36054. */
  36055. void resetToDefaultMappings() throw();
  36056. /** Resets all key-mappings to the defaults for a particular command.
  36057. @see resetToDefaultMappings
  36058. */
  36059. void resetToDefaultMapping (const CommandID commandID) throw();
  36060. /** Removes all keypresses that are assigned to any commands. */
  36061. void clearAllKeyPresses() throw();
  36062. /** Removes all keypresses that are assigned to a particular command. */
  36063. void clearAllKeyPresses (const CommandID commandID) throw();
  36064. /** Removes one of the keypresses that are assigned to a command.
  36065. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  36066. which the keyPressIndex refers.
  36067. */
  36068. void removeKeyPress (const CommandID commandID,
  36069. const int keyPressIndex) throw();
  36070. /** Removes a keypress from any command that it may be assigned to.
  36071. */
  36072. void removeKeyPress (const KeyPress& keypress) throw();
  36073. /** Returns true if the given command is linked to this key. */
  36074. bool containsMapping (const CommandID commandID,
  36075. const KeyPress& keyPress) const throw();
  36076. /** Looks for a command that corresponds to a keypress.
  36077. @returns the UID of the command or 0 if none was found
  36078. */
  36079. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  36080. /** Tries to recreate the mappings from a previously stored state.
  36081. The XML passed in must have been created by the createXml() method.
  36082. If the stored state makes any reference to commands that aren't
  36083. currently available, these will be ignored.
  36084. If the set of mappings being loaded was a set of differences (using createXml (true)),
  36085. then this will call resetToDefaultMappings() and then merge the saved mappings
  36086. on top. If the saved set was created with createXml (false), then this method
  36087. will first clear all existing mappings and load the saved ones as a complete set.
  36088. @returns true if it manages to load the XML correctly
  36089. @see createXml
  36090. */
  36091. bool restoreFromXml (const XmlElement& xmlVersion);
  36092. /** Creates an XML representation of the current mappings.
  36093. This will produce a lump of XML that can be later reloaded using
  36094. restoreFromXml() to recreate the current mapping state.
  36095. The object that is returned must be deleted by the caller.
  36096. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  36097. will be saved into the XML. If it's true, then the XML will
  36098. only store the differences between the current mappings and
  36099. the default mappings you'd get from calling resetToDefaultMappings().
  36100. The advantage of saving a set of differences from the default is that
  36101. if you change the default mappings (in a new version of your app, for
  36102. example), then these will be merged into a user's saved preferences.
  36103. @see restoreFromXml
  36104. */
  36105. XmlElement* createXml (const bool saveDifferencesFromDefaultSet) const;
  36106. /** @internal */
  36107. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  36108. /** @internal */
  36109. bool keyStateChanged (const bool isKeyDown, Component* originatingComponent);
  36110. /** @internal */
  36111. void globalFocusChanged (Component* focusedComponent);
  36112. juce_UseDebuggingNewOperator
  36113. private:
  36114. ApplicationCommandManager* commandManager;
  36115. struct CommandMapping
  36116. {
  36117. CommandID commandID;
  36118. Array <KeyPress> keypresses;
  36119. bool wantsKeyUpDownCallbacks;
  36120. };
  36121. OwnedArray <CommandMapping> mappings;
  36122. struct KeyPressTime
  36123. {
  36124. KeyPress key;
  36125. uint32 timeWhenPressed;
  36126. };
  36127. OwnedArray <KeyPressTime> keysDown;
  36128. void handleMessage (const Message& message);
  36129. void invokeCommand (const CommandID commandID,
  36130. const KeyPress& keyPress,
  36131. const bool isKeyDown,
  36132. const int millisecsSinceKeyPressed,
  36133. Component* const originatingComponent) const;
  36134. const KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  36135. };
  36136. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  36137. /********* End of inlined file: juce_KeyPressMappingSet.h *********/
  36138. /**
  36139. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  36140. object.
  36141. @see KeyPressMappingSet
  36142. */
  36143. class JUCE_API KeyMappingEditorComponent : public Component,
  36144. public TreeViewItem,
  36145. public ChangeListener,
  36146. private ButtonListener
  36147. {
  36148. public:
  36149. /** Creates a KeyMappingEditorComponent.
  36150. @param mappingSet this is the set of mappings to display and
  36151. edit. Make sure the mappings object is not
  36152. deleted before this component!
  36153. @param showResetToDefaultButton if true, then at the bottom of the
  36154. list, the component will include a 'reset to
  36155. defaults' button.
  36156. */
  36157. KeyMappingEditorComponent (KeyPressMappingSet* const mappingSet,
  36158. const bool showResetToDefaultButton);
  36159. /** Destructor. */
  36160. virtual ~KeyMappingEditorComponent();
  36161. /** Sets up the colours to use for parts of the component.
  36162. @param mainBackground colour to use for most of the background
  36163. @param textColour colour to use for the text
  36164. */
  36165. void setColours (const Colour& mainBackground,
  36166. const Colour& textColour);
  36167. /** Returns the KeyPressMappingSet that this component is acting upon.
  36168. */
  36169. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  36170. /** Can be overridden if some commands need to be excluded from the list.
  36171. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  36172. method to decide what to return, but you can override it to handle special cases.
  36173. */
  36174. virtual bool shouldCommandBeIncluded (const CommandID commandID);
  36175. /** Can be overridden to indicate that some commands are shown as read-only.
  36176. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  36177. method to decide what to return, but you can override it to handle special cases.
  36178. */
  36179. virtual bool isCommandReadOnly (const CommandID commandID);
  36180. /** This can be overridden to let you change the format of the string used
  36181. to describe a keypress.
  36182. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  36183. keys that are triggered by something else externally. If you override the
  36184. method, be sure to let the base class's method handle keys you're not
  36185. interested in.
  36186. */
  36187. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  36188. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  36189. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36190. methods.
  36191. To change the colours of the menu that pops up
  36192. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36193. */
  36194. enum ColourIds
  36195. {
  36196. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  36197. textColourId = 0x100ad01, /**< The colour for the text. */
  36198. };
  36199. /** @internal */
  36200. void parentHierarchyChanged();
  36201. /** @internal */
  36202. void resized();
  36203. /** @internal */
  36204. void changeListenerCallback (void*);
  36205. /** @internal */
  36206. bool mightContainSubItems();
  36207. /** @internal */
  36208. const String getUniqueName() const;
  36209. /** @internal */
  36210. void buttonClicked (Button* button);
  36211. juce_UseDebuggingNewOperator
  36212. private:
  36213. KeyPressMappingSet* mappings;
  36214. TreeView* tree;
  36215. friend class KeyMappingTreeViewItem;
  36216. friend class KeyCategoryTreeViewItem;
  36217. friend class KeyMappingItemComponent;
  36218. friend class KeyMappingChangeButton;
  36219. TextButton* resetButton;
  36220. void assignNewKey (const CommandID commandID, int index);
  36221. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  36222. const KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  36223. };
  36224. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  36225. /********* End of inlined file: juce_KeyMappingEditorComponent.h *********/
  36226. #endif
  36227. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  36228. #endif
  36229. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  36230. #endif
  36231. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  36232. #endif
  36233. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  36234. #endif
  36235. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36236. #endif
  36237. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36238. /********* Start of inlined file: juce_ComponentMovementWatcher.h *********/
  36239. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36240. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36241. /** An object that watches for any movement of a component or any of its parent components.
  36242. This makes it easy to check when a component is moved relative to its top-level
  36243. peer window. The normal Component::moved() method is only called when a component
  36244. moves relative to its immediate parent, and sometimes you want to know if any of
  36245. components higher up the tree have moved (which of course will affect the overall
  36246. position of all their sub-components).
  36247. It also includes a callback that lets you know when the top-level peer is changed.
  36248. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  36249. because they need to keep their custom windows in the right place and respond to
  36250. changes in the peer.
  36251. */
  36252. class JUCE_API ComponentMovementWatcher : public ComponentListener
  36253. {
  36254. public:
  36255. /** Creates a ComponentMovementWatcher to watch a given target component. */
  36256. ComponentMovementWatcher (Component* const component);
  36257. /** Destructor. */
  36258. ~ComponentMovementWatcher();
  36259. /** This callback happens when the component that is being watched is moved
  36260. relative to its top-level peer window, or when it is resized.
  36261. */
  36262. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  36263. /** This callback happens when the component's top-level peer is changed.
  36264. */
  36265. virtual void componentPeerChanged() = 0;
  36266. juce_UseDebuggingNewOperator
  36267. /** @internal */
  36268. void componentParentHierarchyChanged (Component& component);
  36269. /** @internal */
  36270. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36271. private:
  36272. Component* const component;
  36273. ComponentPeer* lastPeer;
  36274. VoidArray registeredParentComps;
  36275. bool reentrant;
  36276. int lastX, lastY, lastWidth, lastHeight;
  36277. #ifdef JUCE_DEBUG
  36278. ScopedPointer <ComponentDeletionWatcher> deletionWatcher;
  36279. #endif
  36280. void unregister() throw();
  36281. void registerWithParentComps() throw();
  36282. ComponentMovementWatcher (const ComponentMovementWatcher&);
  36283. const ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  36284. };
  36285. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  36286. /********* End of inlined file: juce_ComponentMovementWatcher.h *********/
  36287. #endif
  36288. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36289. /********* Start of inlined file: juce_GroupComponent.h *********/
  36290. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36291. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36292. /**
  36293. A component that draws an outline around itself and has an optional title at
  36294. the top, for drawing an outline around a group of controls.
  36295. */
  36296. class JUCE_API GroupComponent : public Component
  36297. {
  36298. public:
  36299. /** Creates a GroupComponent.
  36300. @param componentName the name to give the component
  36301. @param labelText the text to show at the top of the outline
  36302. */
  36303. GroupComponent (const String& componentName,
  36304. const String& labelText);
  36305. /** Destructor. */
  36306. ~GroupComponent();
  36307. /** Changes the text that's shown at the top of the component. */
  36308. void setText (const String& newText) throw();
  36309. /** Returns the currently displayed text label. */
  36310. const String getText() const throw();
  36311. /** Sets the positioning of the text label.
  36312. (The default is Justification::left)
  36313. @see getTextLabelPosition
  36314. */
  36315. void setTextLabelPosition (const Justification& justification);
  36316. /** Returns the current text label position.
  36317. @see setTextLabelPosition
  36318. */
  36319. const Justification getTextLabelPosition() const throw() { return justification; }
  36320. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36321. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36322. methods.
  36323. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36324. */
  36325. enum ColourIds
  36326. {
  36327. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  36328. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  36329. };
  36330. /** @internal */
  36331. void paint (Graphics& g);
  36332. /** @internal */
  36333. void enablementChanged();
  36334. /** @internal */
  36335. void colourChanged();
  36336. private:
  36337. String text;
  36338. Justification justification;
  36339. GroupComponent (const GroupComponent&);
  36340. const GroupComponent& operator= (const GroupComponent&);
  36341. };
  36342. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  36343. /********* End of inlined file: juce_GroupComponent.h *********/
  36344. #endif
  36345. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36346. /********* Start of inlined file: juce_MultiDocumentPanel.h *********/
  36347. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36348. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  36349. /********* Start of inlined file: juce_TabbedComponent.h *********/
  36350. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36351. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36352. /********* Start of inlined file: juce_TabbedButtonBar.h *********/
  36353. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36354. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36355. class TabbedButtonBar;
  36356. /** In a TabbedButtonBar, this component is used for each of the buttons.
  36357. If you want to create a TabbedButtonBar with custom tab components, derive
  36358. your component from this class, and override the TabbedButtonBar::createTabButton()
  36359. method to create it instead of the default one.
  36360. @see TabbedButtonBar
  36361. */
  36362. class JUCE_API TabBarButton : public Button
  36363. {
  36364. public:
  36365. /** Creates the tab button. */
  36366. TabBarButton (const String& name,
  36367. TabbedButtonBar* const ownerBar,
  36368. const int tabIndex);
  36369. /** Destructor. */
  36370. ~TabBarButton();
  36371. /** Chooses the best length for the tab, given the specified depth.
  36372. If the tab is horizontal, this should return its width, and the depth
  36373. specifies its height. If it's vertical, it should return the height, and
  36374. the depth is actually its width.
  36375. */
  36376. virtual int getBestTabLength (const int depth);
  36377. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  36378. void clicked (const ModifierKeys& mods);
  36379. bool hitTest (int x, int y);
  36380. juce_UseDebuggingNewOperator
  36381. protected:
  36382. friend class TabbedButtonBar;
  36383. TabbedButtonBar* const owner;
  36384. int tabIndex, overlapPixels;
  36385. DropShadowEffect shadow;
  36386. /** Returns an area of the component that's safe to draw in.
  36387. This deals with the orientation of the tabs, which affects which side is
  36388. touching the tabbed box's content component.
  36389. */
  36390. void getActiveArea (int& x, int& y, int& w, int& h);
  36391. private:
  36392. TabBarButton (const TabBarButton&);
  36393. const TabBarButton& operator= (const TabBarButton&);
  36394. };
  36395. /**
  36396. A vertical or horizontal bar containing tabs that you can select.
  36397. You can use one of these to generate things like a dialog box that has
  36398. tabbed pages you can flip between. Attach a ChangeListener to the
  36399. button bar to be told when the user changes the page.
  36400. An easier method than doing this is to use a TabbedComponent, which
  36401. contains its own TabbedButtonBar and which takes care of the layout
  36402. and other housekeeping.
  36403. @see TabbedComponent
  36404. */
  36405. class JUCE_API TabbedButtonBar : public Component,
  36406. public ChangeBroadcaster,
  36407. public ButtonListener
  36408. {
  36409. public:
  36410. /** The placement of the tab-bar
  36411. @see setOrientation, getOrientation
  36412. */
  36413. enum Orientation
  36414. {
  36415. TabsAtTop,
  36416. TabsAtBottom,
  36417. TabsAtLeft,
  36418. TabsAtRight
  36419. };
  36420. /** Creates a TabbedButtonBar with a given placement.
  36421. You can change the orientation later if you need to.
  36422. */
  36423. TabbedButtonBar (const Orientation orientation);
  36424. /** Destructor. */
  36425. ~TabbedButtonBar();
  36426. /** Changes the bar's orientation.
  36427. This won't change the bar's actual size - you'll need to do that yourself,
  36428. but this determines which direction the tabs go in, and which side they're
  36429. stuck to.
  36430. */
  36431. void setOrientation (const Orientation orientation);
  36432. /** Returns the current orientation.
  36433. @see setOrientation
  36434. */
  36435. Orientation getOrientation() const throw() { return orientation; }
  36436. /** Deletes all the tabs from the bar.
  36437. @see addTab
  36438. */
  36439. void clearTabs();
  36440. /** Adds a tab to the bar.
  36441. Tabs are added in left-to-right reading order.
  36442. If this is the first tab added, it'll also be automatically selected.
  36443. */
  36444. void addTab (const String& tabName,
  36445. const Colour& tabBackgroundColour,
  36446. int insertIndex = -1);
  36447. /** Changes the name of one of the tabs. */
  36448. void setTabName (const int tabIndex,
  36449. const String& newName);
  36450. /** Gets rid of one of the tabs. */
  36451. void removeTab (const int tabIndex);
  36452. /** Moves a tab to a new index in the list.
  36453. Pass -1 as the index to move it to the end of the list.
  36454. */
  36455. void moveTab (const int currentIndex,
  36456. const int newIndex);
  36457. /** Returns the number of tabs in the bar. */
  36458. int getNumTabs() const;
  36459. /** Returns a list of all the tab names in the bar. */
  36460. const StringArray getTabNames() const;
  36461. /** Changes the currently selected tab.
  36462. This will send a change message and cause a synchronous callback to
  36463. the currentTabChanged() method. (But if the given tab is already selected,
  36464. nothing will be done).
  36465. To deselect all the tabs, use an index of -1.
  36466. */
  36467. void setCurrentTabIndex (int newTabIndex, const bool sendChangeMessage = true);
  36468. /** Returns the name of the currently selected tab.
  36469. This could be an empty string if none are selected.
  36470. */
  36471. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  36472. /** Returns the index of the currently selected tab.
  36473. This could return -1 if none are selected.
  36474. */
  36475. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  36476. /** Returns the button for a specific tab.
  36477. The button that is returned may be deleted later by this component, so don't hang
  36478. on to the pointer that is returned. A null pointer may be returned if the index is
  36479. out of range.
  36480. */
  36481. TabBarButton* getTabButton (const int index) const;
  36482. /** Callback method to indicate the selected tab has been changed.
  36483. @see setCurrentTabIndex
  36484. */
  36485. virtual void currentTabChanged (const int newCurrentTabIndex,
  36486. const String& newCurrentTabName);
  36487. /** Callback method to indicate that the user has right-clicked on a tab.
  36488. (Or ctrl-clicked on the Mac)
  36489. */
  36490. virtual void popupMenuClickOnTab (const int tabIndex,
  36491. const String& tabName);
  36492. /** Returns the colour of a tab.
  36493. This is the colour that was specified in addTab().
  36494. */
  36495. const Colour getTabBackgroundColour (const int tabIndex);
  36496. /** Changes the background colour of a tab.
  36497. @see addTab, getTabBackgroundColour
  36498. */
  36499. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36500. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36501. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36502. methods.
  36503. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36504. */
  36505. enum ColourIds
  36506. {
  36507. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  36508. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  36509. the look and feel will choose an appropriate colour. */
  36510. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  36511. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  36512. this isn't specified, the look and feel will choose an appropriate
  36513. colour. */
  36514. };
  36515. /** @internal */
  36516. void resized();
  36517. /** @internal */
  36518. void buttonClicked (Button* button);
  36519. /** @internal */
  36520. void lookAndFeelChanged();
  36521. juce_UseDebuggingNewOperator
  36522. protected:
  36523. /** This creates one of the tabs.
  36524. If you need to use custom tab components, you can override this method and
  36525. return your own class instead of the default.
  36526. */
  36527. virtual TabBarButton* createTabButton (const String& tabName,
  36528. const int tabIndex);
  36529. private:
  36530. Orientation orientation;
  36531. StringArray tabs;
  36532. Array <Colour> tabColours;
  36533. int currentTabIndex;
  36534. Component* behindFrontTab;
  36535. Button* extraTabsButton;
  36536. TabbedButtonBar (const TabbedButtonBar&);
  36537. const TabbedButtonBar& operator= (const TabbedButtonBar&);
  36538. };
  36539. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  36540. /********* End of inlined file: juce_TabbedButtonBar.h *********/
  36541. /**
  36542. A component with a TabbedButtonBar along one of its sides.
  36543. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  36544. with addTab(), and this will take care of showing the pages for you when the
  36545. user clicks on a different tab.
  36546. @see TabbedButtonBar
  36547. */
  36548. class JUCE_API TabbedComponent : public Component
  36549. {
  36550. public:
  36551. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  36552. Once created, add some tabs with the addTab() method.
  36553. */
  36554. TabbedComponent (const TabbedButtonBar::Orientation orientation);
  36555. /** Destructor. */
  36556. ~TabbedComponent();
  36557. /** Changes the placement of the tabs.
  36558. This will rearrange the layout to place the tabs along the appropriate
  36559. side of this component, and will shift the content component accordingly.
  36560. @see TabbedButtonBar::setOrientation
  36561. */
  36562. void setOrientation (const TabbedButtonBar::Orientation orientation);
  36563. /** Returns the current tab placement.
  36564. @see setOrientation, TabbedButtonBar::getOrientation
  36565. */
  36566. TabbedButtonBar::Orientation getOrientation() const throw();
  36567. /** Specifies how many pixels wide or high the tab-bar should be.
  36568. If the tabs are placed along the top or bottom, this specified the height
  36569. of the bar; if they're along the left or right edges, it'll be the width
  36570. of the bar.
  36571. */
  36572. void setTabBarDepth (const int newDepth);
  36573. /** Returns the current thickness of the tab bar.
  36574. @see setTabBarDepth
  36575. */
  36576. int getTabBarDepth() const throw() { return tabDepth; }
  36577. /** Specifies the thickness of an outline that should be drawn around the content component.
  36578. If this thickness is > 0, a line will be drawn around the three sides of the content
  36579. component which don't touch the tab-bar, and the content component will be inset by this amount.
  36580. To set the colour of the line, use setColour (outlineColourId, ...).
  36581. */
  36582. void setOutline (const int newThickness);
  36583. /** Specifies a gap to leave around the edge of the content component.
  36584. Each edge of the content component will be indented by the given number of pixels.
  36585. */
  36586. void setIndent (const int indentThickness);
  36587. /** Removes all the tabs from the bar.
  36588. @see TabbedButtonBar::clearTabs
  36589. */
  36590. void clearTabs();
  36591. /** Adds a tab to the tab-bar.
  36592. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  36593. is true, it will be deleted when the tab is removed or when this object is
  36594. deleted.
  36595. @see TabbedButtonBar::addTab
  36596. */
  36597. void addTab (const String& tabName,
  36598. const Colour& tabBackgroundColour,
  36599. Component* const contentComponent,
  36600. const bool deleteComponentWhenNotNeeded,
  36601. const int insertIndex = -1);
  36602. /** Changes the name of one of the tabs. */
  36603. void setTabName (const int tabIndex,
  36604. const String& newName);
  36605. /** Gets rid of one of the tabs. */
  36606. void removeTab (const int tabIndex);
  36607. /** Returns the number of tabs in the bar. */
  36608. int getNumTabs() const;
  36609. /** Returns a list of all the tab names in the bar. */
  36610. const StringArray getTabNames() const;
  36611. /** Returns the content component that was added for the given index.
  36612. Be sure not to use or delete the components that are returned, as this may interfere
  36613. with the TabbedComponent's use of them.
  36614. */
  36615. Component* getTabContentComponent (const int tabIndex) const throw();
  36616. /** Returns the colour of one of the tabs. */
  36617. const Colour getTabBackgroundColour (const int tabIndex) const throw();
  36618. /** Changes the background colour of one of the tabs. */
  36619. void setTabBackgroundColour (const int tabIndex, const Colour& newColour);
  36620. /** Changes the currently-selected tab.
  36621. To deselect all the tabs, pass -1 as the index.
  36622. @see TabbedButtonBar::setCurrentTabIndex
  36623. */
  36624. void setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage = true);
  36625. /** Returns the index of the currently selected tab.
  36626. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  36627. */
  36628. int getCurrentTabIndex() const;
  36629. /** Returns the name of the currently selected tab.
  36630. @see addTab, TabbedButtonBar::getCurrentTabName()
  36631. */
  36632. const String& getCurrentTabName() const;
  36633. /** Returns the current component that's filling the panel.
  36634. This will return 0 if there isn't one.
  36635. */
  36636. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  36637. /** Callback method to indicate the selected tab has been changed.
  36638. @see setCurrentTabIndex
  36639. */
  36640. virtual void currentTabChanged (const int newCurrentTabIndex,
  36641. const String& newCurrentTabName);
  36642. /** Callback method to indicate that the user has right-clicked on a tab.
  36643. (Or ctrl-clicked on the Mac)
  36644. */
  36645. virtual void popupMenuClickOnTab (const int tabIndex,
  36646. const String& tabName);
  36647. /** Returns the tab button bar component that is being used.
  36648. */
  36649. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  36650. /** A set of colour IDs to use to change the colour of various aspects of the component.
  36651. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36652. methods.
  36653. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36654. */
  36655. enum ColourIds
  36656. {
  36657. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  36658. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  36659. (See setOutline) */
  36660. };
  36661. /** @internal */
  36662. void paint (Graphics& g);
  36663. /** @internal */
  36664. void resized();
  36665. /** @internal */
  36666. void lookAndFeelChanged();
  36667. juce_UseDebuggingNewOperator
  36668. protected:
  36669. TabbedButtonBar* tabs;
  36670. /** This creates one of the tab buttons.
  36671. If you need to use custom tab components, you can override this method and
  36672. return your own class instead of the default.
  36673. */
  36674. virtual TabBarButton* createTabButton (const String& tabName,
  36675. const int tabIndex);
  36676. private:
  36677. Array <Component*> contentComponents;
  36678. Component* panelComponent;
  36679. int tabDepth;
  36680. int outlineThickness, edgeIndent;
  36681. friend class TabCompButtonBar;
  36682. void changeCallback (const int newCurrentTabIndex, const String& newTabName);
  36683. TabbedComponent (const TabbedComponent&);
  36684. const TabbedComponent& operator= (const TabbedComponent&);
  36685. };
  36686. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  36687. /********* End of inlined file: juce_TabbedComponent.h *********/
  36688. /********* Start of inlined file: juce_DocumentWindow.h *********/
  36689. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36690. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  36691. /********* Start of inlined file: juce_MenuBarComponent.h *********/
  36692. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  36693. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  36694. /********* Start of inlined file: juce_MenuBarModel.h *********/
  36695. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  36696. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  36697. class MenuBarModel;
  36698. /**
  36699. A class to receive callbacks when a MenuBarModel changes.
  36700. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  36701. */
  36702. class JUCE_API MenuBarModelListener
  36703. {
  36704. public:
  36705. /** Destructor. */
  36706. virtual ~MenuBarModelListener() {}
  36707. /** This callback is made when items are changed in the menu bar model.
  36708. */
  36709. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  36710. /** This callback is made when an application command is invoked that
  36711. is represented by one of the items in the menu bar model.
  36712. */
  36713. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  36714. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  36715. };
  36716. /**
  36717. A class for controlling MenuBar components.
  36718. This class is used to tell a MenuBar what menus to show, and to respond
  36719. to a menu being selected.
  36720. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  36721. */
  36722. class JUCE_API MenuBarModel : private AsyncUpdater,
  36723. private ApplicationCommandManagerListener
  36724. {
  36725. public:
  36726. MenuBarModel() throw();
  36727. /** Destructor. */
  36728. virtual ~MenuBarModel();
  36729. /** Call this when some of your menu items have changed.
  36730. This method will cause a callback to any MenuBarListener objects that
  36731. are registered with this model.
  36732. If this model is displaying items from an ApplicationCommandManager, you
  36733. can use the setApplicationCommandManagerToWatch() method to cause
  36734. change messages to be sent automatically when the ApplicationCommandManager
  36735. is changed.
  36736. @see addListener, removeListener, MenuBarListener
  36737. */
  36738. void menuItemsChanged();
  36739. /** Tells the menu bar to listen to the specified command manager, and to update
  36740. itself when the commands change.
  36741. This will also allow it to flash a menu name when a command from that menu
  36742. is invoked using a keystroke.
  36743. */
  36744. void setApplicationCommandManagerToWatch (ApplicationCommandManager* const manager) throw();
  36745. /** Registers a listener for callbacks when the menu items in this model change.
  36746. The listener object will get callbacks when this object's menuItemsChanged()
  36747. method is called.
  36748. @see removeListener
  36749. */
  36750. void addListener (MenuBarModelListener* const listenerToAdd) throw();
  36751. /** Removes a listener.
  36752. @see addListener
  36753. */
  36754. void removeListener (MenuBarModelListener* const listenerToRemove) throw();
  36755. /** This method must return a list of the names of the menus. */
  36756. virtual const StringArray getMenuBarNames() = 0;
  36757. /** This should return the popup menu to display for a given top-level menu.
  36758. @param topLevelMenuIndex the index of the top-level menu to show
  36759. @param menuName the name of the top-level menu item to show
  36760. */
  36761. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  36762. const String& menuName) = 0;
  36763. /** This is called when a menu item has been clicked on.
  36764. @param menuItemID the item ID of the PopupMenu item that was selected
  36765. @param topLevelMenuIndex the index of the top-level menu from which the item was
  36766. chosen (just in case you've used duplicate ID numbers
  36767. on more than one of the popup menus)
  36768. */
  36769. virtual void menuItemSelected (int menuItemID,
  36770. int topLevelMenuIndex) = 0;
  36771. #if JUCE_MAC || DOXYGEN
  36772. /** MAC ONLY - Sets the model that is currently being shown as the main
  36773. menu bar at the top of the screen on the Mac.
  36774. You can pass 0 to stop the current model being displayed. Be careful
  36775. not to delete a model while it is being used.
  36776. An optional extra menu can be specified, containing items to add to the top of
  36777. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  36778. an apple, it's the one next to it, with your application's name at the top
  36779. and the services menu etc on it). When one of these items is selected, the
  36780. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  36781. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  36782. object then newMenuBarModel must be non-null.
  36783. */
  36784. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  36785. const PopupMenu* extraAppleMenuItems = 0) throw();
  36786. /** MAC ONLY - Returns the menu model that is currently being shown as
  36787. the main menu bar.
  36788. */
  36789. static MenuBarModel* getMacMainMenu() throw();
  36790. #endif
  36791. /** @internal */
  36792. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  36793. /** @internal */
  36794. void applicationCommandListChanged();
  36795. /** @internal */
  36796. void handleAsyncUpdate();
  36797. juce_UseDebuggingNewOperator
  36798. private:
  36799. ApplicationCommandManager* manager;
  36800. SortedSet <void*> listeners;
  36801. MenuBarModel (const MenuBarModel&);
  36802. const MenuBarModel& operator= (const MenuBarModel&);
  36803. };
  36804. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  36805. /********* End of inlined file: juce_MenuBarModel.h *********/
  36806. /**
  36807. A menu bar component.
  36808. @see MenuBarModel
  36809. */
  36810. class JUCE_API MenuBarComponent : public Component,
  36811. private MenuBarModelListener,
  36812. private Timer
  36813. {
  36814. public:
  36815. /** Creates a menu bar.
  36816. @param model the model object to use to control this bar. You can
  36817. pass 0 into this if you like, and set the model later
  36818. using the setModel() method
  36819. */
  36820. MenuBarComponent (MenuBarModel* const model);
  36821. /** Destructor. */
  36822. ~MenuBarComponent();
  36823. /** Changes the model object to use to control the bar.
  36824. This can be 0, in which case the bar will be empty. Don't delete the object
  36825. that is passed-in while it's still being used by this MenuBar.
  36826. */
  36827. void setModel (MenuBarModel* const newModel);
  36828. /** Pops up one of the menu items.
  36829. This lets you manually open one of the menus - it could be triggered by a
  36830. key shortcut, for example.
  36831. */
  36832. void showMenu (const int menuIndex);
  36833. /** @internal */
  36834. void paint (Graphics& g);
  36835. /** @internal */
  36836. void resized();
  36837. /** @internal */
  36838. void mouseEnter (const MouseEvent& e);
  36839. /** @internal */
  36840. void mouseExit (const MouseEvent& e);
  36841. /** @internal */
  36842. void mouseDown (const MouseEvent& e);
  36843. /** @internal */
  36844. void mouseDrag (const MouseEvent& e);
  36845. /** @internal */
  36846. void mouseUp (const MouseEvent& e);
  36847. /** @internal */
  36848. void mouseMove (const MouseEvent& e);
  36849. /** @internal */
  36850. void inputAttemptWhenModal();
  36851. /** @internal */
  36852. void handleCommandMessage (int commandId);
  36853. /** @internal */
  36854. bool keyPressed (const KeyPress& key);
  36855. /** @internal */
  36856. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  36857. /** @internal */
  36858. void menuCommandInvoked (MenuBarModel* menuBarModel,
  36859. const ApplicationCommandTarget::InvocationInfo& info);
  36860. juce_UseDebuggingNewOperator
  36861. private:
  36862. MenuBarModel* model;
  36863. StringArray menuNames;
  36864. Array <int> xPositions;
  36865. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  36866. int lastMouseX, lastMouseY;
  36867. bool inModalState;
  36868. ScopedPointer <Component> currentPopup;
  36869. int getItemAt (int x, int y);
  36870. void updateItemUnderMouse (const int x, const int y);
  36871. void hideCurrentMenu();
  36872. void timerCallback();
  36873. void repaintMenuItem (int index);
  36874. MenuBarComponent (const MenuBarComponent&);
  36875. const MenuBarComponent& operator= (const MenuBarComponent&);
  36876. };
  36877. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  36878. /********* End of inlined file: juce_MenuBarComponent.h *********/
  36879. /**
  36880. A resizable window with a title bar and maximise, minimise and close buttons.
  36881. This subclass of ResizableWindow creates a fairly standard type of window with
  36882. a title bar and various buttons. The name of the component is shown in the
  36883. title bar, and an icon can optionally be specified with setIcon().
  36884. All the methods available to a ResizableWindow are also available to this,
  36885. so it can easily be made resizable, minimised, maximised, etc.
  36886. It's not advisable to add child components directly to a DocumentWindow: put them
  36887. inside your content component instead. And overriding methods like resized(), moved(), etc
  36888. is also not recommended - instead override these methods for your content component.
  36889. (If for some obscure reason you do need to override these methods, always remember to
  36890. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36891. decorations correctly).
  36892. You can also automatically add a menu bar to the window, using the setMenuBar()
  36893. method.
  36894. @see ResizableWindow, DialogWindow
  36895. */
  36896. class JUCE_API DocumentWindow : public ResizableWindow
  36897. {
  36898. public:
  36899. /** The set of available button-types that can be put on the title bar.
  36900. @see setTitleBarButtonsRequired
  36901. */
  36902. enum TitleBarButtons
  36903. {
  36904. minimiseButton = 1,
  36905. maximiseButton = 2,
  36906. closeButton = 4,
  36907. /** A combination of all the buttons above. */
  36908. allButtons = 7
  36909. };
  36910. /** Creates a DocumentWindow.
  36911. @param name the name to give the component - this is also
  36912. the title shown at the top of the window. To change
  36913. this later, use setName()
  36914. @param backgroundColour the colour to use for filling the window's background.
  36915. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36916. should be shown on the title bar. This value is a bitwise
  36917. combination of values from the TitleBarButtons enum. Note
  36918. that it can be "allButtons" to get them all. You
  36919. can change this later with the setTitleBarButtonsRequired()
  36920. method, which can also specify where they are positioned.
  36921. @param addToDesktop if true, the window will be automatically added to the
  36922. desktop; if false, you can use it as a child component
  36923. @see TitleBarButtons
  36924. */
  36925. DocumentWindow (const String& name,
  36926. const Colour& backgroundColour,
  36927. const int requiredButtons,
  36928. const bool addToDesktop = true);
  36929. /** Destructor.
  36930. If a content component has been set with setContentComponent(), it
  36931. will be deleted.
  36932. */
  36933. ~DocumentWindow();
  36934. /** Changes the component's name.
  36935. (This is overridden from Component::setName() to cause a repaint, as
  36936. the name is what gets drawn across the window's title bar).
  36937. */
  36938. void setName (const String& newName);
  36939. /** Sets an icon to show in the title bar, next to the title.
  36940. A copy is made internally of the image, so the caller can delete the
  36941. image after calling this. If 0 is passed-in, any existing icon will be
  36942. removed.
  36943. */
  36944. void setIcon (const Image* imageToUse);
  36945. /** Changes the height of the title-bar. */
  36946. void setTitleBarHeight (const int newHeight);
  36947. /** Returns the current title bar height. */
  36948. int getTitleBarHeight() const;
  36949. /** Changes the set of title-bar buttons being shown.
  36950. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  36951. should be shown on the title bar. This value is a bitwise
  36952. combination of values from the TitleBarButtons enum. Note
  36953. that it can be "allButtons" to get them all.
  36954. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  36955. left side of the bar; if false, they'll be placed at the right
  36956. */
  36957. void setTitleBarButtonsRequired (const int requiredButtons,
  36958. const bool positionTitleBarButtonsOnLeft);
  36959. /** Sets whether the title should be centred within the window.
  36960. If true, the title text is shown in the middle of the title-bar; if false,
  36961. it'll be shown at the left of the bar.
  36962. */
  36963. void setTitleBarTextCentred (const bool textShouldBeCentred);
  36964. /** Creates a menu inside this window.
  36965. @param menuBarModel this specifies a MenuBarModel that should be used to
  36966. generate the contents of a menu bar that will be placed
  36967. just below the title bar, and just above any content
  36968. component. If this value is zero, any existing menu bar
  36969. will be removed from the component; if non-zero, one will
  36970. be added if it's required.
  36971. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  36972. or less to use the look-and-feel's default size.
  36973. */
  36974. void setMenuBar (MenuBarModel* menuBarModel,
  36975. const int menuBarHeight = 0);
  36976. /** This method is called when the user tries to close the window.
  36977. This is triggered by the user clicking the close button, or using some other
  36978. OS-specific key shortcut or OS menu for getting rid of a window.
  36979. If the window is just a pop-up, you should override this closeButtonPressed()
  36980. method and make it delete the window in whatever way is appropriate for your
  36981. app. E.g. you might just want to call "delete this".
  36982. If your app is centred around this window such that the whole app should quit when
  36983. the window is closed, then you will probably want to use this method as an opportunity
  36984. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  36985. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  36986. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  36987. or closing it via the taskbar icon on Windows).
  36988. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  36989. redirects it to call this method, so any methods of closing the window that are
  36990. caught by userTriedToCloseWindow() will also end up here).
  36991. */
  36992. virtual void closeButtonPressed();
  36993. /** Callback that is triggered when the minimise button is pressed.
  36994. The default implementation of this calls ResizableWindow::setMinimised(), but
  36995. you can override it to do more customised behaviour.
  36996. */
  36997. virtual void minimiseButtonPressed();
  36998. /** Callback that is triggered when the maximise button is pressed, or when the
  36999. title-bar is double-clicked.
  37000. The default implementation of this calls ResizableWindow::setFullScreen(), but
  37001. you can override it to do more customised behaviour.
  37002. */
  37003. virtual void maximiseButtonPressed();
  37004. /** Returns the close button, (or 0 if there isn't one). */
  37005. Button* getCloseButton() const throw();
  37006. /** Returns the minimise button, (or 0 if there isn't one). */
  37007. Button* getMinimiseButton() const throw();
  37008. /** Returns the maximise button, (or 0 if there isn't one). */
  37009. Button* getMaximiseButton() const throw();
  37010. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37011. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37012. methods.
  37013. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37014. */
  37015. enum ColourIds
  37016. {
  37017. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  37018. and feel class how this is used. */
  37019. };
  37020. /** @internal */
  37021. void paint (Graphics& g);
  37022. /** @internal */
  37023. void resized();
  37024. /** @internal */
  37025. void lookAndFeelChanged();
  37026. /** @internal */
  37027. const BorderSize getBorderThickness();
  37028. /** @internal */
  37029. const BorderSize getContentComponentBorder();
  37030. /** @internal */
  37031. void mouseDoubleClick (const MouseEvent& e);
  37032. /** @internal */
  37033. void userTriedToCloseWindow();
  37034. /** @internal */
  37035. void activeWindowStatusChanged();
  37036. /** @internal */
  37037. int getDesktopWindowStyleFlags() const;
  37038. /** @internal */
  37039. void parentHierarchyChanged();
  37040. /** @internal */
  37041. const Rectangle getTitleBarArea();
  37042. juce_UseDebuggingNewOperator
  37043. private:
  37044. int titleBarHeight, menuBarHeight, requiredButtons;
  37045. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  37046. ScopedPointer <Button> titleBarButtons [3];
  37047. ScopedPointer <Image> titleBarIcon;
  37048. ScopedPointer <MenuBarComponent> menuBar;
  37049. MenuBarModel* menuBarModel;
  37050. class ButtonListenerProxy : public ButtonListener
  37051. {
  37052. public:
  37053. ButtonListenerProxy();
  37054. void buttonClicked (Button* button);
  37055. DocumentWindow* owner;
  37056. } buttonListener;
  37057. void repaintTitleBar();
  37058. DocumentWindow (const DocumentWindow&);
  37059. const DocumentWindow& operator= (const DocumentWindow&);
  37060. };
  37061. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  37062. /********* End of inlined file: juce_DocumentWindow.h *********/
  37063. class MultiDocumentPanel;
  37064. class MDITabbedComponentInternal;
  37065. /**
  37066. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  37067. component.
  37068. It's like a normal DocumentWindow but has some extra functionality to make sure
  37069. everything works nicely inside a MultiDocumentPanel.
  37070. @see MultiDocumentPanel
  37071. */
  37072. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  37073. {
  37074. public:
  37075. /**
  37076. */
  37077. MultiDocumentPanelWindow (const Colour& backgroundColour);
  37078. /** Destructor. */
  37079. ~MultiDocumentPanelWindow();
  37080. /** @internal */
  37081. void maximiseButtonPressed();
  37082. /** @internal */
  37083. void closeButtonPressed();
  37084. /** @internal */
  37085. void activeWindowStatusChanged();
  37086. /** @internal */
  37087. void broughtToFront();
  37088. juce_UseDebuggingNewOperator
  37089. private:
  37090. void updateOrder();
  37091. MultiDocumentPanel* getOwner() const throw();
  37092. };
  37093. /**
  37094. A component that contains a set of other components either in floating windows
  37095. or tabs.
  37096. This acts as a panel that can be used to hold a set of open document windows, with
  37097. different layout modes.
  37098. Use addDocument() and closeDocument() to add or remove components from the
  37099. panel - never use any of the Component methods to access the panel's child
  37100. components directly, as these are managed internally.
  37101. */
  37102. class JUCE_API MultiDocumentPanel : public Component,
  37103. private ComponentListener
  37104. {
  37105. public:
  37106. /** Creates an empty panel.
  37107. Use addDocument() and closeDocument() to add or remove components from the
  37108. panel - never use any of the Component methods to access the panel's child
  37109. components directly, as these are managed internally.
  37110. */
  37111. MultiDocumentPanel();
  37112. /** Destructor.
  37113. When deleted, this will call closeAllDocuments (false) to make sure all its
  37114. components are deleted. If you need to make sure all documents are saved
  37115. before closing, then you should call closeAllDocuments (true) and check that
  37116. it returns true before deleting the panel.
  37117. */
  37118. ~MultiDocumentPanel();
  37119. /** Tries to close all the documents.
  37120. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  37121. be called for each open document, and any of these calls fails, this method
  37122. will stop and return false, leaving some documents still open.
  37123. If checkItsOkToCloseFirst is false, then all documents will be closed
  37124. unconditionally.
  37125. @see closeDocument
  37126. */
  37127. bool closeAllDocuments (const bool checkItsOkToCloseFirst);
  37128. /** Adds a document component to the panel.
  37129. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  37130. this will fail and return false. (If it does fail, the component passed-in will not be
  37131. deleted, even if deleteWhenRemoved was set to true).
  37132. The MultiDocumentPanel will deal with creating a window border to go around your component,
  37133. so just pass in the bare content component here, no need to give it a ResizableWindow
  37134. or DocumentWindow.
  37135. @param component the component to add
  37136. @param backgroundColour the background colour to use to fill the component's
  37137. window or tab
  37138. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  37139. or closeAllDocuments(), then it will be deleted. If false, then
  37140. the caller must handle the component's deletion
  37141. */
  37142. bool addDocument (Component* const component,
  37143. const Colour& backgroundColour,
  37144. const bool deleteWhenRemoved);
  37145. /** Closes one of the documents.
  37146. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  37147. be called, and if it fails, this method will return false without closing the
  37148. document.
  37149. If checkItsOkToCloseFirst is false, then the documents will be closed
  37150. unconditionally.
  37151. The component will be deleted if the deleteWhenRemoved parameter was set to
  37152. true when it was added with addDocument.
  37153. @see addDocument, closeAllDocuments
  37154. */
  37155. bool closeDocument (Component* component,
  37156. const bool checkItsOkToCloseFirst);
  37157. /** Returns the number of open document windows.
  37158. @see getDocument
  37159. */
  37160. int getNumDocuments() const throw();
  37161. /** Returns one of the open documents.
  37162. The order of the documents in this array may change when they are added, removed
  37163. or moved around.
  37164. @see getNumDocuments
  37165. */
  37166. Component* getDocument (const int index) const throw();
  37167. /** Returns the document component that is currently focused or on top.
  37168. If currently using floating windows, then this will be the component in the currently
  37169. active window, or the top component if none are active.
  37170. If it's currently in tabbed mode, then it'll return the component in the active tab.
  37171. @see setActiveDocument
  37172. */
  37173. Component* getActiveDocument() const throw();
  37174. /** Makes one of the components active and brings it to the top.
  37175. @see getActiveDocument
  37176. */
  37177. void setActiveDocument (Component* component);
  37178. /** Callback which gets invoked when the currently-active document changes. */
  37179. virtual void activeDocumentChanged();
  37180. /** Sets a limit on how many windows can be open at once.
  37181. If this is zero or less there's no limit (the default). addDocument() will fail
  37182. if this number is exceeded.
  37183. */
  37184. void setMaximumNumDocuments (const int maximumNumDocuments);
  37185. /** Sets an option to make the document fullscreen if there's only one document open.
  37186. If set to true, then if there's only one document, it'll fill the whole of this
  37187. component without tabs or a window border. If false, then tabs or a window
  37188. will always be shown, even if there's only one document. If there's more than
  37189. one document open, then this option makes no difference.
  37190. */
  37191. void useFullscreenWhenOneDocument (const bool shouldUseTabs);
  37192. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  37193. */
  37194. bool isFullscreenWhenOneDocument() const throw();
  37195. /** The different layout modes available. */
  37196. enum LayoutMode
  37197. {
  37198. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  37199. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  37200. };
  37201. /** Changes the panel's mode.
  37202. @see LayoutMode, getLayoutMode
  37203. */
  37204. void setLayoutMode (const LayoutMode newLayoutMode);
  37205. /** Returns the current layout mode. */
  37206. LayoutMode getLayoutMode() const throw() { return mode; }
  37207. /** Sets the background colour for the whole panel.
  37208. Each document has its own background colour, but this is the one used to fill the areas
  37209. behind them.
  37210. */
  37211. void setBackgroundColour (const Colour& newBackgroundColour);
  37212. /** Returns the current background colour.
  37213. @see setBackgroundColour
  37214. */
  37215. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  37216. /** A subclass must override this to say whether its currently ok for a document
  37217. to be closed.
  37218. This method is called by closeDocument() and closeAllDocuments() to indicate that
  37219. a document should be saved if possible, ready for it to be closed.
  37220. If this method returns true, then it means the document is ok and can be closed.
  37221. If it returns false, then it means that the closeDocument() method should stop
  37222. and not close.
  37223. Normally, you'd use this method to ask the user if they want to save any changes,
  37224. then return true if the save operation went ok. If the user cancelled the save
  37225. operation you could return false here to abort the close operation.
  37226. If your component is based on the FileBasedDocument class, then you'd probably want
  37227. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  37228. FileBasedDocument::savedOk
  37229. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  37230. */
  37231. virtual bool tryToCloseDocument (Component* component) = 0;
  37232. /** Creates a new window to be used for a document.
  37233. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  37234. but you might want to override it to return a custom component.
  37235. */
  37236. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  37237. /** @internal */
  37238. void paint (Graphics& g);
  37239. /** @internal */
  37240. void resized();
  37241. /** @internal */
  37242. void componentNameChanged (Component&);
  37243. juce_UseDebuggingNewOperator
  37244. private:
  37245. LayoutMode mode;
  37246. Array <Component*> components;
  37247. TabbedComponent* tabComponent;
  37248. Colour backgroundColour;
  37249. int maximumNumDocuments, numDocsBeforeTabsUsed;
  37250. friend class MultiDocumentPanelWindow;
  37251. friend class MDITabbedComponentInternal;
  37252. Component* getContainerComp (Component* c) const;
  37253. void updateOrder();
  37254. void addWindow (Component* component);
  37255. };
  37256. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  37257. /********* End of inlined file: juce_MultiDocumentPanel.h *********/
  37258. #endif
  37259. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37260. #endif
  37261. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37262. #endif
  37263. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  37264. #endif
  37265. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37266. /********* Start of inlined file: juce_StretchableLayoutManager.h *********/
  37267. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37268. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37269. /**
  37270. For laying out a set of components, where the components have preferred sizes
  37271. and size limits, but where they are allowed to stretch to fill the available
  37272. space.
  37273. For example, if you have a component containing several other components, and
  37274. each one should be given a share of the total size, you could use one of these
  37275. to resize the child components when the parent component is resized. Then
  37276. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  37277. A StretchableLayoutManager operates only in one dimension, so if you have a set
  37278. of components stacked vertically on top of each other, you'd use one to manage their
  37279. heights. To build up complex arrangements of components, e.g. for applications
  37280. with multiple nested panels, you would use more than one StretchableLayoutManager.
  37281. E.g. by using two (one vertical, one horizontal), you could create a resizable
  37282. spreadsheet-style table.
  37283. E.g.
  37284. @code
  37285. class MyComp : public Component
  37286. {
  37287. StretchableLayoutManager myLayout;
  37288. MyComp()
  37289. {
  37290. myLayout.setItemLayout (0, // for item 0
  37291. 50, 100, // must be between 50 and 100 pixels in size
  37292. -0.6); // and its preferred size is 60% of the total available space
  37293. myLayout.setItemLayout (1, // for item 1
  37294. -0.2, -0.6, // size must be between 20% and 60% of the available space
  37295. 50); // and its preferred size is 50 pixels
  37296. }
  37297. void resized()
  37298. {
  37299. // make a list of two of our child components that we want to reposition
  37300. Component* comps[] = { myComp1, myComp2 };
  37301. // this will position the 2 components, one above the other, to fit
  37302. // vertically into the rectangle provided.
  37303. myLayout.layOutComponents (comps, 2,
  37304. 0, 0, getWidth(), getHeight(),
  37305. true);
  37306. }
  37307. };
  37308. @endcode
  37309. @see StretchableLayoutResizerBar
  37310. */
  37311. class JUCE_API StretchableLayoutManager
  37312. {
  37313. public:
  37314. /** Creates an empty layout.
  37315. You'll need to add some item properties to the layout before it can be used
  37316. to resize things - see setItemLayout().
  37317. */
  37318. StretchableLayoutManager();
  37319. /** Destructor. */
  37320. ~StretchableLayoutManager();
  37321. /** For a numbered item, this sets its size limits and preferred size.
  37322. @param itemIndex the index of the item to change.
  37323. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37324. indicates an absolute size in pixels. A negative number indicates a
  37325. proportion of the available space (e.g -0.5 is 50%)
  37326. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37327. indicates an absolute size in pixels. A negative number indicates a
  37328. proportion of the available space
  37329. @param preferredSize the size that this item would like to be, if there's enough room. A
  37330. positive number indicates an absolute size in pixels. A negative number
  37331. indicates a proportion of the available space
  37332. @see getItemLayout
  37333. */
  37334. void setItemLayout (const int itemIndex,
  37335. const double minimumSize,
  37336. const double maximumSize,
  37337. const double preferredSize);
  37338. /** For a numbered item, this returns its size limits and preferred size.
  37339. @param itemIndex the index of the item.
  37340. @param minimumSize the minimum size that this item is allowed to be - a positive number
  37341. indicates an absolute size in pixels. A negative number indicates a
  37342. proportion of the available space (e.g -0.5 is 50%)
  37343. @param maximumSize the maximum size that this item is allowed to be - a positive number
  37344. indicates an absolute size in pixels. A negative number indicates a
  37345. proportion of the available space
  37346. @param preferredSize the size that this item would like to be, if there's enough room. A
  37347. positive number indicates an absolute size in pixels. A negative number
  37348. indicates a proportion of the available space
  37349. @returns false if the item's properties hadn't been set
  37350. @see setItemLayout
  37351. */
  37352. bool getItemLayout (const int itemIndex,
  37353. double& minimumSize,
  37354. double& maximumSize,
  37355. double& preferredSize) const;
  37356. /** Clears all the properties that have been set with setItemLayout() and resets
  37357. this object to its initial state.
  37358. */
  37359. void clearAllItems();
  37360. /** Takes a set of components that correspond to the layout's items, and positions
  37361. them to fill a space.
  37362. This will try to give each item its preferred size, whether that's a relative size
  37363. or an absolute one.
  37364. @param components an array of components that correspond to each of the
  37365. numbered items that the StretchableLayoutManager object
  37366. has been told about with setItemLayout()
  37367. @param numComponents the number of components in the array that is passed-in. This
  37368. should be the same as the number of items this object has been
  37369. told about.
  37370. @param x the left of the rectangle in which the components should
  37371. be laid out
  37372. @param y the top of the rectangle in which the components should
  37373. be laid out
  37374. @param width the width of the rectangle in which the components should
  37375. be laid out
  37376. @param height the height of the rectangle in which the components should
  37377. be laid out
  37378. @param vertically if true, the components will be positioned in a vertical stack,
  37379. so that they fill the height of the rectangle. If false, they
  37380. will be placed side-by-side in a horizontal line, filling the
  37381. available width
  37382. @param resizeOtherDimension if true, this means that the components will have their
  37383. other dimension resized to fit the space - i.e. if the 'vertically'
  37384. parameter is true, their x-positions and widths are adjusted to fit
  37385. the x and width parameters; if 'vertically' is false, their y-positions
  37386. and heights are adjusted to fit the y and height parameters.
  37387. */
  37388. void layOutComponents (Component** const components,
  37389. int numComponents,
  37390. int x, int y, int width, int height,
  37391. const bool vertically,
  37392. const bool resizeOtherDimension);
  37393. /** Returns the current position of one of the items.
  37394. This is only a valid call after layOutComponents() has been called, as it
  37395. returns the last position that this item was placed at. If the layout was
  37396. vertical, the value returned will be the y position of the top of the item,
  37397. relative to the top of the rectangle in which the items were placed (so for
  37398. example, item 0 will always have position of 0, even in the rectangle passed
  37399. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  37400. the position returned is the item's left-hand position, again relative to the
  37401. x position of the rectangle used.
  37402. @see getItemCurrentSize, setItemPosition
  37403. */
  37404. int getItemCurrentPosition (const int itemIndex) const;
  37405. /** Returns the current size of one of the items.
  37406. This is only meaningful after layOutComponents() has been called, as it
  37407. returns the last size that this item was given. If the layout was done
  37408. vertically, it'll return the item's height in pixels; if it was horizontal,
  37409. it'll return its width.
  37410. @see getItemCurrentRelativeSize
  37411. */
  37412. int getItemCurrentAbsoluteSize (const int itemIndex) const;
  37413. /** Returns the current size of one of the items.
  37414. This is only meaningful after layOutComponents() has been called, as it
  37415. returns the last size that this item was given. If the layout was done
  37416. vertically, it'll return a negative value representing the item's height relative
  37417. to the last size used for laying the components out; if the layout was done
  37418. horizontally it'll be the proportion of its width.
  37419. @see getItemCurrentAbsoluteSize
  37420. */
  37421. double getItemCurrentRelativeSize (const int itemIndex) const;
  37422. /** Moves one of the items, shifting along any other items as necessary in
  37423. order to get it to the desired position.
  37424. Calling this method will also update the preferred sizes of the items it
  37425. shuffles along, so that they reflect their new positions.
  37426. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  37427. about when it's dragged).
  37428. @param itemIndex the item to move
  37429. @param newPosition the absolute position that you'd like this item to move
  37430. to. The item might not be able to always reach exactly this position,
  37431. because other items may have minimum sizes that constrain how
  37432. far it can go
  37433. */
  37434. void setItemPosition (const int itemIndex,
  37435. int newPosition);
  37436. juce_UseDebuggingNewOperator
  37437. private:
  37438. struct ItemLayoutProperties
  37439. {
  37440. int itemIndex;
  37441. int currentSize;
  37442. double minSize, maxSize, preferredSize;
  37443. };
  37444. OwnedArray <ItemLayoutProperties> items;
  37445. int totalSize;
  37446. static int sizeToRealSize (double size, int totalSpace);
  37447. ItemLayoutProperties* getInfoFor (const int itemIndex) const;
  37448. void setTotalSize (const int newTotalSize);
  37449. int fitComponentsIntoSpace (const int startIndex,
  37450. const int endIndex,
  37451. const int availableSpace,
  37452. int startPos);
  37453. int getMinimumSizeOfItems (const int startIndex, const int endIndex) const;
  37454. int getMaximumSizeOfItems (const int startIndex, const int endIndex) const;
  37455. void updatePrefSizesToMatchCurrentPositions();
  37456. StretchableLayoutManager (const StretchableLayoutManager&);
  37457. const StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  37458. };
  37459. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  37460. /********* End of inlined file: juce_StretchableLayoutManager.h *********/
  37461. #endif
  37462. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37463. /********* Start of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37464. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37465. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37466. /**
  37467. A component that acts as one of the vertical or horizontal bars you see being
  37468. used to resize panels in a window.
  37469. One of these acts with a StretchableLayoutManager to resize the other components.
  37470. @see StretchableLayoutManager
  37471. */
  37472. class JUCE_API StretchableLayoutResizerBar : public Component
  37473. {
  37474. public:
  37475. /** Creates a resizer bar for use on a specified layout.
  37476. @param layoutToUse the layout that will be affected when this bar
  37477. is dragged
  37478. @param itemIndexInLayout the item index in the layout that corresponds to
  37479. this bar component. You'll need to set up the item
  37480. properties in a suitable way for a divider bar, e.g.
  37481. for an 8-pixel wide bar which, you could call
  37482. myLayout->setItemLayout (barIndex, 8, 8, 8)
  37483. @param isBarVertical true if it's an upright bar that you drag left and
  37484. right; false for a horizontal one that you drag up and
  37485. down
  37486. */
  37487. StretchableLayoutResizerBar (StretchableLayoutManager* const layoutToUse,
  37488. const int itemIndexInLayout,
  37489. const bool isBarVertical);
  37490. /** Destructor. */
  37491. ~StretchableLayoutResizerBar();
  37492. /** This is called when the bar is dragged.
  37493. This method must update the positions of any components whose position is
  37494. determined by the StretchableLayoutManager, because they might have just
  37495. moved.
  37496. The default implementation calls the resized() method of this component's
  37497. parent component, because that's often where you're likely to apply the
  37498. layout, but it can be overridden for more specific needs.
  37499. */
  37500. virtual void hasBeenMoved();
  37501. /** @internal */
  37502. void paint (Graphics& g);
  37503. /** @internal */
  37504. void mouseDown (const MouseEvent& e);
  37505. /** @internal */
  37506. void mouseDrag (const MouseEvent& e);
  37507. juce_UseDebuggingNewOperator
  37508. private:
  37509. StretchableLayoutManager* layout;
  37510. int itemIndex, mouseDownPos;
  37511. bool isVertical;
  37512. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  37513. const StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  37514. };
  37515. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  37516. /********* End of inlined file: juce_StretchableLayoutResizerBar.h *********/
  37517. #endif
  37518. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37519. /********* Start of inlined file: juce_StretchableObjectResizer.h *********/
  37520. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37521. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37522. /**
  37523. A utility class for fitting a set of objects whose sizes can vary between
  37524. a minimum and maximum size, into a space.
  37525. This is a trickier algorithm than it would first seem, so I've put it in this
  37526. class to allow it to be shared by various bits of code.
  37527. To use it, create one of these objects, call addItem() to add the list of items
  37528. you need, then call resizeToFit(), which will change all their sizes. You can
  37529. then retrieve the new sizes with getItemSize() and getNumItems().
  37530. It's currently used by the TableHeaderComponent for stretching out the table
  37531. headings to fill the table's width.
  37532. */
  37533. class StretchableObjectResizer
  37534. {
  37535. public:
  37536. /** Creates an empty object resizer. */
  37537. StretchableObjectResizer();
  37538. /** Destructor. */
  37539. ~StretchableObjectResizer();
  37540. /** Adds an item to the list.
  37541. The order parameter lets you specify groups of items that are resized first when some
  37542. space needs to be found. Those items with an order of 0 will be the first ones to be
  37543. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  37544. will then try resizing the items with an order of 1, then 2, and so on.
  37545. */
  37546. void addItem (const double currentSize,
  37547. const double minSize,
  37548. const double maxSize,
  37549. const int order = 0);
  37550. /** Resizes all the items to fit this amount of space.
  37551. This will attempt to fit them in without exceeding each item's miniumum and
  37552. maximum sizes. In cases where none of the items can be expanded or enlarged any
  37553. further, the final size may be greater or less than the size passed in.
  37554. After calling this method, you can retrieve the new sizes with the getItemSize()
  37555. method.
  37556. */
  37557. void resizeToFit (const double targetSize);
  37558. /** Returns the number of items that have been added. */
  37559. int getNumItems() const throw() { return items.size(); }
  37560. /** Returns the size of one of the items. */
  37561. double getItemSize (const int index) const throw();
  37562. juce_UseDebuggingNewOperator
  37563. private:
  37564. struct Item
  37565. {
  37566. double size;
  37567. double minSize;
  37568. double maxSize;
  37569. int order;
  37570. };
  37571. OwnedArray <Item> items;
  37572. StretchableObjectResizer (const StretchableObjectResizer&);
  37573. const StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  37574. };
  37575. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  37576. /********* End of inlined file: juce_StretchableObjectResizer.h *********/
  37577. #endif
  37578. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  37579. #endif
  37580. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  37581. #endif
  37582. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  37583. #endif
  37584. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  37585. /********* Start of inlined file: juce_LookAndFeel.h *********/
  37586. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  37587. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  37588. /********* Start of inlined file: juce_AlertWindow.h *********/
  37589. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  37590. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  37591. /********* Start of inlined file: juce_TextLayout.h *********/
  37592. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  37593. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  37594. class Graphics;
  37595. /**
  37596. A laid-out arrangement of text.
  37597. You can add text in different fonts to a TextLayout object, then call its
  37598. layout() method to word-wrap it into lines. The layout can then be drawn
  37599. using a graphics context.
  37600. It's handy if you've got a message to display, because you can format it,
  37601. measure the extent of the layout, and then create a suitably-sized window
  37602. to show it in.
  37603. @see Font, Graphics::drawFittedText, GlyphArrangement
  37604. */
  37605. class JUCE_API TextLayout
  37606. {
  37607. public:
  37608. /** Creates an empty text layout.
  37609. Text can then be appended using the appendText() method.
  37610. */
  37611. TextLayout() throw();
  37612. /** Creates a copy of another layout object. */
  37613. TextLayout (const TextLayout& other) throw();
  37614. /** Creates a text layout from an initial string and font. */
  37615. TextLayout (const String& text, const Font& font) throw();
  37616. /** Destructor. */
  37617. ~TextLayout() throw();
  37618. /** Copies another layout onto this one. */
  37619. const TextLayout& operator= (const TextLayout& layoutToCopy) throw();
  37620. /** Clears the layout, removing all its text. */
  37621. void clear() throw();
  37622. /** Adds a string to the end of the arrangement.
  37623. The string will be broken onto new lines wherever it contains
  37624. carriage-returns or linefeeds. After adding it, you can call layout()
  37625. to wrap long lines into a paragraph and justify it.
  37626. */
  37627. void appendText (const String& textToAppend,
  37628. const Font& fontToUse) throw();
  37629. /** Replaces all the text with a new string.
  37630. This is equivalent to calling clear() followed by appendText().
  37631. */
  37632. void setText (const String& newText,
  37633. const Font& fontToUse) throw();
  37634. /** Breaks the text up to form a paragraph with the given width.
  37635. @param maximumWidth any text wider than this will be split
  37636. across multiple lines
  37637. @param justification how the lines are to be laid-out horizontally
  37638. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  37639. width that keeps all the lines of text at a
  37640. similar length - this is good when you're displaying
  37641. a short message and don't want it to get split
  37642. onto two lines with only a couple of words on
  37643. the second line, which looks untidy.
  37644. */
  37645. void layout (int maximumWidth,
  37646. const Justification& justification,
  37647. const bool attemptToBalanceLineLengths) throw();
  37648. /** Returns the overall width of the entire text layout. */
  37649. int getWidth() const throw();
  37650. /** Returns the overall height of the entire text layout. */
  37651. int getHeight() const throw();
  37652. /** Returns the total number of lines of text. */
  37653. int getNumLines() const throw() { return totalLines; }
  37654. /** Returns the width of a particular line of text.
  37655. @param lineNumber the line, from 0 to (getNumLines() - 1)
  37656. */
  37657. int getLineWidth (const int lineNumber) const throw();
  37658. /** Renders the text at a specified position using a graphics context.
  37659. */
  37660. void draw (Graphics& g,
  37661. const int topLeftX,
  37662. const int topLeftY) const throw();
  37663. /** Renders the text within a specified rectangle using a graphics context.
  37664. The justification flags dictate how the block of text should be positioned
  37665. within the rectangle.
  37666. */
  37667. void drawWithin (Graphics& g,
  37668. int x, int y, int w, int h,
  37669. const Justification& layoutFlags) const throw();
  37670. juce_UseDebuggingNewOperator
  37671. private:
  37672. VoidArray tokens;
  37673. int totalLines;
  37674. };
  37675. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  37676. /********* End of inlined file: juce_TextLayout.h *********/
  37677. /** A window that displays a message and has buttons for the user to react to it.
  37678. For simple dialog boxes with just a couple of buttons on them, there are
  37679. some static methods for running these.
  37680. For more complex dialogs, an AlertWindow can be created, then it can have some
  37681. buttons and components added to it, and its runModalLoop() method is then used to
  37682. show it. The value returned by runModalLoop() shows which button the
  37683. user pressed to dismiss the box.
  37684. @see ThreadWithProgressWindow
  37685. */
  37686. class JUCE_API AlertWindow : public TopLevelWindow,
  37687. private ButtonListener
  37688. {
  37689. public:
  37690. /** The type of icon to show in the dialog box. */
  37691. enum AlertIconType
  37692. {
  37693. NoIcon, /**< No icon will be shown on the dialog box. */
  37694. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  37695. user to answer a question. */
  37696. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  37697. warning about something and shouldn't be ignored. */
  37698. InfoIcon /**< An icon that indicates that the dialog box is just
  37699. giving the user some information, which doesn't require
  37700. a response from them. */
  37701. };
  37702. /** Creates an AlertWindow.
  37703. @param title the headline to show at the top of the dialog box
  37704. @param message a longer, more descriptive message to show underneath the
  37705. headline
  37706. @param iconType the type of icon to display
  37707. @param associatedComponent if this is non-zero, it specifies the component that the
  37708. alert window should be associated with. Depending on the look
  37709. and feel, this might be used for positioning of the alert window.
  37710. */
  37711. AlertWindow (const String& title,
  37712. const String& message,
  37713. AlertIconType iconType,
  37714. Component* associatedComponent = 0);
  37715. /** Destroys the AlertWindow */
  37716. ~AlertWindow();
  37717. /** Returns the type of alert icon that was specified when the window
  37718. was created. */
  37719. AlertIconType getAlertType() const throw() { return alertIconType; }
  37720. /** Changes the dialog box's message.
  37721. This will also resize the window to fit the new message if required.
  37722. */
  37723. void setMessage (const String& message);
  37724. /** Adds a button to the window.
  37725. @param name the text to show on the button
  37726. @param returnValue the value that should be returned from runModalLoop()
  37727. if this is the button that the user presses.
  37728. @param shortcutKey1 an optional key that can be pressed to trigger this button
  37729. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  37730. */
  37731. void addButton (const String& name,
  37732. const int returnValue,
  37733. const KeyPress& shortcutKey1 = KeyPress(),
  37734. const KeyPress& shortcutKey2 = KeyPress());
  37735. /** Returns the number of buttons that the window currently has. */
  37736. int getNumButtons() const;
  37737. /** Adds a textbox to the window for entering strings.
  37738. @param name an internal name for the text-box. This is the name to pass to
  37739. the getTextEditorContents() method to find out what the
  37740. user typed-in.
  37741. @param initialContents a string to show in the text box when it's first shown
  37742. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37743. text-box to label it.
  37744. @param isPasswordBox if true, the text editor will display asterisks instead of
  37745. the actual text
  37746. @see getTextEditorContents
  37747. */
  37748. void addTextEditor (const String& name,
  37749. const String& initialContents,
  37750. const String& onScreenLabel = String::empty,
  37751. const bool isPasswordBox = false);
  37752. /** Returns the contents of a named textbox.
  37753. After showing an AlertWindow that contains a text editor, this can be
  37754. used to find out what the user has typed into it.
  37755. @param nameOfTextEditor the name of the text box that you're interested in
  37756. @see addTextEditor
  37757. */
  37758. const String getTextEditorContents (const String& nameOfTextEditor) const;
  37759. /** Adds a drop-down list of choices to the box.
  37760. After the box has been shown, the getComboBoxComponent() method can
  37761. be used to find out which item the user picked.
  37762. @param name the label to use for the drop-down list
  37763. @param items the list of items to show in it
  37764. @param onScreenLabel if this is non-empty, it will be displayed next to the
  37765. combo-box to label it.
  37766. @see getComboBoxComponent
  37767. */
  37768. void addComboBox (const String& name,
  37769. const StringArray& items,
  37770. const String& onScreenLabel = String::empty);
  37771. /** Returns a drop-down list that was added to the AlertWindow.
  37772. @param nameOfList the name that was passed into the addComboBox() method
  37773. when creating the drop-down
  37774. @returns the ComboBox component, or 0 if none was found for the given name.
  37775. */
  37776. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  37777. /** Adds a block of text.
  37778. This is handy for adding a multi-line note next to a textbox or combo-box,
  37779. to provide more details about what's going on.
  37780. */
  37781. void addTextBlock (const String& text);
  37782. /** Adds a progress-bar to the window.
  37783. @param progressValue a variable that will be repeatedly checked while the
  37784. dialog box is visible, to see how far the process has
  37785. got. The value should be in the range 0 to 1.0
  37786. */
  37787. void addProgressBarComponent (double& progressValue);
  37788. /** Adds a user-defined component to the dialog box.
  37789. @param component the component to add - its size should be set up correctly
  37790. before it is passed in. The caller is responsible for deleting
  37791. the component later on - the AlertWindow won't delete it.
  37792. */
  37793. void addCustomComponent (Component* const component);
  37794. /** Returns the number of custom components in the dialog box.
  37795. @see getCustomComponent, addCustomComponent
  37796. */
  37797. int getNumCustomComponents() const;
  37798. /** Returns one of the custom components in the dialog box.
  37799. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37800. will return 0
  37801. @see getNumCustomComponents, addCustomComponent
  37802. */
  37803. Component* getCustomComponent (const int index) const;
  37804. /** Removes one of the custom components in the dialog box.
  37805. Note that this won't delete it, it just removes the component from the window
  37806. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  37807. will return 0
  37808. @returns the component that was removed (or zero)
  37809. @see getNumCustomComponents, addCustomComponent
  37810. */
  37811. Component* removeCustomComponent (const int index);
  37812. /** Returns true if the window contains any components other than just buttons.*/
  37813. bool containsAnyExtraComponents() const;
  37814. // easy-to-use message box functions:
  37815. /** Shows a dialog box that just has a message and a single button to get rid of it.
  37816. The box is shown modally, and the method returns after the user
  37817. has clicked the button (or pressed the escape or return keys).
  37818. @param iconType the type of icon to show
  37819. @param title the headline to show at the top of the box
  37820. @param message a longer, more descriptive message to show underneath the
  37821. headline
  37822. @param buttonText the text to show in the button - if this string is empty, the
  37823. default string "ok" (or a localised version) will be used.
  37824. @param associatedComponent if this is non-zero, it specifies the component that the
  37825. alert window should be associated with. Depending on the look
  37826. and feel, this might be used for positioning of the alert window.
  37827. */
  37828. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  37829. const String& title,
  37830. const String& message,
  37831. const String& buttonText = String::empty,
  37832. Component* associatedComponent = 0);
  37833. /** Shows a dialog box with two buttons.
  37834. Ideal for ok/cancel or yes/no choices. The return key can also be used
  37835. to trigger the first button, and the escape key for the second button.
  37836. @param iconType the type of icon to show
  37837. @param title the headline to show at the top of the box
  37838. @param message a longer, more descriptive message to show underneath the
  37839. headline
  37840. @param button1Text the text to show in the first button - if this string is
  37841. empty, the default string "ok" (or a localised version of it)
  37842. will be used.
  37843. @param button2Text the text to show in the second button - if this string is
  37844. empty, the default string "cancel" (or a localised version of it)
  37845. will be used.
  37846. @param associatedComponent if this is non-zero, it specifies the component that the
  37847. alert window should be associated with. Depending on the look
  37848. and feel, this might be used for positioning of the alert window.
  37849. @returns true if button 1 was clicked, false if it was button 2
  37850. */
  37851. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  37852. const String& title,
  37853. const String& message,
  37854. const String& button1Text = String::empty,
  37855. const String& button2Text = String::empty,
  37856. Component* associatedComponent = 0);
  37857. /** Shows a dialog box with three buttons.
  37858. Ideal for yes/no/cancel boxes.
  37859. The escape key can be used to trigger the third button.
  37860. @param iconType the type of icon to show
  37861. @param title the headline to show at the top of the box
  37862. @param message a longer, more descriptive message to show underneath the
  37863. headline
  37864. @param button1Text the text to show in the first button - if an empty string, then
  37865. "yes" will be used (or a localised version of it)
  37866. @param button2Text the text to show in the first button - if an empty string, then
  37867. "no" will be used (or a localised version of it)
  37868. @param button3Text the text to show in the first button - if an empty string, then
  37869. "cancel" will be used (or a localised version of it)
  37870. @param associatedComponent if this is non-zero, it specifies the component that the
  37871. alert window should be associated with. Depending on the look
  37872. and feel, this might be used for positioning of the alert window.
  37873. @returns one of the following values:
  37874. - 0 if the third button was pressed (normally used for 'cancel')
  37875. - 1 if the first button was pressed (normally used for 'yes')
  37876. - 2 if the middle button was pressed (normally used for 'no')
  37877. */
  37878. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  37879. const String& title,
  37880. const String& message,
  37881. const String& button1Text = String::empty,
  37882. const String& button2Text = String::empty,
  37883. const String& button3Text = String::empty,
  37884. Component* associatedComponent = 0);
  37885. /** Shows an operating-system native dialog box.
  37886. @param title the title to use at the top
  37887. @param bodyText the longer message to show
  37888. @param isOkCancel if true, this will show an ok/cancel box, if false,
  37889. it'll show a box with just an ok button
  37890. @returns true if the ok button was pressed, false if they pressed cancel.
  37891. */
  37892. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  37893. const String& bodyText,
  37894. bool isOkCancel);
  37895. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  37896. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37897. methods.
  37898. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37899. */
  37900. enum ColourIds
  37901. {
  37902. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  37903. textColourId = 0x1001810, /**< The colour for the text. */
  37904. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  37905. };
  37906. juce_UseDebuggingNewOperator
  37907. protected:
  37908. /** @internal */
  37909. void paint (Graphics& g);
  37910. /** @internal */
  37911. void mouseDown (const MouseEvent& e);
  37912. /** @internal */
  37913. void mouseDrag (const MouseEvent& e);
  37914. /** @internal */
  37915. bool keyPressed (const KeyPress& key);
  37916. /** @internal */
  37917. void buttonClicked (Button* button);
  37918. /** @internal */
  37919. void lookAndFeelChanged();
  37920. /** @internal */
  37921. void userTriedToCloseWindow();
  37922. /** @internal */
  37923. int getDesktopWindowStyleFlags() const;
  37924. private:
  37925. String text;
  37926. TextLayout textLayout;
  37927. AlertIconType alertIconType;
  37928. ComponentBoundsConstrainer constrainer;
  37929. ComponentDragger dragger;
  37930. Rectangle textArea;
  37931. VoidArray buttons, textBoxes, comboBoxes;
  37932. VoidArray progressBars, customComps, textBlocks, allComps;
  37933. StringArray textboxNames, comboBoxNames;
  37934. Font font;
  37935. Component* associatedComponent;
  37936. void updateLayout (const bool onlyIncreaseSize);
  37937. // disable copy constructor
  37938. AlertWindow (const AlertWindow&);
  37939. const AlertWindow& operator= (const AlertWindow&);
  37940. };
  37941. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  37942. /********* End of inlined file: juce_AlertWindow.h *********/
  37943. class ToggleButton;
  37944. class TextButton;
  37945. class AlertWindow;
  37946. class TextLayout;
  37947. class ScrollBar;
  37948. class BubbleComponent;
  37949. class ComboBox;
  37950. class Button;
  37951. class FilenameComponent;
  37952. class DocumentWindow;
  37953. class ResizableWindow;
  37954. class GroupComponent;
  37955. class MenuBarComponent;
  37956. class DropShadower;
  37957. class GlyphArrangement;
  37958. class PropertyComponent;
  37959. class TableHeaderComponent;
  37960. class Toolbar;
  37961. class ToolbarItemComponent;
  37962. class PopupMenu;
  37963. class ProgressBar;
  37964. class FileBrowserComponent;
  37965. class DirectoryContentsDisplayComponent;
  37966. class FilePreviewComponent;
  37967. class ImageButton;
  37968. /**
  37969. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  37970. can be used to apply different 'skins' to the application.
  37971. */
  37972. class JUCE_API LookAndFeel
  37973. {
  37974. public:
  37975. /** Creates the default JUCE look and feel. */
  37976. LookAndFeel();
  37977. /** Destructor. */
  37978. virtual ~LookAndFeel();
  37979. /** Returns the current default look-and-feel for a component to use when it
  37980. hasn't got one explicitly set.
  37981. @see setDefaultLookAndFeel
  37982. */
  37983. static LookAndFeel& getDefaultLookAndFeel() throw();
  37984. /** Changes the default look-and-feel.
  37985. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  37986. set to 0, it will revert to using the default one. The
  37987. object passed-in must be deleted by the caller when
  37988. it's no longer needed.
  37989. @see getDefaultLookAndFeel
  37990. */
  37991. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  37992. /** Looks for a colour that has been registered with the given colour ID number.
  37993. If a colour has been set for this ID number using setColour(), then it is
  37994. returned. If none has been set, it will just return Colours::black.
  37995. The colour IDs for various purposes are stored as enums in the components that
  37996. they are relevent to - for an example, see Slider::ColourIds,
  37997. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  37998. If you're looking up a colour for use in drawing a component, it's usually
  37999. best not to call this directly, but to use the Component::findColour() method
  38000. instead. That will first check whether a suitable colour has been registered
  38001. directly with the component, and will fall-back on calling the component's
  38002. LookAndFeel's findColour() method if none is found.
  38003. @see setColour, Component::findColour, Component::setColour
  38004. */
  38005. const Colour findColour (const int colourId) const throw();
  38006. /** Registers a colour to be used for a particular purpose.
  38007. For more details, see the comments for findColour().
  38008. @see findColour, Component::findColour, Component::setColour
  38009. */
  38010. void setColour (const int colourId, const Colour& colour) throw();
  38011. /** Returns true if the specified colour ID has been explicitly set using the
  38012. setColour() method.
  38013. */
  38014. bool isColourSpecified (const int colourId) const throw();
  38015. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  38016. /** Allows you to change the default sans-serif font.
  38017. If you need to supply your own Typeface object for any of the default fonts, rather
  38018. than just supplying the name (e.g. if you want to use an embedded font), then
  38019. you should instead override getTypefaceForFont() to create and return the typeface.
  38020. */
  38021. void setDefaultSansSerifTypefaceName (const String& newName);
  38022. /** Override this to get the chance to swap a component's mouse cursor for a
  38023. customised one.
  38024. */
  38025. virtual const MouseCursor getMouseCursorFor (Component& component);
  38026. /** Draws the lozenge-shaped background for a standard button. */
  38027. virtual void drawButtonBackground (Graphics& g,
  38028. Button& button,
  38029. const Colour& backgroundColour,
  38030. bool isMouseOverButton,
  38031. bool isButtonDown);
  38032. virtual const Font getFontForTextButton (TextButton& button);
  38033. /** Draws the text for a TextButton. */
  38034. virtual void drawButtonText (Graphics& g,
  38035. TextButton& button,
  38036. bool isMouseOverButton,
  38037. bool isButtonDown);
  38038. /** Draws the contents of a standard ToggleButton. */
  38039. virtual void drawToggleButton (Graphics& g,
  38040. ToggleButton& button,
  38041. bool isMouseOverButton,
  38042. bool isButtonDown);
  38043. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  38044. virtual void drawTickBox (Graphics& g,
  38045. Component& component,
  38046. int x, int y, int w, int h,
  38047. const bool ticked,
  38048. const bool isEnabled,
  38049. const bool isMouseOverButton,
  38050. const bool isButtonDown);
  38051. /* AlertWindow handling..
  38052. */
  38053. virtual AlertWindow* createAlertWindow (const String& title,
  38054. const String& message,
  38055. const String& button1,
  38056. const String& button2,
  38057. const String& button3,
  38058. AlertWindow::AlertIconType iconType,
  38059. int numButtons,
  38060. Component* associatedComponent);
  38061. virtual void drawAlertBox (Graphics& g,
  38062. AlertWindow& alert,
  38063. const Rectangle& textArea,
  38064. TextLayout& textLayout);
  38065. virtual int getAlertBoxWindowFlags();
  38066. virtual int getAlertWindowButtonHeight();
  38067. virtual const Font getAlertWindowFont();
  38068. /** Draws a progress bar.
  38069. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  38070. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  38071. isn't known). It can use the current time as a basis for playing an animation.
  38072. (Used by progress bars in AlertWindow).
  38073. */
  38074. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  38075. int width, int height,
  38076. double progress, const String& textToShow);
  38077. // Draws a small image that spins to indicate that something's happening..
  38078. // This method should use the current time to animate itself, so just keep
  38079. // repainting it every so often.
  38080. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  38081. int x, int y, int w, int h);
  38082. /** Draws one of the buttons on a scrollbar.
  38083. @param g the context to draw into
  38084. @param scrollbar the bar itself
  38085. @param width the width of the button
  38086. @param height the height of the button
  38087. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  38088. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  38089. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  38090. @param isButtonDown whether the mouse button's held down
  38091. */
  38092. virtual void drawScrollbarButton (Graphics& g,
  38093. ScrollBar& scrollbar,
  38094. int width, int height,
  38095. int buttonDirection,
  38096. bool isScrollbarVertical,
  38097. bool isMouseOverButton,
  38098. bool isButtonDown);
  38099. /** Draws the thumb area of a scrollbar.
  38100. @param g the context to draw into
  38101. @param scrollbar the bar itself
  38102. @param x the x position of the left edge of the thumb area to draw in
  38103. @param y the y position of the top edge of the thumb area to draw in
  38104. @param width the width of the thumb area to draw in
  38105. @param height the height of the thumb area to draw in
  38106. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  38107. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  38108. thumb, or its x position for horizontal bars
  38109. @param thumbSize for vertical bars, the height of the thumb, or its width for
  38110. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  38111. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  38112. currently dragging the thumb
  38113. @param isMouseDown whether the mouse is currently dragging the scrollbar
  38114. */
  38115. virtual void drawScrollbar (Graphics& g,
  38116. ScrollBar& scrollbar,
  38117. int x, int y,
  38118. int width, int height,
  38119. bool isScrollbarVertical,
  38120. int thumbStartPosition,
  38121. int thumbSize,
  38122. bool isMouseOver,
  38123. bool isMouseDown);
  38124. /** Returns the component effect to use for a scrollbar */
  38125. virtual ImageEffectFilter* getScrollbarEffect();
  38126. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  38127. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  38128. /** Returns the default thickness to use for a scrollbar. */
  38129. virtual int getDefaultScrollbarWidth();
  38130. /** Returns the length in pixels to use for a scrollbar button. */
  38131. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  38132. /** Returns a tick shape for use in yes/no boxes, etc. */
  38133. virtual const Path getTickShape (const float height);
  38134. /** Returns a cross shape for use in yes/no boxes, etc. */
  38135. virtual const Path getCrossShape (const float height);
  38136. /** Draws the + or - box in a treeview. */
  38137. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  38138. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  38139. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  38140. // these return an image from the ImageCache, so use ImageCache::release() to free it
  38141. virtual Image* getDefaultFolderImage();
  38142. virtual Image* getDefaultDocumentFileImage();
  38143. virtual void createFileChooserHeaderText (const String& title,
  38144. const String& instructions,
  38145. GlyphArrangement& destArrangement,
  38146. int width);
  38147. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  38148. const String& filename, Image* icon,
  38149. const String& fileSizeDescription,
  38150. const String& fileTimeDescription,
  38151. const bool isDirectory,
  38152. const bool isItemSelected,
  38153. const int itemIndex);
  38154. virtual Button* createFileBrowserGoUpButton();
  38155. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  38156. DirectoryContentsDisplayComponent* fileListComponent,
  38157. FilePreviewComponent* previewComp,
  38158. ComboBox* currentPathBox,
  38159. TextEditor* filenameBox,
  38160. Button* goUpButton);
  38161. virtual void drawBubble (Graphics& g,
  38162. float tipX, float tipY,
  38163. float boxX, float boxY, float boxW, float boxH);
  38164. /** Fills the background of a popup menu component. */
  38165. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  38166. /** Draws one of the items in a popup menu. */
  38167. virtual void drawPopupMenuItem (Graphics& g,
  38168. int width, int height,
  38169. const bool isSeparator,
  38170. const bool isActive,
  38171. const bool isHighlighted,
  38172. const bool isTicked,
  38173. const bool hasSubMenu,
  38174. const String& text,
  38175. const String& shortcutKeyText,
  38176. Image* image,
  38177. const Colour* const textColour);
  38178. /** Returns the size and style of font to use in popup menus. */
  38179. virtual const Font getPopupMenuFont();
  38180. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  38181. int width, int height,
  38182. bool isScrollUpArrow);
  38183. /** Finds the best size for an item in a popup menu. */
  38184. virtual void getIdealPopupMenuItemSize (const String& text,
  38185. const bool isSeparator,
  38186. int standardMenuItemHeight,
  38187. int& idealWidth,
  38188. int& idealHeight);
  38189. virtual int getMenuWindowFlags();
  38190. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  38191. bool isMouseOverBar,
  38192. MenuBarComponent& menuBar);
  38193. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  38194. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  38195. virtual void drawMenuBarItem (Graphics& g,
  38196. int width, int height,
  38197. int itemIndex,
  38198. const String& itemText,
  38199. bool isMouseOverItem,
  38200. bool isMenuOpen,
  38201. bool isMouseOverBar,
  38202. MenuBarComponent& menuBar);
  38203. virtual void drawComboBox (Graphics& g, int width, int height,
  38204. const bool isButtonDown,
  38205. int buttonX, int buttonY,
  38206. int buttonW, int buttonH,
  38207. ComboBox& box);
  38208. virtual const Font getComboBoxFont (ComboBox& box);
  38209. virtual Label* createComboBoxTextBox (ComboBox& box);
  38210. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  38211. virtual void drawLabel (Graphics& g, Label& label);
  38212. virtual void drawLinearSlider (Graphics& g,
  38213. int x, int y,
  38214. int width, int height,
  38215. float sliderPos,
  38216. float minSliderPos,
  38217. float maxSliderPos,
  38218. const Slider::SliderStyle style,
  38219. Slider& slider);
  38220. virtual void drawLinearSliderBackground (Graphics& g,
  38221. int x, int y,
  38222. int width, int height,
  38223. float sliderPos,
  38224. float minSliderPos,
  38225. float maxSliderPos,
  38226. const Slider::SliderStyle style,
  38227. Slider& slider);
  38228. virtual void drawLinearSliderThumb (Graphics& g,
  38229. int x, int y,
  38230. int width, int height,
  38231. float sliderPos,
  38232. float minSliderPos,
  38233. float maxSliderPos,
  38234. const Slider::SliderStyle style,
  38235. Slider& slider);
  38236. virtual int getSliderThumbRadius (Slider& slider);
  38237. virtual void drawRotarySlider (Graphics& g,
  38238. int x, int y,
  38239. int width, int height,
  38240. float sliderPosProportional,
  38241. const float rotaryStartAngle,
  38242. const float rotaryEndAngle,
  38243. Slider& slider);
  38244. virtual Button* createSliderButton (const bool isIncrement);
  38245. virtual Label* createSliderTextBox (Slider& slider);
  38246. virtual ImageEffectFilter* getSliderEffect();
  38247. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  38248. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  38249. virtual Button* createFilenameComponentBrowseButton (const String& text);
  38250. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  38251. ComboBox* filenameBox, Button* browseButton);
  38252. virtual void drawCornerResizer (Graphics& g,
  38253. int w, int h,
  38254. bool isMouseOver,
  38255. bool isMouseDragging);
  38256. virtual void drawResizableFrame (Graphics& g,
  38257. int w, int h,
  38258. const BorderSize& borders);
  38259. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  38260. const BorderSize& border,
  38261. ResizableWindow& window);
  38262. virtual void drawResizableWindowBorder (Graphics& g,
  38263. int w, int h,
  38264. const BorderSize& border,
  38265. ResizableWindow& window);
  38266. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  38267. Graphics& g, int w, int h,
  38268. int titleSpaceX, int titleSpaceW,
  38269. const Image* icon,
  38270. bool drawTitleTextOnLeft);
  38271. virtual Button* createDocumentWindowButton (int buttonType);
  38272. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  38273. int titleBarX, int titleBarY,
  38274. int titleBarW, int titleBarH,
  38275. Button* minimiseButton,
  38276. Button* maximiseButton,
  38277. Button* closeButton,
  38278. bool positionTitleBarButtonsOnLeft);
  38279. virtual int getDefaultMenuBarHeight();
  38280. virtual DropShadower* createDropShadowerForComponent (Component* component);
  38281. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  38282. int w, int h,
  38283. bool isVerticalBar,
  38284. bool isMouseOver,
  38285. bool isMouseDragging);
  38286. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  38287. const String& text,
  38288. const Justification& position,
  38289. GroupComponent& group);
  38290. virtual void createTabButtonShape (Path& p,
  38291. int width, int height,
  38292. int tabIndex,
  38293. const String& text,
  38294. Button& button,
  38295. TabbedButtonBar::Orientation orientation,
  38296. const bool isMouseOver,
  38297. const bool isMouseDown,
  38298. const bool isFrontTab);
  38299. virtual void fillTabButtonShape (Graphics& g,
  38300. const Path& path,
  38301. const Colour& preferredBackgroundColour,
  38302. int tabIndex,
  38303. const String& text,
  38304. Button& button,
  38305. TabbedButtonBar::Orientation orientation,
  38306. const bool isMouseOver,
  38307. const bool isMouseDown,
  38308. const bool isFrontTab);
  38309. virtual void drawTabButtonText (Graphics& g,
  38310. int x, int y, int w, int h,
  38311. const Colour& preferredBackgroundColour,
  38312. int tabIndex,
  38313. const String& text,
  38314. Button& button,
  38315. TabbedButtonBar::Orientation orientation,
  38316. const bool isMouseOver,
  38317. const bool isMouseDown,
  38318. const bool isFrontTab);
  38319. virtual int getTabButtonOverlap (int tabDepth);
  38320. virtual int getTabButtonSpaceAroundImage();
  38321. virtual int getTabButtonBestWidth (int tabIndex,
  38322. const String& text,
  38323. int tabDepth,
  38324. Button& button);
  38325. virtual void drawTabButton (Graphics& g,
  38326. int w, int h,
  38327. const Colour& preferredColour,
  38328. int tabIndex,
  38329. const String& text,
  38330. Button& button,
  38331. TabbedButtonBar::Orientation orientation,
  38332. const bool isMouseOver,
  38333. const bool isMouseDown,
  38334. const bool isFrontTab);
  38335. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  38336. int w, int h,
  38337. TabbedButtonBar& tabBar,
  38338. TabbedButtonBar::Orientation orientation);
  38339. virtual Button* createTabBarExtrasButton();
  38340. virtual void drawImageButton (Graphics& g, Image* image,
  38341. int imageX, int imageY, int imageW, int imageH,
  38342. const Colour& overlayColour,
  38343. float imageOpacity,
  38344. ImageButton& button);
  38345. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  38346. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  38347. int width, int height,
  38348. bool isMouseOver, bool isMouseDown,
  38349. int columnFlags);
  38350. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  38351. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  38352. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  38353. bool isMouseOver, bool isMouseDown,
  38354. ToolbarItemComponent& component);
  38355. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  38356. const String& text, ToolbarItemComponent& component);
  38357. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  38358. bool isOpen, int width, int height);
  38359. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  38360. PropertyComponent& component);
  38361. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  38362. PropertyComponent& component);
  38363. virtual const Rectangle getPropertyComponentContentPosition (PropertyComponent& component);
  38364. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  38365. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  38366. /**
  38367. */
  38368. virtual void playAlertSound();
  38369. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  38370. static void drawGlassSphere (Graphics& g,
  38371. const float x, const float y,
  38372. const float diameter,
  38373. const Colour& colour,
  38374. const float outlineThickness) throw();
  38375. static void drawGlassPointer (Graphics& g,
  38376. const float x, const float y,
  38377. const float diameter,
  38378. const Colour& colour, const float outlineThickness,
  38379. const int direction) throw();
  38380. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  38381. static void drawGlassLozenge (Graphics& g,
  38382. const float x, const float y,
  38383. const float width, const float height,
  38384. const Colour& colour,
  38385. const float outlineThickness,
  38386. const float cornerSize,
  38387. const bool flatOnLeft, const bool flatOnRight,
  38388. const bool flatOnTop, const bool flatOnBottom) throw();
  38389. juce_UseDebuggingNewOperator
  38390. protected:
  38391. // xxx the following methods are only here to cause a compiler error, because they've been
  38392. // deprecated or their parameters have changed. Hopefully these definitions should cause an
  38393. // error if you try to build a subclass with the old versions.
  38394. virtual int drawTickBox (Graphics&, int, int, int, int, bool, const bool, const bool, const bool) { return 0; }
  38395. virtual int drawProgressBar (Graphics&, int, int, int, int, float) { return 0; }
  38396. virtual int drawProgressBar (Graphics&, ProgressBar&, int, int, int, int, float) { return 0; }
  38397. virtual void getTabButtonBestWidth (int, const String&, int) {}
  38398. virtual int drawTreeviewPlusMinusBox (Graphics&, int, int, int, int, bool) { return 0; }
  38399. private:
  38400. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  38401. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  38402. Array <int> colourIds;
  38403. Array <Colour> colours;
  38404. // default typeface names
  38405. String defaultSans, defaultSerif, defaultFixed;
  38406. void drawShinyButtonShape (Graphics& g,
  38407. float x, float y, float w, float h, float maxCornerSize,
  38408. const Colour& baseColour,
  38409. const float strokeWidth,
  38410. const bool flatOnLeft,
  38411. const bool flatOnRight,
  38412. const bool flatOnTop,
  38413. const bool flatOnBottom) throw();
  38414. LookAndFeel (const LookAndFeel&);
  38415. const LookAndFeel& operator= (const LookAndFeel&);
  38416. };
  38417. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  38418. /********* End of inlined file: juce_LookAndFeel.h *********/
  38419. #endif
  38420. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  38421. /********* Start of inlined file: juce_OldSchoolLookAndFeel.h *********/
  38422. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  38423. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  38424. /**
  38425. The original Juce look-and-feel.
  38426. */
  38427. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  38428. {
  38429. public:
  38430. /** Creates the default JUCE look and feel. */
  38431. OldSchoolLookAndFeel();
  38432. /** Destructor. */
  38433. virtual ~OldSchoolLookAndFeel();
  38434. /** Draws the lozenge-shaped background for a standard button. */
  38435. virtual void drawButtonBackground (Graphics& g,
  38436. Button& button,
  38437. const Colour& backgroundColour,
  38438. bool isMouseOverButton,
  38439. bool isButtonDown);
  38440. /** Draws the contents of a standard ToggleButton. */
  38441. virtual void drawToggleButton (Graphics& g,
  38442. ToggleButton& button,
  38443. bool isMouseOverButton,
  38444. bool isButtonDown);
  38445. virtual void drawTickBox (Graphics& g,
  38446. Component& component,
  38447. int x, int y, int w, int h,
  38448. const bool ticked,
  38449. const bool isEnabled,
  38450. const bool isMouseOverButton,
  38451. const bool isButtonDown);
  38452. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  38453. int width, int height,
  38454. double progress, const String& textToShow);
  38455. virtual void drawScrollbarButton (Graphics& g,
  38456. ScrollBar& scrollbar,
  38457. int width, int height,
  38458. int buttonDirection,
  38459. bool isScrollbarVertical,
  38460. bool isMouseOverButton,
  38461. bool isButtonDown);
  38462. virtual void drawScrollbar (Graphics& g,
  38463. ScrollBar& scrollbar,
  38464. int x, int y,
  38465. int width, int height,
  38466. bool isScrollbarVertical,
  38467. int thumbStartPosition,
  38468. int thumbSize,
  38469. bool isMouseOver,
  38470. bool isMouseDown);
  38471. virtual ImageEffectFilter* getScrollbarEffect();
  38472. virtual void drawTextEditorOutline (Graphics& g,
  38473. int width, int height,
  38474. TextEditor& textEditor);
  38475. /** Fills the background of a popup menu component. */
  38476. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  38477. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  38478. bool isMouseOverBar,
  38479. MenuBarComponent& menuBar);
  38480. virtual void drawComboBox (Graphics& g, int width, int height,
  38481. const bool isButtonDown,
  38482. int buttonX, int buttonY,
  38483. int buttonW, int buttonH,
  38484. ComboBox& box);
  38485. virtual const Font getComboBoxFont (ComboBox& box);
  38486. virtual void drawLinearSlider (Graphics& g,
  38487. int x, int y,
  38488. int width, int height,
  38489. float sliderPos,
  38490. float minSliderPos,
  38491. float maxSliderPos,
  38492. const Slider::SliderStyle style,
  38493. Slider& slider);
  38494. virtual int getSliderThumbRadius (Slider& slider);
  38495. virtual Button* createSliderButton (const bool isIncrement);
  38496. virtual ImageEffectFilter* getSliderEffect();
  38497. virtual void drawCornerResizer (Graphics& g,
  38498. int w, int h,
  38499. bool isMouseOver,
  38500. bool isMouseDragging);
  38501. virtual Button* createDocumentWindowButton (int buttonType);
  38502. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  38503. int titleBarX, int titleBarY,
  38504. int titleBarW, int titleBarH,
  38505. Button* minimiseButton,
  38506. Button* maximiseButton,
  38507. Button* closeButton,
  38508. bool positionTitleBarButtonsOnLeft);
  38509. juce_UseDebuggingNewOperator
  38510. private:
  38511. DropShadowEffect scrollbarShadow;
  38512. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  38513. const OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  38514. };
  38515. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  38516. /********* End of inlined file: juce_OldSchoolLookAndFeel.h *********/
  38517. #endif
  38518. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38519. #endif
  38520. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  38521. #endif
  38522. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  38523. #endif
  38524. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  38525. #endif
  38526. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  38527. #endif
  38528. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  38529. #endif
  38530. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  38531. #endif
  38532. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  38533. #endif
  38534. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  38535. /********* Start of inlined file: juce_LassoComponent.h *********/
  38536. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  38537. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  38538. /********* Start of inlined file: juce_SelectedItemSet.h *********/
  38539. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  38540. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  38541. /** Manages a list of selectable items.
  38542. Use one of these to keep a track of things that the user has highlighted, like
  38543. icons or things in a list.
  38544. The class is templated so that you can use it to hold either a set of pointers
  38545. to objects, or a set of ID numbers or handles, for cases where each item may
  38546. not always have a corresponding object.
  38547. To be informed when items are selected/deselected, register a ChangeListener with
  38548. this object.
  38549. @see SelectableObject
  38550. */
  38551. template <class SelectableItemType>
  38552. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  38553. {
  38554. public:
  38555. /** Creates an empty set. */
  38556. SelectedItemSet()
  38557. {
  38558. }
  38559. /** Creates a set based on an array of items. */
  38560. SelectedItemSet (const Array <SelectableItemType>& items)
  38561. : selectedItems (items)
  38562. {
  38563. }
  38564. /** Creates a copy of another set. */
  38565. SelectedItemSet (const SelectedItemSet& other)
  38566. : selectedItems (other.selectedItems)
  38567. {
  38568. }
  38569. /** Creates a copy of another set. */
  38570. const SelectedItemSet& operator= (const SelectedItemSet& other)
  38571. {
  38572. if (selectedItems != other.selectedItems)
  38573. {
  38574. selectedItems = other.selectedItems;
  38575. changed();
  38576. }
  38577. return *this;
  38578. }
  38579. /** Destructor. */
  38580. ~SelectedItemSet()
  38581. {
  38582. }
  38583. /** Clears any other currently selected items, and selects this item.
  38584. If this item is already the only thing selected, no change notification
  38585. will be sent out.
  38586. @see addToSelection, addToSelectionBasedOnModifiers
  38587. */
  38588. void selectOnly (SelectableItemType item)
  38589. {
  38590. if (isSelected (item))
  38591. {
  38592. for (int i = selectedItems.size(); --i >= 0;)
  38593. {
  38594. if (selectedItems.getUnchecked(i) != item)
  38595. {
  38596. deselect (selectedItems.getUnchecked(i));
  38597. i = jmin (i, selectedItems.size());
  38598. }
  38599. }
  38600. }
  38601. else
  38602. {
  38603. deselectAll();
  38604. changed();
  38605. selectedItems.add (item);
  38606. itemSelected (item);
  38607. }
  38608. }
  38609. /** Selects an item.
  38610. If the item is already selected, no change notification will be sent out.
  38611. @see selectOnly, addToSelectionBasedOnModifiers
  38612. */
  38613. void addToSelection (SelectableItemType item)
  38614. {
  38615. if (! isSelected (item))
  38616. {
  38617. changed();
  38618. selectedItems.add (item);
  38619. itemSelected (item);
  38620. }
  38621. }
  38622. /** Selects or deselects an item.
  38623. This will use the modifier keys to decide whether to deselect other items
  38624. first.
  38625. So if the shift key is held down, the item will be added without deselecting
  38626. anything (same as calling addToSelection() )
  38627. If no modifiers are down, the current selection will be cleared first (same
  38628. as calling selectOnly() )
  38629. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  38630. so it'll be added to the set unless it's already there, in which case it'll be
  38631. deselected.
  38632. If the items that you're selecting can also be dragged, you may need to use the
  38633. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  38634. subtleties of this kind of usage.
  38635. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  38636. */
  38637. void addToSelectionBasedOnModifiers (SelectableItemType item,
  38638. const ModifierKeys& modifiers)
  38639. {
  38640. if (modifiers.isShiftDown())
  38641. {
  38642. addToSelection (item);
  38643. }
  38644. else if (modifiers.isCommandDown())
  38645. {
  38646. if (isSelected (item))
  38647. deselect (item);
  38648. else
  38649. addToSelection (item);
  38650. }
  38651. else
  38652. {
  38653. selectOnly (item);
  38654. }
  38655. }
  38656. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  38657. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  38658. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  38659. makes it easy to handle multiple-selection of sets of objects that can also
  38660. be dragged.
  38661. For example, if you have several items already selected, and you click on
  38662. one of them (without dragging), then you'd expect this to deselect the other, and
  38663. just select the item you clicked on. But if you had clicked on this item and
  38664. dragged it, you'd have expected them all to stay selected.
  38665. When you call this method, you'll need to store the boolean result, because the
  38666. addToSelectionOnMouseUp() method will need to be know this value.
  38667. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  38668. */
  38669. bool addToSelectionOnMouseDown (SelectableItemType item,
  38670. const ModifierKeys& modifiers)
  38671. {
  38672. if (isSelected (item))
  38673. {
  38674. return ! modifiers.isPopupMenu();
  38675. }
  38676. else
  38677. {
  38678. addToSelectionBasedOnModifiers (item, modifiers);
  38679. return false;
  38680. }
  38681. }
  38682. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  38683. Call this during a mouseUp callback, when you have previously called the
  38684. addToSelectionOnMouseDown() method during your mouseDown event.
  38685. See addToSelectionOnMouseDown() for more info
  38686. @param item the item to select (or deselect)
  38687. @param modifiers the modifiers from the mouse-up event
  38688. @param wasItemDragged true if your item was dragged during the mouse click
  38689. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  38690. back from the addToSelectionOnMouseDown() call that you
  38691. should have made during the matching mouseDown event
  38692. */
  38693. void addToSelectionOnMouseUp (SelectableItemType item,
  38694. const ModifierKeys& modifiers,
  38695. const bool wasItemDragged,
  38696. const bool resultOfMouseDownSelectMethod)
  38697. {
  38698. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  38699. addToSelectionBasedOnModifiers (item, modifiers);
  38700. }
  38701. /** Deselects an item. */
  38702. void deselect (SelectableItemType item)
  38703. {
  38704. const int i = selectedItems.indexOf (item);
  38705. if (i >= 0)
  38706. {
  38707. changed();
  38708. itemDeselected (selectedItems.remove (i));
  38709. }
  38710. }
  38711. /** Deselects all items. */
  38712. void deselectAll()
  38713. {
  38714. if (selectedItems.size() > 0)
  38715. {
  38716. changed();
  38717. for (int i = selectedItems.size(); --i >= 0;)
  38718. {
  38719. itemDeselected (selectedItems.remove (i));
  38720. i = jmin (i, selectedItems.size());
  38721. }
  38722. }
  38723. }
  38724. /** Returns the number of currently selected items.
  38725. @see getSelectedItem
  38726. */
  38727. int getNumSelected() const throw()
  38728. {
  38729. return selectedItems.size();
  38730. }
  38731. /** Returns one of the currently selected items.
  38732. Returns 0 if the index is out-of-range.
  38733. @see getNumSelected
  38734. */
  38735. SelectableItemType getSelectedItem (const int index) const throw()
  38736. {
  38737. return selectedItems [index];
  38738. }
  38739. /** True if this item is currently selected. */
  38740. bool isSelected (const SelectableItemType item) const throw()
  38741. {
  38742. return selectedItems.contains (item);
  38743. }
  38744. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  38745. /** Can be overridden to do special handling when an item is selected.
  38746. For example, if the item is an object, you might want to call it and tell
  38747. it that it's being selected.
  38748. */
  38749. virtual void itemSelected (SelectableItemType item) {}
  38750. /** Can be overridden to do special handling when an item is deselected.
  38751. For example, if the item is an object, you might want to call it and tell
  38752. it that it's being deselected.
  38753. */
  38754. virtual void itemDeselected (SelectableItemType item) {}
  38755. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  38756. */
  38757. void changed (const bool synchronous = false)
  38758. {
  38759. if (synchronous)
  38760. sendSynchronousChangeMessage (this);
  38761. else
  38762. sendChangeMessage (this);
  38763. }
  38764. juce_UseDebuggingNewOperator
  38765. private:
  38766. Array <SelectableItemType> selectedItems;
  38767. };
  38768. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  38769. /********* End of inlined file: juce_SelectedItemSet.h *********/
  38770. /**
  38771. A class used by the LassoComponent to manage the things that it selects.
  38772. This allows the LassoComponent to find out which items are within the lasso,
  38773. and to change the list of selected items.
  38774. @see LassoComponent, SelectedItemSet
  38775. */
  38776. template <class SelectableItemType>
  38777. class LassoSource
  38778. {
  38779. public:
  38780. /** Destructor. */
  38781. virtual ~LassoSource() {}
  38782. /** Returns the set of items that lie within a given lassoable region.
  38783. Your implementation of this method must find all the relevent items that lie
  38784. within the given rectangle. and add them to the itemsFound array.
  38785. The co-ordinates are relative to the top-left of the lasso component's parent
  38786. component. (i.e. they are the same as the size and position of the lasso
  38787. component itself).
  38788. */
  38789. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  38790. int x, int y, int width, int height) = 0;
  38791. /** Returns the SelectedItemSet that the lasso should update.
  38792. This set will be continuously updated by the LassoComponent as it gets
  38793. dragged around, so make sure that you've got a ChangeListener attached to
  38794. the set so that your UI objects will know when the selection changes and
  38795. be able to update themselves appropriately.
  38796. */
  38797. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  38798. };
  38799. /**
  38800. A component that acts as a rectangular selection region, which you drag with
  38801. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  38802. To use one of these:
  38803. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  38804. component, and call its beginLasso() method, giving it a
  38805. suitable LassoSource object that it can use to find out which items are in
  38806. the active area.
  38807. - Each time your parent component gets a mouseDrag event, call dragLasso()
  38808. to update the lasso's position - it will use its LassoSource to calculate and
  38809. update the current selection.
  38810. - After the drag has finished and you get a mouseUp callback, you should call
  38811. endLasso() to clean up. This will make the lasso component invisible, and you
  38812. can remove it from the parent component, or delete it.
  38813. The class takes into account the modifier keys that are being held down while
  38814. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  38815. be added to the original selection; if ctrl or command is pressed, they will be
  38816. xor'ed with any previously selected items.
  38817. @see LassoSource, SelectedItemSet
  38818. */
  38819. template <class SelectableItemType>
  38820. class LassoComponent : public Component
  38821. {
  38822. public:
  38823. /** Creates a Lasso component.
  38824. The fill colour is used to fill the lasso'ed rectangle, and the outline
  38825. colour is used to draw a line around its edge.
  38826. */
  38827. LassoComponent (const int outlineThickness_ = 1)
  38828. : source (0),
  38829. outlineThickness (outlineThickness_)
  38830. {
  38831. }
  38832. /** Destructor. */
  38833. ~LassoComponent()
  38834. {
  38835. }
  38836. /** Call this in your mouseDown event, to initialise a drag.
  38837. Pass in a suitable LassoSource object which the lasso will use to find
  38838. the items and change the selection.
  38839. After using this method to initialise the lasso, repeatedly call dragLasso()
  38840. in your component's mouseDrag callback.
  38841. @see dragLasso, endLasso, LassoSource
  38842. */
  38843. void beginLasso (const MouseEvent& e,
  38844. LassoSource <SelectableItemType>* const lassoSource)
  38845. {
  38846. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  38847. jassert (lassoSource != 0); // the source can't be null!
  38848. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  38849. source = lassoSource;
  38850. if (lassoSource != 0)
  38851. originalSelection = lassoSource->getLassoSelection().getItemArray();
  38852. setSize (0, 0);
  38853. }
  38854. /** Call this in your mouseDrag event, to update the lasso's position.
  38855. This must be repeatedly calling when the mouse is dragged, after you've
  38856. first initialised the lasso with beginLasso().
  38857. This method takes into account the modifier keys that are being held down, so
  38858. if shift is pressed, then the lassoed items will be added to any that were
  38859. previously selected; if ctrl or command is pressed, then they will be xor'ed
  38860. with previously selected items.
  38861. @see beginLasso, endLasso
  38862. */
  38863. void dragLasso (const MouseEvent& e)
  38864. {
  38865. if (source != 0)
  38866. {
  38867. const int x1 = e.getMouseDownX();
  38868. const int y1 = e.getMouseDownY();
  38869. setBounds (jmin (x1, e.x), jmin (y1, e.y), abs (e.x - x1), abs (e.y - y1));
  38870. setVisible (true);
  38871. Array <SelectableItemType> itemsInLasso;
  38872. source->findLassoItemsInArea (itemsInLasso, getX(), getY(), getWidth(), getHeight());
  38873. if (e.mods.isShiftDown())
  38874. {
  38875. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  38876. itemsInLasso.addArray (originalSelection);
  38877. }
  38878. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  38879. {
  38880. Array <SelectableItemType> originalMinusNew (originalSelection);
  38881. originalMinusNew.removeValuesIn (itemsInLasso);
  38882. itemsInLasso.removeValuesIn (originalSelection);
  38883. itemsInLasso.addArray (originalMinusNew);
  38884. }
  38885. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  38886. }
  38887. }
  38888. /** Call this in your mouseUp event, after the lasso has been dragged.
  38889. @see beginLasso, dragLasso
  38890. */
  38891. void endLasso()
  38892. {
  38893. source = 0;
  38894. originalSelection.clear();
  38895. setVisible (false);
  38896. }
  38897. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38898. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38899. methods.
  38900. Note that you can also use the constants from TextEditor::ColourIds to change the
  38901. colour of the text editor that is opened when a label is editable.
  38902. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38903. */
  38904. enum ColourIds
  38905. {
  38906. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  38907. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  38908. };
  38909. /** @internal */
  38910. void paint (Graphics& g)
  38911. {
  38912. g.fillAll (findColour (lassoFillColourId));
  38913. g.setColour (findColour (lassoOutlineColourId));
  38914. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  38915. // this suggests that you've left a lasso comp lying around after the
  38916. // mouse drag has finished.. Be careful to call endLasso() when you get a
  38917. // mouse-up event.
  38918. jassert (isMouseButtonDownAnywhere());
  38919. }
  38920. /** @internal */
  38921. bool hitTest (int x, int y) { return false; }
  38922. juce_UseDebuggingNewOperator
  38923. private:
  38924. Array <SelectableItemType> originalSelection;
  38925. LassoSource <SelectableItemType>* source;
  38926. int outlineThickness;
  38927. };
  38928. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  38929. /********* End of inlined file: juce_LassoComponent.h *********/
  38930. #endif
  38931. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  38932. #endif
  38933. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  38934. #endif
  38935. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  38936. /********* Start of inlined file: juce_MouseHoverDetector.h *********/
  38937. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  38938. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  38939. /**
  38940. Monitors a component for mouse activity, and triggers a callback
  38941. when the mouse hovers in one place for a specified length of time.
  38942. To use a hover-detector, just create one and call its setHoverComponent()
  38943. method to start it watching a component. You can call setHoverComponent (0)
  38944. to make it inactive.
  38945. (Be careful not to delete a component that's being monitored without first
  38946. stopping or deleting the hover detector).
  38947. */
  38948. class JUCE_API MouseHoverDetector
  38949. {
  38950. public:
  38951. /** Creates a hover detector.
  38952. Initially the object is inactive, and you need to tell it which component
  38953. to monitor, using the setHoverComponent() method.
  38954. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  38955. needs to stay still before the mouseHovered() method
  38956. is invoked. You can change this setting later with
  38957. the setHoverTimeMillisecs() method
  38958. */
  38959. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  38960. /** Destructor. */
  38961. virtual ~MouseHoverDetector();
  38962. /** Changes the time for which the mouse has to stay still before it's considered
  38963. to be hovering.
  38964. */
  38965. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  38966. /** Changes the component that's being monitored for hovering.
  38967. Be careful not to delete a component that's being monitored without first
  38968. stopping or deleting the hover detector.
  38969. */
  38970. void setHoverComponent (Component* const newSourceComponent);
  38971. protected:
  38972. /** Called back when the mouse hovers.
  38973. After the mouse has stayed still over the component for the length of time
  38974. specified by setHoverTimeMillisecs(), this method will be invoked.
  38975. When the mouse is first moved after this callback has occurred, the
  38976. mouseMovedAfterHover() method will be called.
  38977. @param mouseX the mouse's X position relative to the component being monitored
  38978. @param mouseY the mouse's Y position relative to the component being monitored
  38979. */
  38980. virtual void mouseHovered (int mouseX,
  38981. int mouseY) = 0;
  38982. /** Called when the mouse is moved away after just having hovered. */
  38983. virtual void mouseMovedAfterHover() = 0;
  38984. private:
  38985. class JUCE_API HoverDetectorInternal : public MouseListener,
  38986. public Timer
  38987. {
  38988. public:
  38989. MouseHoverDetector* owner;
  38990. int lastX, lastY;
  38991. void timerCallback();
  38992. void mouseEnter (const MouseEvent&);
  38993. void mouseExit (const MouseEvent&);
  38994. void mouseDown (const MouseEvent&);
  38995. void mouseUp (const MouseEvent&);
  38996. void mouseMove (const MouseEvent&);
  38997. void mouseWheelMove (const MouseEvent&, float, float);
  38998. } internalTimer;
  38999. friend class HoverDetectorInternal;
  39000. Component* source;
  39001. int hoverTimeMillisecs;
  39002. bool hasJustHovered;
  39003. void hoverTimerCallback();
  39004. void checkJustHoveredCallback();
  39005. };
  39006. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  39007. /********* End of inlined file: juce_MouseHoverDetector.h *********/
  39008. #endif
  39009. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  39010. #endif
  39011. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  39012. #endif
  39013. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  39014. /********* Start of inlined file: juce_BooleanPropertyComponent.h *********/
  39015. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  39016. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  39017. /**
  39018. A PropertyComponent that contains an on/off toggle button.
  39019. This type of property component can be used if you have a boolean value to
  39020. toggle on/off.
  39021. @see PropertyComponent
  39022. */
  39023. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  39024. private ButtonListener
  39025. {
  39026. public:
  39027. /** Creates a button component.
  39028. @param propertyName the property name to be passed to the PropertyComponent
  39029. @param buttonTextWhenTrue the text shown in the button when the value is true
  39030. @param buttonTextWhenFalse the text shown in the button when the value is false
  39031. */
  39032. BooleanPropertyComponent (const String& propertyName,
  39033. const String& buttonTextWhenTrue,
  39034. const String& buttonTextWhenFalse);
  39035. /** Destructor. */
  39036. ~BooleanPropertyComponent();
  39037. /** Called to change the state of the boolean value. */
  39038. virtual void setState (const bool newState) = 0;
  39039. /** Must return the current value of the property. */
  39040. virtual bool getState() const = 0;
  39041. /** @internal */
  39042. void paint (Graphics& g);
  39043. /** @internal */
  39044. void refresh();
  39045. /** @internal */
  39046. void buttonClicked (Button*);
  39047. juce_UseDebuggingNewOperator
  39048. private:
  39049. ToggleButton* button;
  39050. String onText, offText;
  39051. };
  39052. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  39053. /********* End of inlined file: juce_BooleanPropertyComponent.h *********/
  39054. #endif
  39055. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  39056. /********* Start of inlined file: juce_ButtonPropertyComponent.h *********/
  39057. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  39058. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  39059. /**
  39060. A PropertyComponent that contains a button.
  39061. This type of property component can be used if you need a button to trigger some
  39062. kind of action.
  39063. @see PropertyComponent
  39064. */
  39065. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  39066. private ButtonListener
  39067. {
  39068. public:
  39069. /** Creates a button component.
  39070. @param propertyName the property name to be passed to the PropertyComponent
  39071. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  39072. */
  39073. ButtonPropertyComponent (const String& propertyName,
  39074. const bool triggerOnMouseDown);
  39075. /** Destructor. */
  39076. ~ButtonPropertyComponent();
  39077. /** Called when the user clicks the button.
  39078. */
  39079. virtual void buttonClicked() = 0;
  39080. /** Returns the string that should be displayed in the button.
  39081. If you need to change this string, call refresh() to update the component.
  39082. */
  39083. virtual const String getButtonText() const = 0;
  39084. /** @internal */
  39085. void refresh();
  39086. /** @internal */
  39087. void buttonClicked (Button*);
  39088. juce_UseDebuggingNewOperator
  39089. private:
  39090. TextButton* button;
  39091. };
  39092. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  39093. /********* End of inlined file: juce_ButtonPropertyComponent.h *********/
  39094. #endif
  39095. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  39096. /********* Start of inlined file: juce_ChoicePropertyComponent.h *********/
  39097. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  39098. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  39099. /**
  39100. A PropertyComponent that shows its value as a combo box.
  39101. This type of property component contains a list of options and has a
  39102. combo box to choose one.
  39103. Your subclass's constructor must add some strings to the choices StringArray
  39104. and these are shown in the list.
  39105. The getIndex() method will be called to find out which option is the currently
  39106. selected one. If you call refresh() it will call getIndex() to check whether
  39107. the value has changed, and will update the combo box if needed.
  39108. If the user selects a different item from the list, setIndex() will be
  39109. called to let your class process this.
  39110. @see PropertyComponent, PropertyPanel
  39111. */
  39112. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  39113. private ComboBoxListener
  39114. {
  39115. public:
  39116. /** Creates the component.
  39117. Your subclass's constructor must add a list of options to the choices
  39118. member variable.
  39119. */
  39120. ChoicePropertyComponent (const String& propertyName);
  39121. /** Destructor. */
  39122. ~ChoicePropertyComponent();
  39123. /** Called when the user selects an item from the combo box.
  39124. Your subclass must use this callback to update the value that this component
  39125. represents. The index is the index of the chosen item in the choices
  39126. StringArray.
  39127. */
  39128. virtual void setIndex (const int newIndex) = 0;
  39129. /** Returns the index of the item that should currently be shown.
  39130. This is the index of the item in the choices StringArray that will be
  39131. shown.
  39132. */
  39133. virtual int getIndex() const = 0;
  39134. /** Returns the list of options. */
  39135. const StringArray& getChoices() const throw();
  39136. /** @internal */
  39137. void refresh();
  39138. /** @internal */
  39139. void comboBoxChanged (ComboBox*);
  39140. juce_UseDebuggingNewOperator
  39141. protected:
  39142. /** The list of options that will be shown in the combo box.
  39143. Your subclass must populate this array in its constructor. If any empty
  39144. strings are added, these will be replaced with horizontal separators (see
  39145. ComboBox::addSeparator() for more info).
  39146. */
  39147. StringArray choices;
  39148. private:
  39149. ComboBox* comboBox;
  39150. };
  39151. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  39152. /********* End of inlined file: juce_ChoicePropertyComponent.h *********/
  39153. #endif
  39154. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  39155. #endif
  39156. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  39157. #endif
  39158. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  39159. /********* Start of inlined file: juce_SliderPropertyComponent.h *********/
  39160. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  39161. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  39162. /**
  39163. A PropertyComponent that shows its value as a slider.
  39164. @see PropertyComponent, Slider
  39165. */
  39166. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  39167. private SliderListener
  39168. {
  39169. public:
  39170. /** Creates the property component.
  39171. The ranges, interval and skew factor are passed to the Slider component.
  39172. If you need to customise the slider in other ways, your constructor can
  39173. access the slider member variable and change it directly.
  39174. */
  39175. SliderPropertyComponent (const String& propertyName,
  39176. const double rangeMin,
  39177. const double rangeMax,
  39178. const double interval,
  39179. const double skewFactor = 1.0);
  39180. /** Destructor. */
  39181. ~SliderPropertyComponent();
  39182. /** Called when the user moves the slider to change its value.
  39183. Your subclass must use this method to update whatever item this property
  39184. represents.
  39185. */
  39186. virtual void setValue (const double newValue) = 0;
  39187. /** Returns the value that the slider should show. */
  39188. virtual const double getValue() const = 0;
  39189. /** @internal */
  39190. void refresh();
  39191. /** @internal */
  39192. void changeListenerCallback (void*);
  39193. /** @internal */
  39194. void sliderValueChanged (Slider*);
  39195. juce_UseDebuggingNewOperator
  39196. protected:
  39197. /** The slider component being used in this component.
  39198. Your subclass has access to this in case it needs to customise it in some way.
  39199. */
  39200. Slider* slider;
  39201. };
  39202. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  39203. /********* End of inlined file: juce_SliderPropertyComponent.h *********/
  39204. #endif
  39205. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  39206. /********* Start of inlined file: juce_TextPropertyComponent.h *********/
  39207. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  39208. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  39209. /**
  39210. A PropertyComponent that shows its value as editable text.
  39211. @see PropertyComponent
  39212. */
  39213. class JUCE_API TextPropertyComponent : public PropertyComponent
  39214. {
  39215. public:
  39216. /** Creates a text property component.
  39217. The maxNumChars is used to set the length of string allowable, and isMultiLine
  39218. sets whether the text editor allows carriage returns.
  39219. @see TextEditor
  39220. */
  39221. TextPropertyComponent (const String& propertyName,
  39222. const int maxNumChars,
  39223. const bool isMultiLine);
  39224. /** Destructor. */
  39225. ~TextPropertyComponent();
  39226. /** Called when the user edits the text.
  39227. Your subclass must use this callback to change the value of whatever item
  39228. this property component represents.
  39229. */
  39230. virtual void setText (const String& newText) = 0;
  39231. /** Returns the text that should be shown in the text editor.
  39232. */
  39233. virtual const String getText() const = 0;
  39234. /** @internal */
  39235. void refresh();
  39236. /** @internal */
  39237. void textWasEdited();
  39238. juce_UseDebuggingNewOperator
  39239. private:
  39240. Label* textEditor;
  39241. };
  39242. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  39243. /********* End of inlined file: juce_TextPropertyComponent.h *********/
  39244. #endif
  39245. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39246. /********* Start of inlined file: juce_ActiveXControlComponent.h *********/
  39247. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39248. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39249. #if JUCE_WINDOWS || DOXYGEN
  39250. /**
  39251. A Windows-specific class that can create and embed an ActiveX control inside
  39252. itself.
  39253. To use it, create one of these, put it in place and make sure it's visible in a
  39254. window, then use createControl() to instantiate an ActiveX control. The control
  39255. will then be moved and resized to follow the movements of this component.
  39256. Of course, since the control is a heavyweight window, it'll obliterate any
  39257. juce components that may overlap this component, but that's life.
  39258. */
  39259. class JUCE_API ActiveXControlComponent : public Component
  39260. {
  39261. public:
  39262. /** Create an initially-empty container. */
  39263. ActiveXControlComponent();
  39264. /** Destructor. */
  39265. ~ActiveXControlComponent();
  39266. /** Tries to create an ActiveX control and embed it in this peer.
  39267. The peer controlIID is a pointer to an IID structure - it's treated
  39268. as a void* because when including the Juce headers, you might not always
  39269. have included windows.h first, in which case IID wouldn't be defined.
  39270. e.g. @code
  39271. const IID myIID = __uuidof (QTControl);
  39272. myControlComp->createControl (&myIID);
  39273. @endcode
  39274. */
  39275. bool createControl (const void* controlIID);
  39276. /** Deletes the ActiveX control, if one has been created.
  39277. */
  39278. void deleteControl();
  39279. /** Returns true if a control is currently in use. */
  39280. bool isControlOpen() const throw() { return control != 0; }
  39281. /** Does a QueryInterface call on the embedded control object.
  39282. This allows you to cast the control to whatever type of COM object you need.
  39283. The iid parameter is a pointer to an IID structure - it's treated
  39284. as a void* because when including the Juce headers, you might not always
  39285. have included windows.h first, in which case IID wouldn't be defined, but
  39286. you should just pass a pointer to an IID.
  39287. e.g. @code
  39288. const IID iid = __uuidof (IOleWindow);
  39289. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  39290. if (oleWindow != 0)
  39291. {
  39292. HWND hwnd;
  39293. oleWindow->GetWindow (&hwnd);
  39294. ...
  39295. oleWindow->Release();
  39296. }
  39297. @endcode
  39298. */
  39299. void* queryInterface (const void* iid) const;
  39300. /** Set this to false to stop mouse events being allowed through to the control.
  39301. */
  39302. void setMouseEventsAllowed (const bool eventsCanReachControl);
  39303. /** Returns true if mouse events are allowed to get through to the control.
  39304. */
  39305. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  39306. /** @internal */
  39307. void paint (Graphics& g);
  39308. /** @internal */
  39309. void* originalWndProc;
  39310. juce_UseDebuggingNewOperator
  39311. private:
  39312. friend class ActiveXControlData;
  39313. void* control;
  39314. bool mouseEventsAllowed;
  39315. ActiveXControlComponent (const ActiveXControlComponent&);
  39316. const ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  39317. void setControlBounds (const Rectangle& bounds) const;
  39318. void setControlVisible (const bool b) const;
  39319. };
  39320. #endif
  39321. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  39322. /********* End of inlined file: juce_ActiveXControlComponent.h *********/
  39323. #endif
  39324. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39325. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39326. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39327. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39328. class MidiInputSelectorComponentListBox;
  39329. /**
  39330. A component containing controls to let the user change the audio settings of
  39331. an AudioDeviceManager object.
  39332. Very easy to use - just create one of these and show it to the user.
  39333. @see AudioDeviceManager
  39334. */
  39335. class JUCE_API AudioDeviceSelectorComponent : public Component,
  39336. public ComboBoxListener,
  39337. public ButtonListener,
  39338. public ChangeListener
  39339. {
  39340. public:
  39341. /** Creates the component.
  39342. If your app needs only output channels, you might ask for a maximum of 0 input
  39343. channels, and the component won't display any options for choosing the input
  39344. channels. And likewise if you're doing an input-only app.
  39345. @param deviceManager the device manager that this component should control
  39346. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  39347. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  39348. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  39349. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  39350. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  39351. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  39352. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  39353. treated as a set of separate mono channels.
  39354. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  39355. are shown, with an "advanced" button that shows the rest of them
  39356. */
  39357. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  39358. const int minAudioInputChannels,
  39359. const int maxAudioInputChannels,
  39360. const int minAudioOutputChannels,
  39361. const int maxAudioOutputChannels,
  39362. const bool showMidiInputOptions,
  39363. const bool showMidiOutputSelector,
  39364. const bool showChannelsAsStereoPairs,
  39365. const bool hideAdvancedOptionsWithButton);
  39366. /** Destructor */
  39367. ~AudioDeviceSelectorComponent();
  39368. /** @internal */
  39369. void resized();
  39370. /** @internal */
  39371. void comboBoxChanged (ComboBox*);
  39372. /** @internal */
  39373. void buttonClicked (Button*);
  39374. /** @internal */
  39375. void changeListenerCallback (void*);
  39376. /** @internal */
  39377. void childBoundsChanged (Component*);
  39378. juce_UseDebuggingNewOperator
  39379. private:
  39380. AudioDeviceManager& deviceManager;
  39381. ComboBox* deviceTypeDropDown;
  39382. Label* deviceTypeDropDownLabel;
  39383. Component* audioDeviceSettingsComp;
  39384. String audioDeviceSettingsCompType;
  39385. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  39386. const bool showChannelsAsStereoPairs;
  39387. const bool hideAdvancedOptionsWithButton;
  39388. MidiInputSelectorComponentListBox* midiInputsList;
  39389. Label* midiInputsLabel;
  39390. ComboBox* midiOutputSelector;
  39391. Label* midiOutputLabel;
  39392. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  39393. const AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  39394. };
  39395. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  39396. /********* End of inlined file: juce_AudioDeviceSelectorComponent.h *********/
  39397. #endif
  39398. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39399. /********* Start of inlined file: juce_BubbleComponent.h *********/
  39400. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39401. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39402. /**
  39403. A component for showing a message or other graphics inside a speech-bubble-shaped
  39404. outline, pointing at a location on the screen.
  39405. This is a base class that just draws and positions the bubble shape, but leaves
  39406. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  39407. that draws a text message.
  39408. To use it, create your subclass, then either add it to a parent component or
  39409. put it on the desktop with addToDesktop (0), use setPosition() to
  39410. resize and position it, then make it visible.
  39411. @see BubbleMessageComponent
  39412. */
  39413. class JUCE_API BubbleComponent : public Component
  39414. {
  39415. protected:
  39416. /** Creates a BubbleComponent.
  39417. Your subclass will need to implement the getContentSize() and paintContent()
  39418. methods to draw the bubble's contents.
  39419. */
  39420. BubbleComponent();
  39421. public:
  39422. /** Destructor. */
  39423. ~BubbleComponent();
  39424. /** A list of permitted placements for the bubble, relative to the co-ordinates
  39425. at which it should be pointing.
  39426. @see setAllowedPlacement
  39427. */
  39428. enum BubblePlacement
  39429. {
  39430. above = 1,
  39431. below = 2,
  39432. left = 4,
  39433. right = 8
  39434. };
  39435. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  39436. point at which it's pointing.
  39437. By default when setPosition() is called, the bubble will place itself either
  39438. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  39439. the values in BubblePlacement to restrict this choice.
  39440. E.g. if you only want your bubble to appear above or below the target area,
  39441. use setAllowedPlacement (above | below);
  39442. @see BubblePlacement
  39443. */
  39444. void setAllowedPlacement (const int newPlacement);
  39445. /** Moves and resizes the bubble to point at a given component.
  39446. This will resize the bubble to fit its content, then find a position for it
  39447. so that it's next to, but doesn't overlap the given component.
  39448. It'll put itself either above, below, or to the side of the component depending
  39449. on where there's the most space, honouring any restrictions that were set
  39450. with setAllowedPlacement().
  39451. */
  39452. void setPosition (Component* componentToPointTo);
  39453. /** Moves and resizes the bubble to point at a given point.
  39454. This will resize the bubble to fit its content, then position it
  39455. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  39456. are relative to either the bubble component's parent component if it has one, or
  39457. they are screen co-ordinates if not.
  39458. It'll put itself either above, below, or to the side of this point, depending
  39459. on where there's the most space, honouring any restrictions that were set
  39460. with setAllowedPlacement().
  39461. */
  39462. void setPosition (const int arrowTipX,
  39463. const int arrowTipY);
  39464. /** Moves and resizes the bubble to point at a given rectangle.
  39465. This will resize the bubble to fit its content, then find a position for it
  39466. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  39467. co-ordinates are relative to either the bubble component's parent component
  39468. if it has one, or they are screen co-ordinates if not.
  39469. It'll put itself either above, below, or to the side of the component depending
  39470. on where there's the most space, honouring any restrictions that were set
  39471. with setAllowedPlacement().
  39472. */
  39473. void setPosition (const Rectangle& rectangleToPointTo);
  39474. protected:
  39475. /** Subclasses should override this to return the size of the content they
  39476. want to draw inside the bubble.
  39477. */
  39478. virtual void getContentSize (int& width, int& height) = 0;
  39479. /** Subclasses should override this to draw their bubble's contents.
  39480. The graphics object's clip region and the dimensions passed in here are
  39481. set up to paint just the rectangle inside the bubble.
  39482. */
  39483. virtual void paintContent (Graphics& g, int width, int height) = 0;
  39484. public:
  39485. /** @internal */
  39486. void paint (Graphics& g);
  39487. juce_UseDebuggingNewOperator
  39488. private:
  39489. Rectangle content;
  39490. int side, allowablePlacements;
  39491. float arrowTipX, arrowTipY;
  39492. DropShadowEffect shadow;
  39493. BubbleComponent (const BubbleComponent&);
  39494. const BubbleComponent& operator= (const BubbleComponent&);
  39495. };
  39496. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  39497. /********* End of inlined file: juce_BubbleComponent.h *********/
  39498. #endif
  39499. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39500. /********* Start of inlined file: juce_BubbleMessageComponent.h *********/
  39501. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39502. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39503. /**
  39504. A speech-bubble component that displays a short message.
  39505. This can be used to show a message with the tail of the speech bubble
  39506. pointing to a particular component or location on the screen.
  39507. @see BubbleComponent
  39508. */
  39509. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  39510. private Timer
  39511. {
  39512. public:
  39513. /** Creates a bubble component.
  39514. After creating one a BubbleComponent, do the following:
  39515. - add it to an appropriate parent component, or put it on the
  39516. desktop with Component::addToDesktop (0).
  39517. - use the showAt() method to show a message.
  39518. - it will make itself invisible after it times-out (and can optionally
  39519. also delete itself), or you can reuse it somewhere else by calling
  39520. showAt() again.
  39521. */
  39522. BubbleMessageComponent (const int fadeOutLengthMs = 150);
  39523. /** Destructor. */
  39524. ~BubbleMessageComponent();
  39525. /** Shows a message bubble at a particular position.
  39526. This shows the bubble with its stem pointing to the given location
  39527. (co-ordinates being relative to its parent component).
  39528. For details about exactly how it decides where to position itself, see
  39529. BubbleComponent::updatePosition().
  39530. @param x the x co-ordinate of end of the bubble's tail
  39531. @param y the y co-ordinate of end of the bubble's tail
  39532. @param message the text to display
  39533. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39534. from its parent compnent. If this is 0 or less, it
  39535. will stay there until manually removed.
  39536. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39537. mouse button is pressed (anywhere on the screen)
  39538. @param deleteSelfAfterUse if true, then the component will delete itself after
  39539. it becomes invisible
  39540. */
  39541. void showAt (int x, int y,
  39542. const String& message,
  39543. const int numMillisecondsBeforeRemoving,
  39544. const bool removeWhenMouseClicked = true,
  39545. const bool deleteSelfAfterUse = false);
  39546. /** Shows a message bubble next to a particular component.
  39547. This shows the bubble with its stem pointing at the given component.
  39548. For details about exactly how it decides where to position itself, see
  39549. BubbleComponent::updatePosition().
  39550. @param component the component that you want to point at
  39551. @param message the text to display
  39552. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  39553. from its parent compnent. If this is 0 or less, it
  39554. will stay there until manually removed.
  39555. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  39556. mouse button is pressed (anywhere on the screen)
  39557. @param deleteSelfAfterUse if true, then the component will delete itself after
  39558. it becomes invisible
  39559. */
  39560. void showAt (Component* const component,
  39561. const String& message,
  39562. const int numMillisecondsBeforeRemoving,
  39563. const bool removeWhenMouseClicked = true,
  39564. const bool deleteSelfAfterUse = false);
  39565. /** @internal */
  39566. void getContentSize (int& w, int& h);
  39567. /** @internal */
  39568. void paintContent (Graphics& g, int w, int h);
  39569. /** @internal */
  39570. void timerCallback();
  39571. juce_UseDebuggingNewOperator
  39572. private:
  39573. int fadeOutLength, mouseClickCounter;
  39574. TextLayout textLayout;
  39575. int64 expiryTime;
  39576. bool deleteAfterUse;
  39577. void init (const int numMillisecondsBeforeRemoving,
  39578. const bool removeWhenMouseClicked,
  39579. const bool deleteSelfAfterUse);
  39580. BubbleMessageComponent (const BubbleMessageComponent&);
  39581. const BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  39582. };
  39583. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  39584. /********* End of inlined file: juce_BubbleMessageComponent.h *********/
  39585. #endif
  39586. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39587. /********* Start of inlined file: juce_ColourSelector.h *********/
  39588. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  39589. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  39590. /**
  39591. A component that lets the user choose a colour.
  39592. This shows RGB sliders and a colourspace that the user can pick colours from.
  39593. This class is also a ChangeBroadcaster, so listeners can register to be told
  39594. when the colour changes.
  39595. */
  39596. class JUCE_API ColourSelector : public Component,
  39597. public ChangeBroadcaster,
  39598. protected SliderListener
  39599. {
  39600. public:
  39601. /** Options for the type of selector to show. These are passed into the constructor. */
  39602. enum ColourSelectorOptions
  39603. {
  39604. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  39605. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  39606. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  39607. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  39608. };
  39609. /** Creates a ColourSelector object.
  39610. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  39611. which of the selector's features should be visible.
  39612. The edgeGap value specifies the amount of space to leave around the edge.
  39613. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  39614. colourspace and hue selector components.
  39615. */
  39616. ColourSelector (const int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  39617. const int edgeGap = 4,
  39618. const int gapAroundColourSpaceComponent = 7);
  39619. /** Destructor. */
  39620. ~ColourSelector();
  39621. /** Returns the colour that the user has currently selected.
  39622. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  39623. register to be told when the colour changes.
  39624. @see setCurrentColour
  39625. */
  39626. const Colour getCurrentColour() const;
  39627. /** Changes the colour that is currently being shown.
  39628. */
  39629. void setCurrentColour (const Colour& newColour);
  39630. /** Tells the selector how many preset colour swatches you want to have on the component.
  39631. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39632. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39633. their values.
  39634. */
  39635. virtual int getNumSwatches() const;
  39636. /** Called by the selector to find out the colour of one of the swatches.
  39637. Your subclass should return the colour of the swatch with the given index.
  39638. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39639. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39640. their values.
  39641. */
  39642. virtual const Colour getSwatchColour (const int index) const;
  39643. /** Called by the selector when the user puts a new colour into one of the swatches.
  39644. Your subclass should change the colour of the swatch with the given index.
  39645. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  39646. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  39647. their values.
  39648. */
  39649. virtual void setSwatchColour (const int index, const Colour& newColour) const;
  39650. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39651. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39652. methods.
  39653. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39654. */
  39655. enum ColourIds
  39656. {
  39657. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  39658. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  39659. };
  39660. juce_UseDebuggingNewOperator
  39661. private:
  39662. friend class ColourSpaceView;
  39663. friend class HueSelectorComp;
  39664. Colour colour;
  39665. float h, s, v;
  39666. Slider* sliders[4];
  39667. Component* colourSpace;
  39668. Component* hueSelector;
  39669. VoidArray swatchComponents;
  39670. const int flags;
  39671. int topSpace, edgeGap;
  39672. void setHue (float newH);
  39673. void setSV (float newS, float newV);
  39674. void updateHSV();
  39675. void update();
  39676. void sliderValueChanged (Slider*);
  39677. void paint (Graphics& g);
  39678. void resized();
  39679. ColourSelector (const ColourSelector&);
  39680. const ColourSelector& operator= (const ColourSelector&);
  39681. // this constructor is here temporarily to prevent old code compiling, because the parameters
  39682. // have changed - if you get an error here, update your code to use the new constructor instead..
  39683. // (xxx - note to self: remember to remove this at some point in the future)
  39684. ColourSelector (const bool);
  39685. };
  39686. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  39687. /********* End of inlined file: juce_ColourSelector.h *********/
  39688. #endif
  39689. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  39690. #endif
  39691. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39692. /********* Start of inlined file: juce_MagnifierComponent.h *********/
  39693. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39694. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39695. /**
  39696. A component that contains another component, and can magnify or shrink it.
  39697. This component will continually update its size so that it fits the zoomed
  39698. version of the content component that you put inside it, so don't try to
  39699. change the size of this component directly - instead change that of the
  39700. content component.
  39701. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  39702. to remap mouse events correctly. This means that the content component won't
  39703. appear to be a direct child of this component, and instead will think its
  39704. on the desktop.
  39705. */
  39706. class JUCE_API MagnifierComponent : public Component
  39707. {
  39708. public:
  39709. /** Creates a MagnifierComponent.
  39710. This component will continually update its size so that it fits the zoomed
  39711. version of the content component that you put inside it, so don't try to
  39712. change the size of this component directly - instead change that of the
  39713. content component.
  39714. @param contentComponent the component to add as the magnified one
  39715. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  39716. be deleted when this component is deleted. If false,
  39717. it's the caller's responsibility to delete it later.
  39718. */
  39719. MagnifierComponent (Component* const contentComponent,
  39720. const bool deleteContentCompWhenNoLongerNeeded);
  39721. /** Destructor. */
  39722. ~MagnifierComponent();
  39723. /** Returns the current content component. */
  39724. Component* getContentComponent() const throw() { return content; }
  39725. /** Changes the zoom level.
  39726. The scale factor must be greater than zero. Values less than 1 will shrink the
  39727. image; values greater than 1 will multiply its size by this amount.
  39728. When this is called, this component will change its size to fit the full extent
  39729. of the newly zoomed content.
  39730. */
  39731. void setScaleFactor (double newScaleFactor);
  39732. /** Returns the current zoom factor. */
  39733. double getScaleFactor() const throw() { return scaleFactor; }
  39734. /** Changes the quality setting used to rescale the graphics.
  39735. */
  39736. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  39737. juce_UseDebuggingNewOperator
  39738. /** @internal */
  39739. void childBoundsChanged (Component*);
  39740. private:
  39741. Component* content;
  39742. Component* holderComp;
  39743. double scaleFactor;
  39744. ComponentPeer* peer;
  39745. bool deleteContent;
  39746. Graphics::ResamplingQuality quality;
  39747. void paint (Graphics& g);
  39748. void mouseDown (const MouseEvent& e);
  39749. void mouseUp (const MouseEvent& e);
  39750. void mouseDrag (const MouseEvent& e);
  39751. void mouseMove (const MouseEvent& e);
  39752. void mouseEnter (const MouseEvent& e);
  39753. void mouseExit (const MouseEvent& e);
  39754. void mouseWheelMove (const MouseEvent& e, float, float);
  39755. int scaleInt (const int n) const throw();
  39756. MagnifierComponent (const MagnifierComponent&);
  39757. const MagnifierComponent& operator= (const MagnifierComponent&);
  39758. };
  39759. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  39760. /********* End of inlined file: juce_MagnifierComponent.h *********/
  39761. #endif
  39762. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39763. /********* Start of inlined file: juce_MidiKeyboardComponent.h *********/
  39764. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39765. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  39766. /**
  39767. A component that displays a piano keyboard, whose notes can be clicked on.
  39768. This component will mimic a physical midi keyboard, showing the current state of
  39769. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  39770. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  39771. Another feature is that the computer keyboard can also be used to play notes. By
  39772. default it maps the top two rows of a standard querty keyboard to the notes, but
  39773. these can be remapped if needed. It will only respond to keypresses when it has
  39774. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  39775. The component is also a ChangeBroadcaster, so if you want to be informed when the
  39776. keyboard is scrolled, you can register a ChangeListener for callbacks.
  39777. @see MidiKeyboardState
  39778. */
  39779. class JUCE_API MidiKeyboardComponent : public Component,
  39780. public MidiKeyboardStateListener,
  39781. public ChangeBroadcaster,
  39782. private Timer,
  39783. private AsyncUpdater
  39784. {
  39785. public:
  39786. /** The direction of the keyboard.
  39787. @see setOrientation
  39788. */
  39789. enum Orientation
  39790. {
  39791. horizontalKeyboard,
  39792. verticalKeyboardFacingLeft,
  39793. verticalKeyboardFacingRight,
  39794. };
  39795. /** Creates a MidiKeyboardComponent.
  39796. @param state the midi keyboard model that this component will represent
  39797. @param orientation whether the keyboard is horizonal or vertical
  39798. */
  39799. MidiKeyboardComponent (MidiKeyboardState& state,
  39800. const Orientation orientation);
  39801. /** Destructor. */
  39802. ~MidiKeyboardComponent();
  39803. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  39804. on the component.
  39805. Values are 0 to 1.0, where 1.0 is the heaviest.
  39806. @see setMidiChannel
  39807. */
  39808. void setVelocity (const float velocity, const bool useMousePositionForVelocity);
  39809. /** Changes the midi channel number that will be used for events triggered by clicking
  39810. on the component.
  39811. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  39812. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  39813. Although this is the channel used for outgoing events, the component can display
  39814. incoming events from more than one channel - see setMidiChannelsToDisplay()
  39815. @see setVelocity
  39816. */
  39817. void setMidiChannel (const int midiChannelNumber);
  39818. /** Returns the midi channel that the keyboard is using for midi messages.
  39819. @see setMidiChannel
  39820. */
  39821. int getMidiChannel() const throw() { return midiChannel; }
  39822. /** Sets a mask to indicate which incoming midi channels should be represented by
  39823. key movements.
  39824. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  39825. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  39826. in this mask, the on-screen keys will also go down.
  39827. By default, this mask is set to 0xffff (all channels displayed).
  39828. @see setMidiChannel
  39829. */
  39830. void setMidiChannelsToDisplay (const int midiChannelMask);
  39831. /** Returns the current set of midi channels represented by the component.
  39832. This is the value that was set with setMidiChannelsToDisplay().
  39833. */
  39834. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  39835. /** Changes the width used to draw the white keys. */
  39836. void setKeyWidth (const float widthInPixels);
  39837. /** Returns the width that was set by setKeyWidth(). */
  39838. float getKeyWidth() const throw() { return keyWidth; }
  39839. /** Changes the keyboard's current direction. */
  39840. void setOrientation (const Orientation newOrientation);
  39841. /** Returns the keyboard's current direction. */
  39842. const Orientation getOrientation() const throw() { return orientation; }
  39843. /** Sets the range of midi notes that the keyboard will be limited to.
  39844. By default the range is 0 to 127 (inclusive), but you can limit this if you
  39845. only want a restricted set of the keys to be shown.
  39846. Note that the values here are inclusive and must be between 0 and 127.
  39847. */
  39848. void setAvailableRange (const int lowestNote,
  39849. const int highestNote);
  39850. /** Returns the first note in the available range.
  39851. @see setAvailableRange
  39852. */
  39853. int getRangeStart() const throw() { return rangeStart; }
  39854. /** Returns the last note in the available range.
  39855. @see setAvailableRange
  39856. */
  39857. int getRangeEnd() const throw() { return rangeEnd; }
  39858. /** If the keyboard extends beyond the size of the component, this will scroll
  39859. it to show the given key at the start.
  39860. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  39861. base class to send a callback to any ChangeListeners that have been registered.
  39862. */
  39863. void setLowestVisibleKey (int noteNumber);
  39864. /** Returns the number of the first key shown in the component.
  39865. @see setLowestVisibleKey
  39866. */
  39867. int getLowestVisibleKey() const throw() { return firstKey; }
  39868. /** Returns the length of the black notes.
  39869. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  39870. */
  39871. int getBlackNoteLength() const throw() { return blackNoteLength; }
  39872. /** If set to true, then scroll buttons will appear at either end of the keyboard
  39873. if there are too many notes to fit them all in the component at once.
  39874. */
  39875. void setScrollButtonsVisible (const bool canScroll);
  39876. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  39877. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39878. methods.
  39879. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39880. */
  39881. enum ColourIds
  39882. {
  39883. whiteNoteColourId = 0x1005000,
  39884. blackNoteColourId = 0x1005001,
  39885. keySeparatorLineColourId = 0x1005002,
  39886. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  39887. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  39888. textLabelColourId = 0x1005005,
  39889. upDownButtonBackgroundColourId = 0x1005006,
  39890. upDownButtonArrowColourId = 0x1005007
  39891. };
  39892. /** Returns the position within the component of the left-hand edge of a key.
  39893. Depending on the keyboard's orientation, this may be a horizontal or vertical
  39894. distance, in either direction.
  39895. */
  39896. int getKeyStartPosition (const int midiNoteNumber) const;
  39897. /** Deletes all key-mappings.
  39898. @see setKeyPressForNote
  39899. */
  39900. void clearKeyMappings();
  39901. /** Maps a key-press to a given note.
  39902. @param key the key that should trigger the note
  39903. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  39904. be. The actual midi note that gets played will be
  39905. this value + (12 * the current base octave). To change
  39906. the base octave, see setKeyPressBaseOctave()
  39907. */
  39908. void setKeyPressForNote (const KeyPress& key,
  39909. const int midiNoteOffsetFromC);
  39910. /** Removes any key-mappings for a given note.
  39911. For a description of what the note number means, see setKeyPressForNote().
  39912. */
  39913. void removeKeyPressForNote (const int midiNoteOffsetFromC);
  39914. /** Changes the base note above which key-press-triggered notes are played.
  39915. The set of key-mappings that trigger notes can be moved up and down to cover
  39916. the entire scale using this method.
  39917. The value passed in is an octave number between 0 and 10 (inclusive), and
  39918. indicates which C is the base note to which the key-mapped notes are
  39919. relative.
  39920. */
  39921. void setKeyPressBaseOctave (const int newOctaveNumber);
  39922. /** This sets the octave number which is shown as the octave number for middle C.
  39923. This affects only the default implementation of getWhiteNoteText(), which
  39924. passes this octave number to MidiMessage::getMidiNoteName() in order to
  39925. get the note text. See MidiMessage::getMidiNoteName() for more info about
  39926. the parameter.
  39927. By default this value is set to 3.
  39928. @see getOctaveForMiddleC
  39929. */
  39930. void setOctaveForMiddleC (const int octaveNumForMiddleC) throw();
  39931. /** This returns the value set by setOctaveForMiddleC().
  39932. @see setOctaveForMiddleC
  39933. */
  39934. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  39935. /** @internal */
  39936. void paint (Graphics& g);
  39937. /** @internal */
  39938. void resized();
  39939. /** @internal */
  39940. void mouseMove (const MouseEvent& e);
  39941. /** @internal */
  39942. void mouseDrag (const MouseEvent& e);
  39943. /** @internal */
  39944. void mouseDown (const MouseEvent& e);
  39945. /** @internal */
  39946. void mouseUp (const MouseEvent& e);
  39947. /** @internal */
  39948. void mouseEnter (const MouseEvent& e);
  39949. /** @internal */
  39950. void mouseExit (const MouseEvent& e);
  39951. /** @internal */
  39952. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  39953. /** @internal */
  39954. void timerCallback();
  39955. /** @internal */
  39956. bool keyStateChanged (const bool isKeyDown);
  39957. /** @internal */
  39958. void focusLost (FocusChangeType cause);
  39959. /** @internal */
  39960. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  39961. /** @internal */
  39962. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  39963. /** @internal */
  39964. void handleAsyncUpdate();
  39965. /** @internal */
  39966. void colourChanged();
  39967. juce_UseDebuggingNewOperator
  39968. protected:
  39969. friend class MidiKeyboardUpDownButton;
  39970. /** Draws a white note in the given rectangle.
  39971. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39972. currently pressed down.
  39973. When doing this, be sure to note the keyboard's orientation.
  39974. */
  39975. virtual void drawWhiteNote (int midiNoteNumber,
  39976. Graphics& g,
  39977. int x, int y, int w, int h,
  39978. bool isDown, bool isOver,
  39979. const Colour& lineColour,
  39980. const Colour& textColour);
  39981. /** Draws a black note in the given rectangle.
  39982. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  39983. currently pressed down.
  39984. When doing this, be sure to note the keyboard's orientation.
  39985. */
  39986. virtual void drawBlackNote (int midiNoteNumber,
  39987. Graphics& g,
  39988. int x, int y, int w, int h,
  39989. bool isDown, bool isOver,
  39990. const Colour& noteFillColour);
  39991. /** Allows text to be drawn on the white notes.
  39992. By default this is used to label the C in each octave, but could be used for other things.
  39993. @see setOctaveForMiddleC
  39994. */
  39995. virtual const String getWhiteNoteText (const int midiNoteNumber);
  39996. /** Draws the up and down buttons that change the base note. */
  39997. virtual void drawUpDownButton (Graphics& g, int w, int h,
  39998. const bool isMouseOver,
  39999. const bool isButtonPressed,
  40000. const bool movesOctavesUp);
  40001. /** Callback when the mouse is clicked on a key.
  40002. You could use this to do things like handle right-clicks on keys, etc.
  40003. Return true if you want the click to trigger the note, or false if you
  40004. want to handle it yourself and not have the note played.
  40005. @see mouseDraggedToKey
  40006. */
  40007. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  40008. /** Callback when the mouse is dragged from one key onto another.
  40009. @see mouseDownOnKey
  40010. */
  40011. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  40012. /** Calculates the positon of a given midi-note.
  40013. This can be overridden to create layouts with custom key-widths.
  40014. @param midiNoteNumber the note to find
  40015. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  40016. @param x the x position of the left-hand edge of the key (this method
  40017. always works in terms of a horizontal keyboard)
  40018. @param w the width of the key
  40019. */
  40020. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  40021. int& x, int& w) const;
  40022. private:
  40023. MidiKeyboardState& state;
  40024. int xOffset, blackNoteLength;
  40025. float keyWidth;
  40026. Orientation orientation;
  40027. int midiChannel, midiInChannelMask;
  40028. float velocity;
  40029. int noteUnderMouse, mouseDownNote;
  40030. BitArray keysPressed, keysCurrentlyDrawnDown;
  40031. int rangeStart, rangeEnd, firstKey;
  40032. bool canScroll, mouseDragging, useMousePositionForVelocity;
  40033. Button* scrollDown;
  40034. Button* scrollUp;
  40035. Array <KeyPress> keyPresses;
  40036. Array <int> keyPressNotes;
  40037. int keyMappingOctave;
  40038. int octaveNumForMiddleC;
  40039. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  40040. int xyToNote (int x, int y, float& mousePositionVelocity);
  40041. int remappedXYToNote (int x, int y, float& mousePositionVelocity) const;
  40042. void resetAnyKeysInUse();
  40043. void updateNoteUnderMouse (int x, int y);
  40044. void repaintNote (const int midiNoteNumber);
  40045. MidiKeyboardComponent (const MidiKeyboardComponent&);
  40046. const MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  40047. };
  40048. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  40049. /********* End of inlined file: juce_MidiKeyboardComponent.h *********/
  40050. #endif
  40051. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40052. /********* Start of inlined file: juce_NSViewComponent.h *********/
  40053. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40054. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40055. #if ! DOXYGEN
  40056. class NSViewComponentInternal;
  40057. #endif
  40058. #if JUCE_MAC || DOXYGEN
  40059. /**
  40060. A Mac-specific class that can create and embed an NSView inside itself.
  40061. To use it, create one of these, put it in place and make sure it's visible in a
  40062. window, then use setView() to assign an NSView to it. The view will then be
  40063. moved and resized to follow the movements of this component.
  40064. Of course, since the view is a native object, it'll obliterate any
  40065. juce components that may overlap this component, but that's life.
  40066. */
  40067. class JUCE_API NSViewComponent : public Component
  40068. {
  40069. public:
  40070. /** Create an initially-empty container. */
  40071. NSViewComponent();
  40072. /** Destructor. */
  40073. ~NSViewComponent();
  40074. /** Assigns an NSView to this peer.
  40075. The view will be retained and released by this component for as long as
  40076. it is needed. To remove the current view, just call setView (0).
  40077. Note: a void* is used here to avoid including the cocoa headers as
  40078. part of the juce.h, but the method expects an NSView*.
  40079. */
  40080. void setView (void* nsView);
  40081. /** Returns the current NSView.
  40082. Note: a void* is returned here to avoid including the cocoa headers as
  40083. a requirement of juce.h, so you should just cast the object to an NSView*.
  40084. */
  40085. void* getView() const;
  40086. /** @internal */
  40087. void paint (Graphics& g);
  40088. juce_UseDebuggingNewOperator
  40089. private:
  40090. friend class NSViewComponentInternal;
  40091. ScopedPointer <NSViewComponentInternal> info;
  40092. NSViewComponent (const NSViewComponent&);
  40093. const NSViewComponent& operator= (const NSViewComponent&);
  40094. };
  40095. #endif
  40096. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  40097. /********* End of inlined file: juce_NSViewComponent.h *********/
  40098. #endif
  40099. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40100. /********* Start of inlined file: juce_OpenGLComponent.h *********/
  40101. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40102. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40103. // this is used to disable OpenGL, and is defined in juce_Config.h
  40104. #if JUCE_OPENGL || DOXYGEN
  40105. class OpenGLComponentWatcher;
  40106. /**
  40107. Represents the various properties of an OpenGL bitmap format.
  40108. @see OpenGLComponent::setPixelFormat
  40109. */
  40110. class JUCE_API OpenGLPixelFormat
  40111. {
  40112. public:
  40113. /** Creates an OpenGLPixelFormat.
  40114. The default constructor just initialises the object as a simple 8-bit
  40115. RGBA format.
  40116. */
  40117. OpenGLPixelFormat (const int bitsPerRGBComponent = 8,
  40118. const int alphaBits = 8,
  40119. const int depthBufferBits = 16,
  40120. const int stencilBufferBits = 0) throw();
  40121. int redBits; /**< The number of bits per pixel to use for the red channel. */
  40122. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  40123. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  40124. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  40125. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  40126. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  40127. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  40128. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  40129. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  40130. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  40131. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  40132. /** Returns a list of all the pixel formats that can be used in this system.
  40133. A reference component is needed in case there are multiple screens with different
  40134. capabilities - in which case, the one that the component is on will be used.
  40135. */
  40136. static void getAvailablePixelFormats (Component* component,
  40137. OwnedArray <OpenGLPixelFormat>& results);
  40138. bool operator== (const OpenGLPixelFormat&) const throw();
  40139. juce_UseDebuggingNewOperator
  40140. };
  40141. /**
  40142. A base class for types of OpenGL context.
  40143. An OpenGLComponent will supply its own context for drawing in its window.
  40144. */
  40145. class JUCE_API OpenGLContext
  40146. {
  40147. public:
  40148. /** Destructor. */
  40149. virtual ~OpenGLContext();
  40150. /** Makes this context the currently active one. */
  40151. virtual bool makeActive() const throw() = 0;
  40152. /** If this context is currently active, it is disactivated. */
  40153. virtual bool makeInactive() const throw() = 0;
  40154. /** Returns true if this context is currently active. */
  40155. virtual bool isActive() const throw() = 0;
  40156. /** Swaps the buffers (if the context can do this). */
  40157. virtual void swapBuffers() = 0;
  40158. /** Sets whether the context checks the vertical sync before swapping.
  40159. The value is the number of frames to allow between buffer-swapping. This is
  40160. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  40161. and greater numbers indicate that it should swap less often.
  40162. Returns true if it sets the value successfully.
  40163. */
  40164. virtual bool setSwapInterval (const int numFramesPerSwap) = 0;
  40165. /** Returns the current swap-sync interval.
  40166. See setSwapInterval() for info about the value returned.
  40167. */
  40168. virtual int getSwapInterval() const = 0;
  40169. /** Returns the pixel format being used by this context. */
  40170. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  40171. /** For windowed contexts, this moves the context within the bounds of
  40172. its parent window.
  40173. */
  40174. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  40175. /** For windowed contexts, this triggers a repaint of the window.
  40176. (Not relevent on all platforms).
  40177. */
  40178. virtual void repaint() = 0;
  40179. /** Returns an OS-dependent handle to the raw GL context.
  40180. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  40181. a GLXContext.
  40182. */
  40183. virtual void* getRawContext() const throw() = 0;
  40184. /** This tries to create a context that can be used for drawing into the
  40185. area occupied by the specified component.
  40186. Note that you probably shouldn't use this method directly unless you know what
  40187. you're doing - the OpenGLComponent calls this and manages the context for you.
  40188. */
  40189. static OpenGLContext* createContextForWindow (Component* componentToDrawTo,
  40190. const OpenGLPixelFormat& pixelFormat,
  40191. const OpenGLContext* const contextToShareWith);
  40192. /** Returns the context that's currently in active use by the calling thread.
  40193. Returns 0 if there isn't an active context.
  40194. */
  40195. static OpenGLContext* getCurrentContext();
  40196. juce_UseDebuggingNewOperator
  40197. protected:
  40198. OpenGLContext() throw();
  40199. };
  40200. /**
  40201. A component that contains an OpenGL canvas.
  40202. Override this, add it to whatever component you want to, and use the renderOpenGL()
  40203. method to draw its contents.
  40204. */
  40205. class JUCE_API OpenGLComponent : public Component
  40206. {
  40207. public:
  40208. /** Creates an OpenGLComponent.
  40209. */
  40210. OpenGLComponent();
  40211. /** Destructor. */
  40212. ~OpenGLComponent();
  40213. /** Changes the pixel format used by this component.
  40214. @see OpenGLPixelFormat::getAvailablePixelFormats()
  40215. */
  40216. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  40217. /** Returns the pixel format that this component is currently using. */
  40218. const OpenGLPixelFormat getPixelFormat() const;
  40219. /** Specifies an OpenGL context which should be shared with the one that this
  40220. component is using.
  40221. This is an OpenGL feature that lets two contexts share their texture data.
  40222. Note that this pointer is stored by the component, and when the component
  40223. needs to recreate its internal context for some reason, the same context
  40224. will be used again to share lists. So if you pass a context in here,
  40225. don't delete the context while this component is still using it! You can
  40226. call shareWith (0) to stop this component from sharing with it.
  40227. */
  40228. void shareWith (OpenGLContext* contextToShareListsWith);
  40229. /** Returns the context that this component is sharing with.
  40230. @see shareWith
  40231. */
  40232. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  40233. /** Flips the openGL buffers over. */
  40234. void swapBuffers();
  40235. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  40236. When this is called, makeCurrentContextActive() will already have been called
  40237. for you, so you just need to draw.
  40238. */
  40239. virtual void renderOpenGL() = 0;
  40240. /** This method is called when the component creates a new OpenGL context.
  40241. A new context may be created when the component is first used, or when it
  40242. is moved to a different window, or when the window is hidden and re-shown,
  40243. etc.
  40244. You can use this callback as an opportunity to set up things like textures
  40245. that your context needs.
  40246. New contexts are created on-demand by the makeCurrentContextActive() method - so
  40247. if the context is deleted, e.g. by changing the pixel format or window, no context
  40248. will be created until the next call to makeCurrentContextActive(), which will
  40249. synchronously create one and call this method. This means that if you're using
  40250. a non-GUI thread for rendering, you can make sure this method is be called by
  40251. your renderer thread.
  40252. When this callback happens, the context will already have been made current
  40253. using the makeCurrentContextActive() method, so there's no need to call it
  40254. again in your code.
  40255. */
  40256. virtual void newOpenGLContextCreated() = 0;
  40257. /** Returns the context that will draw into this component.
  40258. This may return 0 if the component is currently invisible or hasn't currently
  40259. got a context. The context object can be deleted and a new one created during
  40260. the lifetime of this component, and there may be times when it doesn't have one.
  40261. @see newOpenGLContextCreated()
  40262. */
  40263. OpenGLContext* getCurrentContext() const throw() { return context; }
  40264. /** Makes this component the current openGL context.
  40265. You might want to use this in things like your resize() method, before calling
  40266. GL commands.
  40267. If this returns false, then the context isn't active, so you should avoid
  40268. making any calls.
  40269. This call may actually create a context if one isn't currently initialised. If
  40270. it does this, it will also synchronously call the newOpenGLContextCreated()
  40271. method to let you initialise it as necessary.
  40272. @see OpenGLContext::makeActive
  40273. */
  40274. bool makeCurrentContextActive();
  40275. /** Stops the current component being the active OpenGL context.
  40276. This is the opposite of makeCurrentContextActive()
  40277. @see OpenGLContext::makeInactive
  40278. */
  40279. void makeCurrentContextInactive();
  40280. /** Returns true if this component is the active openGL context for the
  40281. current thread.
  40282. @see OpenGLContext::isActive
  40283. */
  40284. bool isActiveContext() const throw();
  40285. /** Calls the rendering callback, and swaps the buffers afterwards.
  40286. This is called automatically by paint() when the component needs to be rendered.
  40287. It can be overridden if you need to decouple the rendering from the paint callback
  40288. and render with a custom thread.
  40289. Returns true if the operation succeeded.
  40290. */
  40291. virtual bool renderAndSwapBuffers();
  40292. /** This returns a critical section that can be used to lock the current context.
  40293. Because the context that is used by this component can change, e.g. when the
  40294. component is shown or hidden, then if you're rendering to it on a background
  40295. thread, this allows you to lock the context for the duration of your rendering
  40296. routine.
  40297. */
  40298. CriticalSection& getContextLock() throw() { return contextLock; }
  40299. /** @internal */
  40300. void paint (Graphics& g);
  40301. /** Returns the native handle of an embedded heavyweight window, if there is one.
  40302. E.g. On windows, this will return the HWND of the sub-window containing
  40303. the opengl context, on the mac it'll be the NSOpenGLView.
  40304. */
  40305. void* getNativeWindowHandle() const;
  40306. juce_UseDebuggingNewOperator
  40307. private:
  40308. friend class OpenGLComponentWatcher;
  40309. OpenGLComponentWatcher* componentWatcher;
  40310. OpenGLContext* context;
  40311. OpenGLContext* contextToShareListsWith;
  40312. CriticalSection contextLock;
  40313. OpenGLPixelFormat preferredPixelFormat;
  40314. bool needToUpdateViewport;
  40315. void deleteContext();
  40316. void updateContextPosition();
  40317. void internalRepaint (int x, int y, int w, int h);
  40318. OpenGLComponent (const OpenGLComponent&);
  40319. const OpenGLComponent& operator= (const OpenGLComponent&);
  40320. };
  40321. #endif
  40322. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  40323. /********* End of inlined file: juce_OpenGLComponent.h *********/
  40324. #endif
  40325. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40326. /********* Start of inlined file: juce_PreferencesPanel.h *********/
  40327. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40328. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40329. /**
  40330. A component with a set of buttons at the top for changing between pages of
  40331. preferences.
  40332. This is just a handy way of writing a Mac-style preferences panel where you
  40333. have a row of buttons along the top for the different preference categories,
  40334. each button having an icon above its name. Clicking these will show an
  40335. appropriate prefs page below it.
  40336. You can either put one of these inside your own component, or just use the
  40337. showInDialogBox() method to show it in a window and run it modally.
  40338. To use it, just add a set of named pages with the addSettingsPage() method,
  40339. and implement the createComponentForPage() method to create suitable components
  40340. for each of these pages.
  40341. */
  40342. class JUCE_API PreferencesPanel : public Component,
  40343. private ButtonListener
  40344. {
  40345. public:
  40346. /** Creates an empty panel.
  40347. Use addSettingsPage() to add some pages to it in your constructor.
  40348. */
  40349. PreferencesPanel();
  40350. /** Destructor. */
  40351. ~PreferencesPanel();
  40352. /** Creates a page using a set of drawables to define the page's icon.
  40353. Note that the other version of this method is much easier if you're using
  40354. an image instead of a custom drawable.
  40355. @param pageTitle the name of this preferences page - you'll need to
  40356. make sure your createComponentForPage() method creates
  40357. a suitable component when it is passed this name
  40358. @param normalIcon the drawable to display in the page's button normally
  40359. @param overIcon the drawable to display in the page's button when the mouse is over
  40360. @param downIcon the drawable to display in the page's button when the button is down
  40361. @see DrawableButton
  40362. */
  40363. void addSettingsPage (const String& pageTitle,
  40364. const Drawable* normalIcon,
  40365. const Drawable* overIcon,
  40366. const Drawable* downIcon);
  40367. /** Creates a page using a set of drawables to define the page's icon.
  40368. The other version of this method gives you more control over the icon, but this
  40369. one is much easier if you're just loading it from a file.
  40370. @param pageTitle the name of this preferences page - you'll need to
  40371. make sure your createComponentForPage() method creates
  40372. a suitable component when it is passed this name
  40373. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  40374. For this to look good, you'll probably want to use a nice
  40375. transparent png file.
  40376. @param imageDataSize the size of the image data, in bytes
  40377. */
  40378. void addSettingsPage (const String& pageTitle,
  40379. const char* imageData,
  40380. const int imageDataSize);
  40381. /** Utility method to display this panel in a DialogWindow.
  40382. Calling this will create a DialogWindow containing this panel with the
  40383. given size and title, and will run it modally, returning when the user
  40384. closes the dialog box.
  40385. */
  40386. void showInDialogBox (const String& dialogtitle,
  40387. int dialogWidth,
  40388. int dialogHeight,
  40389. const Colour& backgroundColour = Colours::white);
  40390. /** Subclasses must override this to return a component for each preferences page.
  40391. The subclass should return a pointer to a new component representing the named
  40392. page, which the panel will then display.
  40393. The panel will delete the component later when the user goes to another page
  40394. or deletes the panel.
  40395. */
  40396. virtual Component* createComponentForPage (const String& pageName) = 0;
  40397. /** Changes the current page being displayed. */
  40398. void setCurrentPage (const String& pageName);
  40399. /** @internal */
  40400. void resized();
  40401. /** @internal */
  40402. void paint (Graphics& g);
  40403. /** @internal */
  40404. void buttonClicked (Button* button);
  40405. juce_UseDebuggingNewOperator
  40406. private:
  40407. String currentPageName;
  40408. ScopedPointer <Component> currentPage;
  40409. int buttonSize;
  40410. PreferencesPanel (const PreferencesPanel&);
  40411. const PreferencesPanel& operator= (const PreferencesPanel&);
  40412. };
  40413. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  40414. /********* End of inlined file: juce_PreferencesPanel.h *********/
  40415. #endif
  40416. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40417. /********* Start of inlined file: juce_QuickTimeMovieComponent.h *********/
  40418. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40419. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40420. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  40421. // amalgamated build)
  40422. #if JUCE_WINDOWS
  40423. typedef ActiveXControlComponent QTCompBaseClass;
  40424. #elif JUCE_MAC
  40425. typedef NSViewComponent QTCompBaseClass;
  40426. #endif
  40427. // this is used to disable QuickTime, and is defined in juce_Config.h
  40428. #if JUCE_QUICKTIME || DOXYGEN
  40429. /**
  40430. A window that can play back a QuickTime movie.
  40431. */
  40432. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  40433. {
  40434. public:
  40435. /** Creates a QuickTimeMovieComponent, initially blank.
  40436. Use the loadMovie() method to load a movie once you've added the
  40437. component to a window, (or put it on the desktop as a heavyweight window).
  40438. Loading a movie when the component isn't visible can cause problems, as
  40439. QuickTime needs a window handle to initialise properly.
  40440. */
  40441. QuickTimeMovieComponent();
  40442. /** Destructor. */
  40443. ~QuickTimeMovieComponent();
  40444. /** Returns true if QT is installed and working on this machine.
  40445. */
  40446. static bool isQuickTimeAvailable() throw();
  40447. /** Tries to load a QuickTime movie from a file into the player.
  40448. It's best to call this function once you've added the component to a window,
  40449. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40450. component isn't visible can cause problems, because QuickTime needs a window
  40451. handle to do its stuff.
  40452. @param movieFile the .mov file to open
  40453. @param isControllerVisible whether to show a controller bar at the bottom
  40454. @returns true if the movie opens successfully
  40455. */
  40456. bool loadMovie (const File& movieFile,
  40457. const bool isControllerVisible);
  40458. /** Tries to load a QuickTime movie from a URL into the player.
  40459. It's best to call this function once you've added the component to a window,
  40460. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40461. component isn't visible can cause problems, because QuickTime needs a window
  40462. handle to do its stuff.
  40463. @param movieURL the .mov file to open
  40464. @param isControllerVisible whether to show a controller bar at the bottom
  40465. @returns true if the movie opens successfully
  40466. */
  40467. bool loadMovie (const URL& movieURL,
  40468. const bool isControllerVisible);
  40469. /** Tries to load a QuickTime movie from a stream into the player.
  40470. It's best to call this function once you've added the component to a window,
  40471. (or put it on the desktop as a heavyweight window). Loading a movie when the
  40472. component isn't visible can cause problems, because QuickTime needs a window
  40473. handle to do its stuff.
  40474. @param movieStream a stream containing a .mov file. The component may try
  40475. to read the whole stream before playing, rather than
  40476. streaming from it.
  40477. @param isControllerVisible whether to show a controller bar at the bottom
  40478. @returns true if the movie opens successfully
  40479. */
  40480. bool loadMovie (InputStream* movieStream,
  40481. const bool isControllerVisible);
  40482. /** Closes the movie, if one is open. */
  40483. void closeMovie();
  40484. /** Returns the movie file that is currently open.
  40485. If there isn't one, this returns File::nonexistent
  40486. */
  40487. const File getCurrentMovieFile() const;
  40488. /** Returns true if there's currently a movie open. */
  40489. bool isMovieOpen() const;
  40490. /** Returns the length of the movie, in seconds. */
  40491. double getMovieDuration() const;
  40492. /** Returns the movie's natural size, in pixels.
  40493. You can use this to resize the component to show the movie at its preferred
  40494. scale.
  40495. If no movie is loaded, the size returned will be 0 x 0.
  40496. */
  40497. void getMovieNormalSize (int& width, int& height) const;
  40498. /** This will position the component within a given area, keeping its aspect
  40499. ratio correct according to the movie's normal size.
  40500. The component will be made as large as it can go within the space, and will
  40501. be aligned according to the justification value if this means there are gaps at
  40502. the top or sides.
  40503. */
  40504. void setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  40505. const RectanglePlacement& placement);
  40506. /** Starts the movie playing. */
  40507. void play();
  40508. /** Stops the movie playing. */
  40509. void stop();
  40510. /** Returns true if the movie is currently playing. */
  40511. bool isPlaying() const;
  40512. /** Moves the movie's position back to the start. */
  40513. void goToStart();
  40514. /** Sets the movie's position to a given time. */
  40515. void setPosition (const double seconds);
  40516. /** Returns the current play position of the movie. */
  40517. double getPosition() const;
  40518. /** Changes the movie playback rate.
  40519. A value of 1 is normal speed, greater values play it proportionately faster,
  40520. smaller values play it slower.
  40521. */
  40522. void setSpeed (const float newSpeed);
  40523. /** Changes the movie's playback volume.
  40524. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  40525. */
  40526. void setMovieVolume (const float newVolume);
  40527. /** Returns the movie's playback volume.
  40528. @returns the volume in the range 0 (silent) to 1.0 (full)
  40529. */
  40530. float getMovieVolume() const;
  40531. /** Tells the movie whether it should loop. */
  40532. void setLooping (const bool shouldLoop);
  40533. /** Returns true if the movie is currently looping.
  40534. @see setLooping
  40535. */
  40536. bool isLooping() const;
  40537. /** True if the native QuickTime controller bar is shown in the window.
  40538. @see loadMovie
  40539. */
  40540. bool isControllerVisible() const;
  40541. /** @internal */
  40542. void paint (Graphics& g);
  40543. juce_UseDebuggingNewOperator
  40544. private:
  40545. File movieFile;
  40546. bool movieLoaded, controllerVisible, looping;
  40547. #if JUCE_WINDOWS
  40548. /** @internal */
  40549. void parentHierarchyChanged();
  40550. /** @internal */
  40551. void visibilityChanged();
  40552. void createControlIfNeeded();
  40553. bool isControlCreated() const;
  40554. void* internal;
  40555. #else
  40556. void* movie;
  40557. #endif
  40558. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  40559. const QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  40560. };
  40561. #endif
  40562. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  40563. /********* End of inlined file: juce_QuickTimeMovieComponent.h *********/
  40564. #endif
  40565. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40566. /********* Start of inlined file: juce_SystemTrayIconComponent.h *********/
  40567. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40568. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40569. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  40570. /**
  40571. On Windows only, this component sits in the taskbar tray as a small icon.
  40572. To use it, just create one of these components, but don't attempt to make it
  40573. visible, add it to a parent, or put it on the desktop.
  40574. You can then call setIconImage() to create an icon for it in the taskbar.
  40575. To change the icon's tooltip, you can use setIconTooltip().
  40576. To respond to mouse-events, you can override the normal mouseDown(),
  40577. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  40578. position will not be valid, you can use this to respond to clicks. Traditionally
  40579. you'd use a left-click to show your application's window, and a right-click
  40580. to show a pop-up menu.
  40581. */
  40582. class JUCE_API SystemTrayIconComponent : public Component
  40583. {
  40584. public:
  40585. SystemTrayIconComponent();
  40586. /** Destructor. */
  40587. ~SystemTrayIconComponent();
  40588. /** Changes the image shown in the taskbar.
  40589. */
  40590. void setIconImage (const Image& newImage);
  40591. /** Changes the tooltip that Windows shows above the icon. */
  40592. void setIconTooltip (const String& tooltip);
  40593. #if JUCE_LINUX
  40594. /** @internal */
  40595. void paint (Graphics& g);
  40596. #endif
  40597. juce_UseDebuggingNewOperator
  40598. private:
  40599. SystemTrayIconComponent (const SystemTrayIconComponent&);
  40600. const SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  40601. };
  40602. #endif
  40603. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  40604. /********* End of inlined file: juce_SystemTrayIconComponent.h *********/
  40605. #endif
  40606. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40607. /********* Start of inlined file: juce_WebBrowserComponent.h *********/
  40608. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40609. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40610. #if JUCE_WEB_BROWSER || DOXYGEN
  40611. #if ! DOXYGEN
  40612. class WebBrowserComponentInternal;
  40613. #endif
  40614. /**
  40615. A component that displays an embedded web browser.
  40616. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  40617. Windows, probably IE.
  40618. */
  40619. class JUCE_API WebBrowserComponent : public Component
  40620. {
  40621. public:
  40622. /** Creates a WebBrowserComponent.
  40623. Once it's created and visible, send the browser to a URL using goToURL().
  40624. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  40625. component is taken offscreen, it'll clear the current page
  40626. and replace it with a blank page - this can be handy to stop
  40627. the browser using resources in the background when it's not
  40628. actually being used.
  40629. */
  40630. WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden = true);
  40631. /** Destructor. */
  40632. ~WebBrowserComponent();
  40633. /** Sends the browser to a particular URL.
  40634. @param url the URL to go to.
  40635. @param headers an optional set of parameters to put in the HTTP header. If
  40636. you supply this, it should be a set of string in the form
  40637. "HeaderKey: HeaderValue"
  40638. @param postData an optional block of data that will be attached to the HTTP
  40639. POST request
  40640. */
  40641. void goToURL (const String& url,
  40642. const StringArray* headers = 0,
  40643. const MemoryBlock* postData = 0);
  40644. /** Stops the current page loading.
  40645. */
  40646. void stop();
  40647. /** Sends the browser back one page.
  40648. */
  40649. void goBack();
  40650. /** Sends the browser forward one page.
  40651. */
  40652. void goForward();
  40653. /** Refreshes the browser.
  40654. */
  40655. void refresh();
  40656. /** This callback is called when the browser is about to navigate
  40657. to a new location.
  40658. You can override this method to perform some action when the user
  40659. tries to go to a particular URL. To allow the operation to carry on,
  40660. return true, or return false to stop the navigation happening.
  40661. */
  40662. virtual bool pageAboutToLoad (const String& newURL);
  40663. /** @internal */
  40664. void paint (Graphics& g);
  40665. /** @internal */
  40666. void resized();
  40667. /** @internal */
  40668. void parentHierarchyChanged();
  40669. /** @internal */
  40670. void visibilityChanged();
  40671. juce_UseDebuggingNewOperator
  40672. private:
  40673. WebBrowserComponentInternal* browser;
  40674. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  40675. String lastURL;
  40676. StringArray lastHeaders;
  40677. MemoryBlock lastPostData;
  40678. void reloadLastURL();
  40679. void checkWindowAssociation();
  40680. WebBrowserComponent (const WebBrowserComponent&);
  40681. const WebBrowserComponent& operator= (const WebBrowserComponent&);
  40682. };
  40683. #endif
  40684. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  40685. /********* End of inlined file: juce_WebBrowserComponent.h *********/
  40686. #endif
  40687. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  40688. #endif
  40689. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  40690. #endif
  40691. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  40692. /********* Start of inlined file: juce_DialogWindow.h *********/
  40693. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  40694. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  40695. /**
  40696. A dialog-box style window.
  40697. This class is a convenient way of creating a DocumentWindow with a close button
  40698. that can be triggered by pressing the escape key.
  40699. Any of the methods available to a DocumentWindow or ResizableWindow are also
  40700. available to this, so it can be made resizable, have a menu bar, etc.
  40701. To add items to the box, see the ResizableWindow::setContentComponent() method.
  40702. Don't add components directly to this class - always put them in a content component!
  40703. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  40704. the user clicking the close button - for more info, see the DocumentWindow
  40705. help.
  40706. @see DocumentWindow, ResizableWindow
  40707. */
  40708. class JUCE_API DialogWindow : public DocumentWindow
  40709. {
  40710. public:
  40711. /** Creates a DialogWindow.
  40712. @param name the name to give the component - this is also
  40713. the title shown at the top of the window. To change
  40714. this later, use setName()
  40715. @param backgroundColour the colour to use for filling the window's background.
  40716. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  40717. close button to be triggered
  40718. @param addToDesktop if true, the window will be automatically added to the
  40719. desktop; if false, you can use it as a child component
  40720. */
  40721. DialogWindow (const String& name,
  40722. const Colour& backgroundColour,
  40723. const bool escapeKeyTriggersCloseButton,
  40724. const bool addToDesktop = true);
  40725. /** Destructor.
  40726. If a content component has been set with setContentComponent(), it
  40727. will be deleted.
  40728. */
  40729. ~DialogWindow();
  40730. /** Easy way of quickly showing a dialog box containing a given component.
  40731. This will open and display a DialogWindow containing a given component, returning
  40732. when the user clicks its close button.
  40733. It returns the value that was returned by the dialog box's runModalLoop() call.
  40734. To close the dialog programatically, you should call exitModalState (returnValue) on
  40735. the DialogWindow that is created. To find a pointer to this window from your
  40736. contentComponent, you can do something like this:
  40737. @code
  40738. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  40739. if (dw != 0)
  40740. dw->exitModalState (1234);
  40741. @endcode
  40742. @param dialogTitle the dialog box's title
  40743. @param contentComponent the content component for the dialog box. Make sure
  40744. that this has been set to the size you want it to
  40745. be before calling this method. The component won't
  40746. be deleted by this call, so you can re-use it or delete
  40747. it afterwards
  40748. @param componentToCentreAround if this is non-zero, it indicates a component that
  40749. you'd like to show this dialog box in front of. See the
  40750. DocumentWindow::centreAroundComponent() method for more
  40751. info on this parameter
  40752. @param backgroundColour a colour to use for the dialog box's background colour
  40753. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  40754. close button to be triggered
  40755. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  40756. a corner resizer
  40757. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  40758. to use a border or corner resizer component. See ResizableWindow::setResizable()
  40759. */
  40760. static int showModalDialog (const String& dialogTitle,
  40761. Component* contentComponent,
  40762. Component* componentToCentreAround,
  40763. const Colour& backgroundColour,
  40764. const bool escapeKeyTriggersCloseButton,
  40765. const bool shouldBeResizable = false,
  40766. const bool useBottomRightCornerResizer = false);
  40767. juce_UseDebuggingNewOperator
  40768. protected:
  40769. /** @internal */
  40770. void resized();
  40771. private:
  40772. bool escapeKeyTriggersCloseButton;
  40773. DialogWindow (const DialogWindow&);
  40774. const DialogWindow& operator= (const DialogWindow&);
  40775. };
  40776. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  40777. /********* End of inlined file: juce_DialogWindow.h *********/
  40778. #endif
  40779. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  40780. #endif
  40781. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  40782. #endif
  40783. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  40784. /********* Start of inlined file: juce_SplashScreen.h *********/
  40785. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  40786. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  40787. /** A component for showing a splash screen while your app starts up.
  40788. This will automatically position itself, and delete itself when the app has
  40789. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  40790. this).
  40791. To use it, just create one of these in your JUCEApplication::initialise() method,
  40792. call its show() method and let the object delete itself later.
  40793. E.g. @code
  40794. void MyApp::initialise (const String& commandLine)
  40795. {
  40796. SplashScreen* splash = new SplashScreen();
  40797. splash->show (T("welcome to my app"),
  40798. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  40799. 4000, false);
  40800. .. no need to delete the splash screen - it'll do that itself.
  40801. }
  40802. @endcode
  40803. */
  40804. class JUCE_API SplashScreen : public Component,
  40805. public Timer,
  40806. private DeletedAtShutdown
  40807. {
  40808. public:
  40809. /** Creates a SplashScreen object.
  40810. After creating one of these (or your subclass of it), call one of the show()
  40811. methods to display it.
  40812. */
  40813. SplashScreen();
  40814. /** Destructor. */
  40815. ~SplashScreen();
  40816. /** Creates a SplashScreen object that will display an image.
  40817. As soon as this is called, the SplashScreen will be displayed in the centre of the
  40818. screen. This method will also dispatch any pending messages to make sure that when
  40819. it returns, the splash screen has been completely drawn, and your initialisation
  40820. code can carry on.
  40821. @param title the name to give the component
  40822. @param backgroundImage an image to draw on the component. The component's size
  40823. will be set to the size of this image, and if the image is
  40824. semi-transparent, the component will be made semi-transparent
  40825. too. This image will be deleted (or released from the ImageCache
  40826. if that's how it was created) by the splash screen object when
  40827. it is itself deleted.
  40828. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  40829. should stay visible for. If the initialisation takes longer than
  40830. this time, the splash screen will wait for it to finish before
  40831. disappearing, but if initialisation is very quick, this lets
  40832. you make sure that people get a good look at your splash.
  40833. @param useDropShadow if true, the window will have a drop shadow
  40834. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  40835. the mouse (anywhere)
  40836. */
  40837. void show (const String& title,
  40838. Image* const backgroundImage,
  40839. const int minimumTimeToDisplayFor,
  40840. const bool useDropShadow,
  40841. const bool removeOnMouseClick = true);
  40842. /** Creates a SplashScreen object with a specified size.
  40843. For a custom splash screen, you can use this method to display it at a certain size
  40844. and then override the paint() method yourself to do whatever's necessary.
  40845. As soon as this is called, the SplashScreen will be displayed in the centre of the
  40846. screen. This method will also dispatch any pending messages to make sure that when
  40847. it returns, the splash screen has been completely drawn, and your initialisation
  40848. code can carry on.
  40849. @param title the name to give the component
  40850. @param width the width to use
  40851. @param height the height to use
  40852. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  40853. should stay visible for. If the initialisation takes longer than
  40854. this time, the splash screen will wait for it to finish before
  40855. disappearing, but if initialisation is very quick, this lets
  40856. you make sure that people get a good look at your splash.
  40857. @param useDropShadow if true, the window will have a drop shadow
  40858. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  40859. the mouse (anywhere)
  40860. */
  40861. void show (const String& title,
  40862. const int width,
  40863. const int height,
  40864. const int minimumTimeToDisplayFor,
  40865. const bool useDropShadow,
  40866. const bool removeOnMouseClick = true);
  40867. /** @internal */
  40868. void paint (Graphics& g);
  40869. /** @internal */
  40870. void timerCallback();
  40871. juce_UseDebuggingNewOperator
  40872. private:
  40873. Image* backgroundImage;
  40874. Time earliestTimeToDelete;
  40875. int originalClickCounter;
  40876. SplashScreen (const SplashScreen&);
  40877. const SplashScreen& operator= (const SplashScreen&);
  40878. };
  40879. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  40880. /********* End of inlined file: juce_SplashScreen.h *********/
  40881. #endif
  40882. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  40883. /********* Start of inlined file: juce_ThreadWithProgressWindow.h *********/
  40884. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  40885. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  40886. /**
  40887. A thread that automatically pops up a modal dialog box with a progress bar
  40888. and cancel button while it's busy running.
  40889. These are handy for performing some sort of task while giving the user feedback
  40890. about how long there is to go, etc.
  40891. E.g. @code
  40892. class MyTask : public ThreadWithProgressWindow
  40893. {
  40894. public:
  40895. MyTask() : ThreadWithProgressWindow (T("busy..."), true, true)
  40896. {
  40897. }
  40898. ~MyTask()
  40899. {
  40900. }
  40901. void run()
  40902. {
  40903. for (int i = 0; i < thingsToDo; ++i)
  40904. {
  40905. // must check this as often as possible, because this is
  40906. // how we know if the user's pressed 'cancel'
  40907. if (threadShouldExit())
  40908. break;
  40909. // this will update the progress bar on the dialog box
  40910. setProgress (i / (double) thingsToDo);
  40911. // ... do the business here...
  40912. }
  40913. }
  40914. };
  40915. void doTheTask()
  40916. {
  40917. MyTask m;
  40918. if (m.runThread())
  40919. {
  40920. // thread finished normally..
  40921. }
  40922. else
  40923. {
  40924. // user pressed the cancel button..
  40925. }
  40926. }
  40927. @endcode
  40928. @see Thread, AlertWindow
  40929. */
  40930. class JUCE_API ThreadWithProgressWindow : public Thread,
  40931. private Timer
  40932. {
  40933. public:
  40934. /** Creates the thread.
  40935. Initially, the dialog box won't be visible, it'll only appear when the
  40936. runThread() method is called.
  40937. @param windowTitle the title to go at the top of the dialog box
  40938. @param hasProgressBar whether the dialog box should have a progress bar (see
  40939. setProgress() )
  40940. @param hasCancelButton whether the dialog box should have a cancel button
  40941. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  40942. the thread to stop before killing it forcibly (see
  40943. Thread::stopThread() )
  40944. @param cancelButtonText the text that should be shown in the cancel button
  40945. (if it has one)
  40946. */
  40947. ThreadWithProgressWindow (const String& windowTitle,
  40948. const bool hasProgressBar,
  40949. const bool hasCancelButton,
  40950. const int timeOutMsWhenCancelling = 10000,
  40951. const String& cancelButtonText = JUCE_T("Cancel"));
  40952. /** Destructor. */
  40953. ~ThreadWithProgressWindow();
  40954. /** Starts the thread and waits for it to finish.
  40955. This will start the thread, make the dialog box appear, and wait until either
  40956. the thread finishes normally, or until the cancel button is pressed.
  40957. Before returning, the dialog box will be hidden.
  40958. @param threadPriority the priority to use when starting the thread - see
  40959. Thread::startThread() for values
  40960. @returns true if the thread finished normally; false if the user pressed cancel
  40961. */
  40962. bool runThread (const int threadPriority = 5);
  40963. /** The thread should call this periodically to update the position of the progress bar.
  40964. @param newProgress the progress, from 0.0 to 1.0
  40965. @see setStatusMessage
  40966. */
  40967. void setProgress (const double newProgress);
  40968. /** The thread can call this to change the message that's displayed in the dialog box.
  40969. */
  40970. void setStatusMessage (const String& newStatusMessage);
  40971. /** Returns the AlertWindow that is being used.
  40972. */
  40973. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  40974. juce_UseDebuggingNewOperator
  40975. private:
  40976. void timerCallback();
  40977. double progress;
  40978. ScopedPointer <AlertWindow> alertWindow;
  40979. String message;
  40980. CriticalSection messageLock;
  40981. const int timeOutMsWhenCancelling;
  40982. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  40983. const ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  40984. };
  40985. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  40986. /********* End of inlined file: juce_ThreadWithProgressWindow.h *********/
  40987. #endif
  40988. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  40989. #endif
  40990. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  40991. #endif
  40992. #ifndef __JUCE_COLOUR_JUCEHEADER__
  40993. #endif
  40994. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  40995. #endif
  40996. #ifndef __JUCE_COLOURS_JUCEHEADER__
  40997. #endif
  40998. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  40999. #endif
  41000. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  41001. #endif
  41002. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  41003. #endif
  41004. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  41005. #endif
  41006. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  41007. #endif
  41008. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  41009. /********* Start of inlined file: juce_LowLevelGraphicsContext.h *********/
  41010. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  41011. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  41012. /**
  41013. Interface class for graphics context objects, used internally by the Graphics class.
  41014. Users are not supposed to create instances of this class directly - do your drawing
  41015. via the Graphics object instead.
  41016. It's a base class for different types of graphics context, that may perform software-based
  41017. or OS-accelerated rendering.
  41018. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  41019. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  41020. context.
  41021. */
  41022. class JUCE_API LowLevelGraphicsContext
  41023. {
  41024. protected:
  41025. LowLevelGraphicsContext();
  41026. public:
  41027. virtual ~LowLevelGraphicsContext();
  41028. /** Returns true if this device is vector-based, e.g. a printer. */
  41029. virtual bool isVectorDevice() const = 0;
  41030. /** Moves the origin to a new position.
  41031. The co-ords are relative to the current origin, and indicate the new position
  41032. of (0, 0).
  41033. */
  41034. virtual void setOrigin (int x, int y) = 0;
  41035. virtual bool clipToRectangle (const Rectangle& r) = 0;
  41036. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  41037. virtual void excludeClipRectangle (const Rectangle& r) = 0;
  41038. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  41039. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform) = 0;
  41040. virtual bool clipRegionIntersects (const Rectangle& r) = 0;
  41041. virtual const Rectangle getClipBounds() const = 0;
  41042. virtual bool isClipEmpty() const = 0;
  41043. virtual void saveState() = 0;
  41044. virtual void restoreState() = 0;
  41045. virtual void setFill (const FillType& fillType) = 0;
  41046. virtual void setOpacity (float newOpacity) = 0;
  41047. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  41048. virtual void fillRect (const Rectangle& r, const bool replaceExistingContents) = 0;
  41049. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  41050. virtual void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  41051. const AffineTransform& transform, const bool fillEntireClipAsTiles) = 0;
  41052. virtual void drawLine (double x1, double y1, double x2, double y2) = 0;
  41053. virtual void drawVerticalLine (const int x, double top, double bottom) = 0;
  41054. virtual void drawHorizontalLine (const int y, double left, double right) = 0;
  41055. virtual void setFont (const Font& newFont) = 0;
  41056. virtual const Font getFont() = 0;
  41057. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  41058. };
  41059. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  41060. /********* End of inlined file: juce_LowLevelGraphicsContext.h *********/
  41061. #endif
  41062. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  41063. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  41064. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  41065. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  41066. /**
  41067. An implementation of LowLevelGraphicsContext that turns the drawing operations
  41068. into a PostScript document.
  41069. */
  41070. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  41071. {
  41072. public:
  41073. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  41074. const String& documentTitle,
  41075. const int totalWidth,
  41076. const int totalHeight);
  41077. ~LowLevelGraphicsPostScriptRenderer();
  41078. bool isVectorDevice() const;
  41079. void setOrigin (int x, int y);
  41080. bool clipToRectangle (const Rectangle& r);
  41081. bool clipToRectangleList (const RectangleList& clipRegion);
  41082. void excludeClipRectangle (const Rectangle& r);
  41083. void clipToPath (const Path& path, const AffineTransform& transform);
  41084. void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform);
  41085. void saveState();
  41086. void restoreState();
  41087. bool clipRegionIntersects (const Rectangle& r);
  41088. const Rectangle getClipBounds() const;
  41089. bool isClipEmpty() const;
  41090. void setFill (const FillType& fillType);
  41091. void setOpacity (float opacity);
  41092. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  41093. void fillRect (const Rectangle& r, const bool replaceExistingContents);
  41094. void fillPath (const Path& path, const AffineTransform& transform);
  41095. void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  41096. const AffineTransform& transform, const bool fillEntireClipAsTiles);
  41097. void drawLine (double x1, double y1, double x2, double y2);
  41098. void drawVerticalLine (const int x, double top, double bottom);
  41099. void drawHorizontalLine (const int x, double top, double bottom);
  41100. const Font getFont();
  41101. void setFont (const Font& newFont);
  41102. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  41103. juce_UseDebuggingNewOperator
  41104. protected:
  41105. OutputStream& out;
  41106. int totalWidth, totalHeight;
  41107. bool needToClip;
  41108. Colour lastColour;
  41109. struct SavedState
  41110. {
  41111. SavedState();
  41112. ~SavedState();
  41113. RectangleList clip;
  41114. int xOffset, yOffset;
  41115. FillType fillType;
  41116. Font font;
  41117. private:
  41118. const SavedState& operator= (const SavedState&);
  41119. };
  41120. OwnedArray <SavedState> stateStack;
  41121. void writeClip();
  41122. void writeColour (const Colour& colour);
  41123. void writePath (const Path& path) const;
  41124. void writeXY (const float x, const float y) const;
  41125. void writeTransform (const AffineTransform& trans) const;
  41126. void writeImage (const Image& im, const int sx, const int sy, const int maxW, const int maxH) const;
  41127. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  41128. const LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  41129. };
  41130. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  41131. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h *********/
  41132. #endif
  41133. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  41134. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  41135. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  41136. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  41137. class LLGCSavedState;
  41138. /**
  41139. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  41140. its rendering in memory.
  41141. User code is not supposed to create instances of this class directly - do all your
  41142. rendering via the Graphics class instead.
  41143. */
  41144. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  41145. {
  41146. public:
  41147. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  41148. ~LowLevelGraphicsSoftwareRenderer();
  41149. bool isVectorDevice() const;
  41150. void setOrigin (int x, int y);
  41151. bool clipToRectangle (const Rectangle& r);
  41152. bool clipToRectangleList (const RectangleList& clipRegion);
  41153. void excludeClipRectangle (const Rectangle& r);
  41154. void clipToPath (const Path& path, const AffineTransform& transform);
  41155. void clipToImageAlpha (const Image& sourceImage, const Rectangle& srcClip, const AffineTransform& transform);
  41156. bool clipRegionIntersects (const Rectangle& r);
  41157. const Rectangle getClipBounds() const;
  41158. bool isClipEmpty() const;
  41159. void saveState();
  41160. void restoreState();
  41161. void setFill (const FillType& fillType);
  41162. void setOpacity (float opacity);
  41163. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  41164. void fillRect (const Rectangle& r, const bool replaceExistingContents);
  41165. void fillPath (const Path& path, const AffineTransform& transform);
  41166. void drawImage (const Image& sourceImage, const Rectangle& srcClip,
  41167. const AffineTransform& transform, const bool fillEntireClipAsTiles);
  41168. void drawLine (double x1, double y1, double x2, double y2);
  41169. void drawVerticalLine (const int x, double top, double bottom);
  41170. void drawHorizontalLine (const int x, double top, double bottom);
  41171. void setFont (const Font& newFont);
  41172. const Font getFont();
  41173. void drawGlyph (int glyphNumber, float x, float y);
  41174. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  41175. juce_UseDebuggingNewOperator
  41176. protected:
  41177. Image& image;
  41178. ScopedPointer <LLGCSavedState> currentState;
  41179. OwnedArray <LLGCSavedState> stateStack;
  41180. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  41181. const LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  41182. };
  41183. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  41184. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h *********/
  41185. #endif
  41186. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  41187. #endif
  41188. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  41189. #endif
  41190. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  41191. /********* Start of inlined file: juce_DrawableComposite.h *********/
  41192. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  41193. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  41194. /**
  41195. A drawable object which acts as a container for a set of other Drawables.
  41196. @see Drawable
  41197. */
  41198. class JUCE_API DrawableComposite : public Drawable
  41199. {
  41200. public:
  41201. /** Creates a composite Drawable.
  41202. */
  41203. DrawableComposite();
  41204. /** Destructor. */
  41205. virtual ~DrawableComposite();
  41206. /** Adds a new sub-drawable to this one.
  41207. This passes in a Drawable pointer for this object to look after. To add a copy
  41208. of a drawable, use the form of this method that takes a Drawable reference instead.
  41209. @param drawable the object to add - this will be deleted automatically
  41210. when no longer needed, so the caller mustn't keep any
  41211. pointers to it.
  41212. @param transform the transform to apply to this drawable when it's being
  41213. drawn
  41214. @param index where to insert it in the list of drawables. 0 is the back,
  41215. -1 is the front, or any value from 0 and getNumDrawables()
  41216. can be used
  41217. @see removeDrawable
  41218. */
  41219. void insertDrawable (Drawable* drawable,
  41220. const AffineTransform& transform = AffineTransform::identity,
  41221. const int index = -1);
  41222. /** Adds a new sub-drawable to this one.
  41223. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  41224. for this object to look after, use the form of this method that takes a Drawable
  41225. pointer instead.
  41226. @param drawable the object to add - an internal copy will be made of this object
  41227. @param transform the transform to apply to this drawable when it's being
  41228. drawn
  41229. @param index where to insert it in the list of drawables. 0 is the back,
  41230. -1 is the front, or any value from 0 and getNumDrawables()
  41231. can be used
  41232. @see removeDrawable
  41233. */
  41234. void insertDrawable (const Drawable& drawable,
  41235. const AffineTransform& transform = AffineTransform::identity,
  41236. const int index = -1);
  41237. /** Deletes one of the Drawable objects.
  41238. @param index the index of the drawable to delete, between 0
  41239. and (getNumDrawables() - 1).
  41240. @param deleteDrawable if this is true, the drawable that is removed will also
  41241. be deleted. If false, it'll just be removed.
  41242. @see insertDrawable, getNumDrawables
  41243. */
  41244. void removeDrawable (const int index, const bool deleteDrawable = true);
  41245. /** Returns the number of drawables contained inside this one.
  41246. @see getDrawable
  41247. */
  41248. int getNumDrawables() const throw() { return drawables.size(); }
  41249. /** Returns one of the drawables that are contained in this one.
  41250. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  41251. to find it.
  41252. The pointer returned is managed by this object and will be deleted when no longer
  41253. needed, so be careful what you do with it.
  41254. @see getNumDrawables
  41255. */
  41256. Drawable* getDrawable (const int index) const throw() { return drawables [index]; }
  41257. /** Returns the transform that applies to one of the drawables that are contained in this one.
  41258. The pointer returned is managed by this object and will be deleted when no longer
  41259. needed, so be careful what you do with it.
  41260. @see getNumDrawables
  41261. */
  41262. const AffineTransform* getDrawableTransform (const int index) const throw() { return transforms [index]; }
  41263. /** Brings one of the Drawables to the front.
  41264. @param index the index of the drawable to move, between 0
  41265. and (getNumDrawables() - 1).
  41266. @see insertDrawable, getNumDrawables
  41267. */
  41268. void bringToFront (const int index);
  41269. /** @internal */
  41270. void render (const Drawable::RenderingContext& context) const;
  41271. /** @internal */
  41272. void getBounds (float& x, float& y, float& width, float& height) const;
  41273. /** @internal */
  41274. bool hitTest (float x, float y) const;
  41275. /** @internal */
  41276. Drawable* createCopy() const;
  41277. /** @internal */
  41278. ValueTree createValueTree() const throw();
  41279. /** @internal */
  41280. static DrawableComposite* createFromValueTree (const ValueTree& tree) throw();
  41281. juce_UseDebuggingNewOperator
  41282. private:
  41283. OwnedArray <Drawable> drawables;
  41284. OwnedArray <AffineTransform> transforms;
  41285. DrawableComposite (const DrawableComposite&);
  41286. const DrawableComposite& operator= (const DrawableComposite&);
  41287. };
  41288. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  41289. /********* End of inlined file: juce_DrawableComposite.h *********/
  41290. #endif
  41291. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  41292. /********* Start of inlined file: juce_DrawableImage.h *********/
  41293. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  41294. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  41295. /**
  41296. A drawable object which is a bitmap image.
  41297. @see Drawable
  41298. */
  41299. class JUCE_API DrawableImage : public Drawable
  41300. {
  41301. public:
  41302. DrawableImage();
  41303. /** Destructor. */
  41304. virtual ~DrawableImage();
  41305. /** Sets the image that this drawable will render.
  41306. An internal copy is made of the image passed-in. If you want to provide an
  41307. image that this object can take charge of without needing to create a copy,
  41308. use the other setImage() method.
  41309. */
  41310. void setImage (const Image& imageToCopy);
  41311. /** Sets the image that this drawable will render.
  41312. An internal copy of this will not be made, so the caller mustn't delete
  41313. the image while it's still being used by this object.
  41314. A good way to use this is with the ImageCache - if you create an image
  41315. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  41316. it'll be released neatly with its reference count being decreased.
  41317. @param imageToUse the image to render
  41318. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  41319. then the image will be deleted when this object no longer
  41320. needs it - unless the image was created by the ImageCache,
  41321. in which case it will be released with ImageCache::release().
  41322. */
  41323. void setImage (Image* imageToUse,
  41324. const bool releaseWhenNotNeeded);
  41325. /** Returns the current image. */
  41326. Image* getImage() const throw() { return image; }
  41327. /** Clears (and possibly deletes) the currently set image. */
  41328. void clearImage();
  41329. /** Sets the opacity to use when drawing the image. */
  41330. void setOpacity (const float newOpacity);
  41331. /** Returns the image's opacity. */
  41332. float getOpacity() const throw() { return opacity; }
  41333. /** Sets a colour to draw over the image's alpha channel.
  41334. By default this is transparent so isn't drawn, but if you set a non-transparent
  41335. colour here, then it will be overlaid on the image, using the image's alpha
  41336. channel as a mask.
  41337. This is handy for doing things like darkening or lightening an image by overlaying
  41338. it with semi-transparent black or white.
  41339. */
  41340. void setOverlayColour (const Colour& newOverlayColour);
  41341. /** Returns the overlay colour. */
  41342. const Colour& getOverlayColour() const throw() { return overlayColour; }
  41343. /** @internal */
  41344. void render (const Drawable::RenderingContext& context) const;
  41345. /** @internal */
  41346. void getBounds (float& x, float& y, float& width, float& height) const;
  41347. /** @internal */
  41348. bool hitTest (float x, float y) const;
  41349. /** @internal */
  41350. Drawable* createCopy() const;
  41351. /** @internal */
  41352. ValueTree createValueTree() const throw();
  41353. /** @internal */
  41354. static DrawableImage* createFromValueTree (const ValueTree& tree) throw();
  41355. juce_UseDebuggingNewOperator
  41356. private:
  41357. Image* image;
  41358. bool canDeleteImage;
  41359. float opacity;
  41360. Colour overlayColour;
  41361. DrawableImage (const DrawableImage&);
  41362. const DrawableImage& operator= (const DrawableImage&);
  41363. };
  41364. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  41365. /********* End of inlined file: juce_DrawableImage.h *********/
  41366. #endif
  41367. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  41368. /********* Start of inlined file: juce_DrawablePath.h *********/
  41369. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  41370. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  41371. /**
  41372. A drawable object which renders a filled or outlined shape.
  41373. @see Drawable
  41374. */
  41375. class JUCE_API DrawablePath : public Drawable
  41376. {
  41377. public:
  41378. /** Creates a DrawablePath.
  41379. */
  41380. DrawablePath();
  41381. /** Destructor. */
  41382. virtual ~DrawablePath();
  41383. /** Changes the path that will be drawn.
  41384. @see setFillColour, setStrokeType
  41385. */
  41386. void setPath (const Path& newPath) throw();
  41387. /** Returns the current path. */
  41388. const Path& getPath() const throw() { return path; }
  41389. /** Sets a fill type for the path.
  41390. This colour is used to fill the path - if you don't want the path to be
  41391. filled (e.g. if you're just drawing an outline), set this to a transparent
  41392. colour.
  41393. @see setPath, setStrokeFill
  41394. */
  41395. void setFill (const FillType& newFill) throw();
  41396. /** Returns the current fill type.
  41397. @see setFill
  41398. */
  41399. const FillType& getFill() const throw() { return mainFill; }
  41400. /** Sets the fill type with which the outline will be drawn.
  41401. @see setFill
  41402. */
  41403. void setStrokeFill (const FillType& newStrokeFill) throw();
  41404. /** Returns the current stroke fill.
  41405. @see setStrokeFill
  41406. */
  41407. const FillType& getStrokeFill() const throw() { return strokeFill; }
  41408. /** Changes the properties of the outline that will be drawn around the path.
  41409. If the stroke has 0 thickness, no stroke will be drawn.
  41410. @see setStrokeThickness, setStrokeColour
  41411. */
  41412. void setStrokeType (const PathStrokeType& newStrokeType) throw();
  41413. /** Changes the stroke thickness.
  41414. This is a shortcut for calling setStrokeType.
  41415. */
  41416. void setStrokeThickness (const float newThickness) throw();
  41417. /** Returns the current outline style. */
  41418. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  41419. /** @internal */
  41420. void render (const Drawable::RenderingContext& context) const;
  41421. /** @internal */
  41422. void getBounds (float& x, float& y, float& width, float& height) const;
  41423. /** @internal */
  41424. bool hitTest (float x, float y) const;
  41425. /** @internal */
  41426. Drawable* createCopy() const;
  41427. /** @internal */
  41428. ValueTree createValueTree() const throw();
  41429. /** @internal */
  41430. static DrawablePath* createFromValueTree (const ValueTree& tree) throw();
  41431. juce_UseDebuggingNewOperator
  41432. private:
  41433. Path path, stroke;
  41434. FillType mainFill, strokeFill;
  41435. PathStrokeType strokeType;
  41436. void updateOutline();
  41437. DrawablePath (const DrawablePath&);
  41438. const DrawablePath& operator= (const DrawablePath&);
  41439. };
  41440. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  41441. /********* End of inlined file: juce_DrawablePath.h *********/
  41442. #endif
  41443. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  41444. /********* Start of inlined file: juce_DrawableText.h *********/
  41445. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  41446. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  41447. /**
  41448. A drawable object which renders a line of text.
  41449. @see Drawable
  41450. */
  41451. class JUCE_API DrawableText : public Drawable
  41452. {
  41453. public:
  41454. /** Creates a DrawableText object. */
  41455. DrawableText();
  41456. /** Destructor. */
  41457. virtual ~DrawableText();
  41458. /** Sets the block of text to render */
  41459. void setText (const GlyphArrangement& newText);
  41460. /** Sets a single line of text to render.
  41461. This is a convenient method of adding a single line - for
  41462. more complex text, use the setText() that takes a
  41463. GlyphArrangement instead.
  41464. */
  41465. void setText (const String& newText, const Font& fontToUse);
  41466. /** Returns the text arrangement that was set with setText(). */
  41467. const GlyphArrangement& getText() const throw() { return text; }
  41468. /** Sets the colour of the text. */
  41469. void setColour (const Colour& newColour);
  41470. /** Returns the current text colour. */
  41471. const Colour& getColour() const throw() { return colour; }
  41472. /** @internal */
  41473. void render (const Drawable::RenderingContext& context) const;
  41474. /** @internal */
  41475. void getBounds (float& x, float& y, float& width, float& height) const;
  41476. /** @internal */
  41477. bool hitTest (float x, float y) const;
  41478. /** @internal */
  41479. Drawable* createCopy() const;
  41480. /** @internal */
  41481. ValueTree createValueTree() const throw();
  41482. /** @internal */
  41483. static DrawableText* createFromValueTree (const ValueTree& tree) throw();
  41484. juce_UseDebuggingNewOperator
  41485. private:
  41486. GlyphArrangement text;
  41487. Colour colour;
  41488. DrawableText (const DrawableText&);
  41489. const DrawableText& operator= (const DrawableText&);
  41490. };
  41491. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  41492. /********* End of inlined file: juce_DrawableText.h *********/
  41493. #endif
  41494. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  41495. #endif
  41496. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  41497. /********* Start of inlined file: juce_GlowEffect.h *********/
  41498. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  41499. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  41500. /**
  41501. A component effect that adds a coloured blur around the component's contents.
  41502. (This will only work on non-opaque components).
  41503. @see Component::setComponentEffect, DropShadowEffect
  41504. */
  41505. class JUCE_API GlowEffect : public ImageEffectFilter
  41506. {
  41507. public:
  41508. /** Creates a default 'glow' effect.
  41509. To customise its appearance, use the setGlowProperties() method.
  41510. */
  41511. GlowEffect();
  41512. /** Destructor. */
  41513. ~GlowEffect();
  41514. /** Sets the glow's radius and colour.
  41515. The radius is how large the blur should be, and the colour is
  41516. used to render it (for a less intense glow, lower the colour's
  41517. opacity).
  41518. */
  41519. void setGlowProperties (const float newRadius,
  41520. const Colour& newColour);
  41521. /** @internal */
  41522. void applyEffect (Image& sourceImage, Graphics& destContext);
  41523. juce_UseDebuggingNewOperator
  41524. private:
  41525. float radius;
  41526. Colour colour;
  41527. };
  41528. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  41529. /********* End of inlined file: juce_GlowEffect.h *********/
  41530. #endif
  41531. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  41532. #endif
  41533. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  41534. /********* Start of inlined file: juce_ReduceOpacityEffect.h *********/
  41535. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  41536. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  41537. /**
  41538. An effect filter that reduces the image's opacity.
  41539. This can be used to make a component (and its child components) more
  41540. transparent.
  41541. @see Component::setComponentEffect
  41542. */
  41543. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  41544. {
  41545. public:
  41546. /** Creates the effect object.
  41547. The opacity of the component to which the effect is applied will be
  41548. scaled by the given factor (in the range 0 to 1.0f).
  41549. */
  41550. ReduceOpacityEffect (const float opacity = 1.0f);
  41551. /** Destructor. */
  41552. ~ReduceOpacityEffect();
  41553. /** Sets how much to scale the component's opacity.
  41554. @param newOpacity should be between 0 and 1.0f
  41555. */
  41556. void setOpacity (const float newOpacity);
  41557. /** @internal */
  41558. void applyEffect (Image& sourceImage, Graphics& destContext);
  41559. juce_UseDebuggingNewOperator
  41560. private:
  41561. float opacity;
  41562. };
  41563. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  41564. /********* End of inlined file: juce_ReduceOpacityEffect.h *********/
  41565. #endif
  41566. #ifndef __JUCE_FONT_JUCEHEADER__
  41567. #endif
  41568. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  41569. #endif
  41570. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  41571. #endif
  41572. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  41573. #endif
  41574. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  41575. #endif
  41576. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  41577. #endif
  41578. #ifndef __JUCE_LINE_JUCEHEADER__
  41579. #endif
  41580. #ifndef __JUCE_PATH_JUCEHEADER__
  41581. #endif
  41582. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  41583. /********* Start of inlined file: juce_PathIterator.h *********/
  41584. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  41585. #define __JUCE_PATHITERATOR_JUCEHEADER__
  41586. /**
  41587. Flattens a Path object into a series of straight-line sections.
  41588. Use one of these to iterate through a Path object, and it will convert
  41589. all the curves into line sections so it's easy to render or perform
  41590. geometric operations on.
  41591. @see Path
  41592. */
  41593. class JUCE_API PathFlatteningIterator
  41594. {
  41595. public:
  41596. /** Creates a PathFlatteningIterator.
  41597. After creation, use the next() method to initialise the fields in the
  41598. object with the first line's position.
  41599. @param path the path to iterate along
  41600. @param transform a transform to apply to each point in the path being iterated
  41601. @param tolerence the amount by which the curves are allowed to deviate from the
  41602. lines into which they are being broken down - a higher tolerence
  41603. is a bit faster, but less smooth.
  41604. */
  41605. PathFlatteningIterator (const Path& path,
  41606. const AffineTransform& transform = AffineTransform::identity,
  41607. float tolerence = 6.0f) throw();
  41608. /** Destructor. */
  41609. ~PathFlatteningIterator() throw();
  41610. /** Fetches the next line segment from the path.
  41611. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  41612. so that they describe the new line segment.
  41613. @returns false when there are no more lines to fetch.
  41614. */
  41615. bool next() throw();
  41616. /** The x position of the start of the current line segment. */
  41617. float x1;
  41618. /** The y position of the start of the current line segment. */
  41619. float y1;
  41620. /** The x position of the end of the current line segment. */
  41621. float x2;
  41622. /** The y position of the end of the current line segment. */
  41623. float y2;
  41624. /** Indicates whether the current line segment is closing a sub-path.
  41625. If the current line is the one that connects the end of a sub-path
  41626. back to the start again, this will be true.
  41627. */
  41628. bool closesSubPath;
  41629. /** The index of the current line within the current sub-path.
  41630. E.g. you can use this to see whether the line is the first one in the
  41631. subpath by seeing if it's 0.
  41632. */
  41633. int subPathIndex;
  41634. /** Returns true if the current segment is the last in the current sub-path. */
  41635. bool isLastInSubpath() const throw() { return stackPos == stackBase
  41636. && (index >= path.numElements
  41637. || points [index] == Path::moveMarker); }
  41638. juce_UseDebuggingNewOperator
  41639. private:
  41640. const Path& path;
  41641. const AffineTransform transform;
  41642. float* points;
  41643. float tolerence, subPathCloseX, subPathCloseY;
  41644. bool isIdentityTransform;
  41645. HeapBlock <float> stackBase;
  41646. float* stackPos;
  41647. int index, stackSize;
  41648. PathFlatteningIterator (const PathFlatteningIterator&);
  41649. const PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  41650. };
  41651. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  41652. /********* End of inlined file: juce_PathIterator.h *********/
  41653. #endif
  41654. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  41655. #endif
  41656. #ifndef __JUCE_POINT_JUCEHEADER__
  41657. #endif
  41658. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  41659. /********* Start of inlined file: juce_PositionedRectangle.h *********/
  41660. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  41661. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  41662. /**
  41663. A rectangle whose co-ordinates can be defined in terms of absolute or
  41664. proportional distances.
  41665. Designed mainly for storing component positions, this gives you a lot of
  41666. control over how each co-ordinate is stored, either as an absolute position,
  41667. or as a proportion of the size of a parent rectangle.
  41668. It also allows you to define the anchor points by which the rectangle is
  41669. positioned, so for example you could specify that the top right of the
  41670. rectangle should be an absolute distance from its parent's bottom-right corner.
  41671. This object can be stored as a string, which takes the form "x y w h", including
  41672. symbols like '%' and letters to indicate the anchor point. See its toString()
  41673. method for more info.
  41674. Example usage:
  41675. @code
  41676. class MyComponent
  41677. {
  41678. void resized()
  41679. {
  41680. // this will set the child component's x to be 20% of our width, its y
  41681. // to be 30, its width to be 150, and its height to be 50% of our
  41682. // height..
  41683. const PositionedRectangle pos1 ("20% 30 150 50%");
  41684. pos1.applyToComponent (*myChildComponent1);
  41685. // this will inset the child component with a gap of 10 pixels
  41686. // around each of its edges..
  41687. const PositionedRectangle pos2 ("10 10 20M 20M");
  41688. pos2.applyToComponent (*myChildComponent2);
  41689. }
  41690. };
  41691. @endcode
  41692. */
  41693. class JUCE_API PositionedRectangle
  41694. {
  41695. public:
  41696. /** Creates an empty rectangle with all co-ordinates set to zero.
  41697. The default anchor point is top-left; the default
  41698. */
  41699. PositionedRectangle() throw();
  41700. /** Initialises a PositionedRectangle from a saved string version.
  41701. The string must be in the format generated by toString().
  41702. */
  41703. PositionedRectangle (const String& stringVersion) throw();
  41704. /** Creates a copy of another PositionedRectangle. */
  41705. PositionedRectangle (const PositionedRectangle& other) throw();
  41706. /** Copies another PositionedRectangle. */
  41707. const PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  41708. /** Destructor. */
  41709. ~PositionedRectangle() throw();
  41710. /** Returns a string version of this position, from which it can later be
  41711. re-generated.
  41712. The format is four co-ordinates, "x y w h".
  41713. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  41714. - If a co-ordinate is proportional to its parent's width or height, it is stored
  41715. as a percentage, e.g. "80%".
  41716. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  41717. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  41718. the parent's right-hand edge.
  41719. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  41720. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  41721. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  41722. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  41723. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  41724. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  41725. has "c" appended to it. So "-50Rc" would mean that this component's
  41726. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  41727. this component's centre should be placed 40% across the parent's width.
  41728. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  41729. the number has "M" appended to it.
  41730. To reload a stored string, use the constructor that takes a string parameter.
  41731. */
  41732. const String toString() const throw();
  41733. /** Calculates the absolute position, given the size of the space that
  41734. it should go in.
  41735. This will work out any proportional distances and sizes relative to the
  41736. target rectangle, and will return the absolute position.
  41737. @see applyToComponent
  41738. */
  41739. const Rectangle getRectangle (const Rectangle& targetSpaceToBeRelativeTo) const throw();
  41740. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  41741. */
  41742. void getRectangleDouble (const Rectangle& targetSpaceToBeRelativeTo,
  41743. double& x,
  41744. double& y,
  41745. double& width,
  41746. double& height) const throw();
  41747. /** This sets the bounds of the given component to this position.
  41748. This is equivalent to writing:
  41749. @code
  41750. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  41751. @endcode
  41752. @see getRectangle, updateFromComponent
  41753. */
  41754. void applyToComponent (Component& comp) const throw();
  41755. /** Updates this object's co-ordinates to match the given rectangle.
  41756. This will set all co-ordinates based on the given rectangle, re-calculating
  41757. any proportional distances, and using the current anchor points.
  41758. So for example if the x co-ordinate mode is currently proportional, this will
  41759. re-calculate x based on the rectangle's relative position within the target
  41760. rectangle's width.
  41761. If the target rectangle's width or height are zero then it may not be possible
  41762. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  41763. will not be changed.
  41764. */
  41765. void updateFrom (const Rectangle& newPosition,
  41766. const Rectangle& targetSpaceToBeRelativeTo) throw();
  41767. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  41768. */
  41769. void updateFromDouble (const double x, const double y,
  41770. const double width, const double height,
  41771. const Rectangle& targetSpaceToBeRelativeTo) throw();
  41772. /** Updates this object's co-ordinates to match the bounds of this component.
  41773. This is equivalent to calling updateFrom() with the component's bounds and
  41774. it parent size.
  41775. If the component doesn't currently have a parent, then proportional co-ordinates
  41776. might not be updated because it would need to know the parent's size to do the
  41777. maths for this.
  41778. */
  41779. void updateFromComponent (const Component& comp) throw();
  41780. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  41781. enum AnchorPoint
  41782. {
  41783. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  41784. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  41785. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  41786. };
  41787. /** Specifies how an x or y co-ordinate should be interpreted. */
  41788. enum PositionMode
  41789. {
  41790. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  41791. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  41792. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  41793. 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. */
  41794. };
  41795. /** Specifies how the width or height should be interpreted. */
  41796. enum SizeMode
  41797. {
  41798. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  41799. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  41800. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  41801. };
  41802. /** Sets all options for all co-ordinates.
  41803. This requires a reference rectangle to be specified, because if you're changing any
  41804. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  41805. the co-ordinates, and will need to know the parent size so it can calculate this.
  41806. */
  41807. void setModes (const AnchorPoint xAnchorMode,
  41808. const PositionMode xPositionMode,
  41809. const AnchorPoint yAnchorMode,
  41810. const PositionMode yPositionMode,
  41811. const SizeMode widthMode,
  41812. const SizeMode heightMode,
  41813. const Rectangle& targetSpaceToBeRelativeTo) throw();
  41814. /** Returns the anchoring mode for the x co-ordinate.
  41815. To change any of the modes, use setModes().
  41816. */
  41817. AnchorPoint getAnchorPointX() const throw();
  41818. /** Returns the positioning mode for the x co-ordinate.
  41819. To change any of the modes, use setModes().
  41820. */
  41821. PositionMode getPositionModeX() const throw();
  41822. /** Returns the raw x co-ordinate.
  41823. If the x position mode is absolute, then this will be the absolute value. If it's
  41824. proportional, then this will be a fractional proportion, where 1.0 means the full
  41825. width of the parent space.
  41826. */
  41827. double getX() const throw() { return x; }
  41828. /** Sets the raw value of the x co-ordinate.
  41829. See getX() for the meaning of this value.
  41830. */
  41831. void setX (const double newX) throw() { x = newX; }
  41832. /** Returns the anchoring mode for the y co-ordinate.
  41833. To change any of the modes, use setModes().
  41834. */
  41835. AnchorPoint getAnchorPointY() const throw();
  41836. /** Returns the positioning mode for the y co-ordinate.
  41837. To change any of the modes, use setModes().
  41838. */
  41839. PositionMode getPositionModeY() const throw();
  41840. /** Returns the raw y co-ordinate.
  41841. If the y position mode is absolute, then this will be the absolute value. If it's
  41842. proportional, then this will be a fractional proportion, where 1.0 means the full
  41843. height of the parent space.
  41844. */
  41845. double getY() const throw() { return y; }
  41846. /** Sets the raw value of the y co-ordinate.
  41847. See getY() for the meaning of this value.
  41848. */
  41849. void setY (const double newY) throw() { y = newY; }
  41850. /** Returns the mode used to calculate the width.
  41851. To change any of the modes, use setModes().
  41852. */
  41853. SizeMode getWidthMode() const throw();
  41854. /** Returns the raw width value.
  41855. If the width mode is absolute, then this will be the absolute value. If the mode is
  41856. proportional, then this will be a fractional proportion, where 1.0 means the full
  41857. width of the parent space.
  41858. */
  41859. double getWidth() const throw() { return w; }
  41860. /** Sets the raw width value.
  41861. See getWidth() for the details about what this value means.
  41862. */
  41863. void setWidth (const double newWidth) throw() { w = newWidth; }
  41864. /** Returns the mode used to calculate the height.
  41865. To change any of the modes, use setModes().
  41866. */
  41867. SizeMode getHeightMode() const throw();
  41868. /** Returns the raw height value.
  41869. If the height mode is absolute, then this will be the absolute value. If the mode is
  41870. proportional, then this will be a fractional proportion, where 1.0 means the full
  41871. height of the parent space.
  41872. */
  41873. double getHeight() const throw() { return h; }
  41874. /** Sets the raw height value.
  41875. See getHeight() for the details about what this value means.
  41876. */
  41877. void setHeight (const double newHeight) throw() { h = newHeight; }
  41878. /** If the size and position are constance, and wouldn't be affected by changes
  41879. in the parent's size, then this will return true.
  41880. */
  41881. bool isPositionAbsolute() const throw();
  41882. /** Compares two objects. */
  41883. const bool operator== (const PositionedRectangle& other) const throw();
  41884. /** Compares two objects. */
  41885. const bool operator!= (const PositionedRectangle& other) const throw();
  41886. juce_UseDebuggingNewOperator
  41887. private:
  41888. double x, y, w, h;
  41889. uint8 xMode, yMode, wMode, hMode;
  41890. void addPosDescription (String& result, const uint8 mode, const double value) const throw();
  41891. void addSizeDescription (String& result, const uint8 mode, const double value) const throw();
  41892. void decodePosString (const String& s, uint8& mode, double& value) throw();
  41893. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  41894. void applyPosAndSize (double& xOut, double& wOut, const double x, const double w,
  41895. const uint8 xMode, const uint8 wMode,
  41896. const int parentPos, const int parentSize) const throw();
  41897. void updatePosAndSize (double& xOut, double& wOut, double x, const double w,
  41898. const uint8 xMode, const uint8 wMode,
  41899. const int parentPos, const int parentSize) const throw();
  41900. };
  41901. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  41902. /********* End of inlined file: juce_PositionedRectangle.h *********/
  41903. #endif
  41904. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  41905. #endif
  41906. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  41907. #endif
  41908. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  41909. /********* Start of inlined file: juce_CameraDevice.h *********/
  41910. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  41911. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  41912. #if JUCE_USE_CAMERA
  41913. /**
  41914. Receives callbacks with images from a CameraDevice.
  41915. @see CameraDevice::addListener
  41916. */
  41917. class CameraImageListener
  41918. {
  41919. public:
  41920. CameraImageListener() {}
  41921. virtual ~CameraImageListener() {}
  41922. /** This method is called when a new image arrives.
  41923. This may be called by any thread, so be careful about thread-safety,
  41924. and make sure that you process the data as quickly as possible to
  41925. avoid glitching!
  41926. */
  41927. virtual void imageReceived (Image& image) = 0;
  41928. };
  41929. /**
  41930. Controls any camera capture devices that might be available.
  41931. Use getAvailableDevices() to list the devices that are attached to the
  41932. system, then call openDevice to open one for use. Once you have a CameraDevice
  41933. object, you can get a viewer component from it, and use its methods to
  41934. stream to a file or capture still-frames.
  41935. */
  41936. class JUCE_API CameraDevice
  41937. {
  41938. public:
  41939. /** Destructor. */
  41940. virtual ~CameraDevice();
  41941. /** Returns a list of the available cameras on this machine.
  41942. You can open one of these devices by calling openDevice().
  41943. */
  41944. static const StringArray getAvailableDevices();
  41945. /** Opens a camera device.
  41946. The index parameter indicates which of the items returned by getAvailableDevices()
  41947. to open.
  41948. The size constraints allow the method to choose between different resolutions if
  41949. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  41950. then these will be ignored.
  41951. */
  41952. static CameraDevice* openDevice (int deviceIndex,
  41953. int minWidth = 128, int minHeight = 64,
  41954. int maxWidth = 1024, int maxHeight = 768);
  41955. /** Returns the name of this device */
  41956. const String getName() const throw() { return name; }
  41957. /** Creates a component that can be used to display a preview of the
  41958. video from this camera.
  41959. */
  41960. Component* createViewerComponent();
  41961. /** Starts recording video to the specified file.
  41962. You should use getFileExtension() to find out the correct extension to
  41963. use for your filename.
  41964. If the file exists, it will be deleted before the recording starts.
  41965. This method may not start recording instantly, so if you need to know the
  41966. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  41967. after the recording has finished.
  41968. */
  41969. void startRecordingToFile (const File& file);
  41970. /** Stops recording, after a call to startRecordingToFile().
  41971. */
  41972. void stopRecording();
  41973. /** Returns the file extension that should be used for the files
  41974. that you pass to startRecordingToFile().
  41975. This may be platform-specific, e.g. ".mov" or ".avi".
  41976. */
  41977. static const String getFileExtension();
  41978. /** After calling stopRecording(), this method can be called to return the timestamp
  41979. of the first frame that was written to the file.
  41980. */
  41981. const Time getTimeOfFirstRecordedFrame() const;
  41982. /** Adds a listener to receive images from the camera.
  41983. Be very careful not to delete the listener without first removing it by calling
  41984. removeListener().
  41985. */
  41986. void addListener (CameraImageListener* listenerToAdd);
  41987. /** Removes a listener that was previously added with addListener().
  41988. */
  41989. void removeListener (CameraImageListener* listenerToRemove);
  41990. juce_UseDebuggingNewOperator
  41991. protected:
  41992. /** @internal */
  41993. CameraDevice (const String& name, int index);
  41994. private:
  41995. void* internal;
  41996. bool isRecording;
  41997. String name;
  41998. CameraDevice (const CameraDevice&);
  41999. const CameraDevice& operator= (const CameraDevice&);
  42000. };
  42001. #endif
  42002. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  42003. /********* End of inlined file: juce_CameraDevice.h *********/
  42004. #endif
  42005. #ifndef __JUCE_IMAGE_JUCEHEADER__
  42006. #endif
  42007. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  42008. /********* Start of inlined file: juce_ImageCache.h *********/
  42009. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  42010. #define __JUCE_IMAGECACHE_JUCEHEADER__
  42011. /**
  42012. A global cache of images that have been loaded from files or memory.
  42013. If you're loading an image and may need to use the image in more than one
  42014. place, this is used to allow the same image to be shared rather than loading
  42015. multiple copies into memory.
  42016. Another advantage is that after images are released, they will be kept in
  42017. memory for a few seconds before it is actually deleted, so if you're repeatedly
  42018. loading/deleting the same image, it'll reduce the chances of having to reload it
  42019. each time.
  42020. @see Image, ImageFileFormat
  42021. */
  42022. class JUCE_API ImageCache : private DeletedAtShutdown,
  42023. private Timer
  42024. {
  42025. public:
  42026. /** Loads an image from a file, (or just returns the image if it's already cached).
  42027. If the cache already contains an image that was loaded from this file,
  42028. that image will be returned. Otherwise, this method will try to load the
  42029. file, add it to the cache, and return it.
  42030. It's very important not to delete the image that is returned - instead use
  42031. the ImageCache::release() method.
  42032. Also, remember that the image returned is shared, so drawing into it might
  42033. affect other things that are using it!
  42034. @param file the file to try to load
  42035. @returns the image, or null if it there was an error loading it
  42036. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  42037. */
  42038. static Image* getFromFile (const File& file);
  42039. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  42040. If the cache already contains an image that was loaded from this block of memory,
  42041. that image will be returned. Otherwise, this method will try to load the
  42042. file, add it to the cache, and return it.
  42043. It's very important not to delete the image that is returned - instead use
  42044. the ImageCache::release() method.
  42045. Also, remember that the image returned is shared, so drawing into it might
  42046. affect other things that are using it!
  42047. @param imageData the block of memory containing the image data
  42048. @param dataSize the data size in bytes
  42049. @returns the image, or null if it there was an error loading it
  42050. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  42051. */
  42052. static Image* getFromMemory (const void* imageData,
  42053. const int dataSize);
  42054. /** Releases an image that was previously created by the ImageCache.
  42055. If an image has been returned by the getFromFile() or getFromMemory() methods,
  42056. it mustn't be deleted directly, but should be released with this method
  42057. instead.
  42058. @see getFromFile, getFromMemory
  42059. */
  42060. static void release (Image* const imageToRelease);
  42061. /** Releases an image if it's in the cache, or deletes it if it isn't cached.
  42062. This is a handy function to use if you want to delete an image but are afraid that
  42063. it might be cached.
  42064. */
  42065. static void releaseOrDelete (Image* const imageToRelease);
  42066. /** Checks whether an image is in the cache or not.
  42067. @returns true if the image is currently in the cache
  42068. */
  42069. static bool isImageInCache (Image* const imageToLookFor);
  42070. /** Increments the reference-count for a cached image.
  42071. If the image isn't in the cache, this method won't do anything.
  42072. */
  42073. static void incReferenceCount (Image* const image);
  42074. /** Checks the cache for an image with a particular hashcode.
  42075. If there's an image in the cache with this hashcode, it will be returned,
  42076. otherwise it will return zero.
  42077. If an image is returned, it must be released with the release() method
  42078. when no longer needed, to maintain the correct reference counts.
  42079. @param hashCode the hash code that would have been associated with the
  42080. image by addImageToCache()
  42081. @see addImageToCache
  42082. */
  42083. static Image* getFromHashCode (const int64 hashCode);
  42084. /** Adds an image to the cache with a user-defined hash-code.
  42085. After calling this, responsibilty for deleting the image will be taken
  42086. by the ImageCache.
  42087. The image will be initially be given a reference count of 1, so call
  42088. the release() method to delete it.
  42089. @param image the image to add
  42090. @param hashCode the hash-code to associate with it
  42091. @see getFromHashCode
  42092. */
  42093. static void addImageToCache (Image* const image,
  42094. const int64 hashCode);
  42095. /** Changes the amount of time before an unused image will be removed from the cache.
  42096. By default this is about 5 seconds.
  42097. */
  42098. static void setCacheTimeout (const int millisecs);
  42099. juce_UseDebuggingNewOperator
  42100. private:
  42101. CriticalSection lock;
  42102. VoidArray images;
  42103. ImageCache() throw();
  42104. ImageCache (const ImageCache&);
  42105. const ImageCache& operator= (const ImageCache&);
  42106. ~ImageCache();
  42107. void timerCallback();
  42108. };
  42109. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  42110. /********* End of inlined file: juce_ImageCache.h *********/
  42111. #endif
  42112. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  42113. /********* Start of inlined file: juce_ImageConvolutionKernel.h *********/
  42114. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  42115. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  42116. /**
  42117. Represents a filter kernel to use in convoluting an image.
  42118. @see Image::applyConvolution
  42119. */
  42120. class JUCE_API ImageConvolutionKernel
  42121. {
  42122. public:
  42123. /** Creates an empty convulution kernel.
  42124. @param size the length of each dimension of the kernel, so e.g. if the size
  42125. is 5, it will create a 5x5 kernel
  42126. */
  42127. ImageConvolutionKernel (const int size) throw();
  42128. /** Destructor. */
  42129. ~ImageConvolutionKernel() throw();
  42130. /** Resets all values in the kernel to zero.
  42131. */
  42132. void clear() throw();
  42133. /** Sets the value of a specific cell in the kernel.
  42134. The x and y parameters must be in the range 0 < x < getKernelSize().
  42135. @see setOverallSum
  42136. */
  42137. void setKernelValue (const int x,
  42138. const int y,
  42139. const float value) throw();
  42140. /** Rescales all values in the kernel to make the total add up to a fixed value.
  42141. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  42142. */
  42143. void setOverallSum (const float desiredTotalSum) throw();
  42144. /** Multiplies all values in the kernel by a value. */
  42145. void rescaleAllValues (const float multiplier) throw();
  42146. /** Intialises the kernel for a gaussian blur.
  42147. @param blurRadius this may be larger or smaller than the kernel's actual
  42148. size but this will obviously be wasteful or clip at the
  42149. edges. Ideally the kernel should be just larger than
  42150. (blurRadius * 2).
  42151. */
  42152. void createGaussianBlur (const float blurRadius) throw();
  42153. /** Returns the size of the kernel.
  42154. E.g. if it's a 3x3 kernel, this returns 3.
  42155. */
  42156. int getKernelSize() const throw() { return size; }
  42157. /** Returns a 2-dimensional array of the kernel's values.
  42158. The size of each dimension of the array will be getKernelSize().
  42159. */
  42160. float** getValues() const throw() { return values; }
  42161. /** Applies the kernel to an image.
  42162. @param destImage the image that will receive the resultant convoluted pixels.
  42163. @param sourceImage an optional source image to read from - if this is 0, then the
  42164. destination image will be used as the source. If an image is
  42165. specified, it must be exactly the same size and type as the destination
  42166. image.
  42167. @param x the region of the image to apply the filter to
  42168. @param y the region of the image to apply the filter to
  42169. @param width the region of the image to apply the filter to
  42170. @param height the region of the image to apply the filter to
  42171. */
  42172. void applyToImage (Image& destImage,
  42173. const Image* sourceImage,
  42174. int x,
  42175. int y,
  42176. int width,
  42177. int height) const;
  42178. juce_UseDebuggingNewOperator
  42179. private:
  42180. HeapBlock <float> values;
  42181. const int size;
  42182. // no reason not to implement these one day..
  42183. ImageConvolutionKernel (const ImageConvolutionKernel&);
  42184. const ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  42185. };
  42186. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  42187. /********* End of inlined file: juce_ImageConvolutionKernel.h *********/
  42188. #endif
  42189. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  42190. /********* Start of inlined file: juce_ImageFileFormat.h *********/
  42191. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  42192. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  42193. /**
  42194. Base-class for codecs that can read and write image file formats such
  42195. as PNG, JPEG, etc.
  42196. This class also contains static methods to make it easy to load images
  42197. from files, streams or from memory.
  42198. @see Image, ImageCache
  42199. */
  42200. class JUCE_API ImageFileFormat
  42201. {
  42202. protected:
  42203. /** Creates an ImageFormat. */
  42204. ImageFileFormat() throw() {}
  42205. public:
  42206. /** Destructor. */
  42207. virtual ~ImageFileFormat() throw() {}
  42208. /** Returns a description of this file format.
  42209. E.g. "JPEG", "PNG"
  42210. */
  42211. virtual const String getFormatName() = 0;
  42212. /** Returns true if the given stream seems to contain data that this format
  42213. understands.
  42214. The format class should only read the first few bytes of the stream and sniff
  42215. for header bytes that it understands.
  42216. @see decodeImage
  42217. */
  42218. virtual bool canUnderstand (InputStream& input) = 0;
  42219. /** Tries to decode and return an image from the given stream.
  42220. This will be called for an image format after calling its canUnderStand() method
  42221. to see if it can handle the stream.
  42222. @param input the stream to read the data from. The stream will be positioned
  42223. at the start of the image data (but this may not necessarily
  42224. be position 0)
  42225. @returns the image that was decoded, or 0 if it fails. It's the
  42226. caller's responsibility to delete this image when no longer needed.
  42227. @see loadFrom
  42228. */
  42229. virtual Image* decodeImage (InputStream& input) = 0;
  42230. /** Attempts to write an image to a stream.
  42231. To specify extra information like encoding quality, there will be appropriate parameters
  42232. in the subclasses of the specific file types.
  42233. @returns true if it nothing went wrong.
  42234. */
  42235. virtual bool writeImageToStream (const Image& sourceImage,
  42236. OutputStream& destStream) = 0;
  42237. /** Tries the built-in decoders to see if it can find one to read this stream.
  42238. There are currently built-in decoders for PNG, JPEG and GIF formats.
  42239. The object that is returned should not be deleted by the caller.
  42240. @see canUnderstand, decodeImage, loadFrom
  42241. */
  42242. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  42243. /** Tries to load an image from a stream.
  42244. This will use the findImageFormatForStream() method to locate a suitable
  42245. codec, and use that to load the image.
  42246. @returns the image that was decoded, or 0 if it fails to load one. It's the
  42247. caller's responsibility to delete this image when no longer needed.
  42248. */
  42249. static Image* loadFrom (InputStream& input);
  42250. /** Tries to load an image from a file.
  42251. This will use the findImageFormatForStream() method to locate a suitable
  42252. codec, and use that to load the image.
  42253. @returns the image that was decoded, or 0 if it fails to load one. It's the
  42254. caller's responsibility to delete this image when no longer needed.
  42255. */
  42256. static Image* loadFrom (const File& file);
  42257. /** Tries to load an image from a block of raw image data.
  42258. This will use the findImageFormatForStream() method to locate a suitable
  42259. codec, and use that to load the image.
  42260. @returns the image that was decoded, or 0 if it fails to load one. It's the
  42261. caller's responsibility to delete this image when no longer needed.
  42262. */
  42263. static Image* loadFrom (const void* rawData,
  42264. const int numBytesOfData);
  42265. };
  42266. /**
  42267. A type of ImageFileFormat for reading and writing PNG files.
  42268. @see ImageFileFormat, JPEGImageFormat
  42269. */
  42270. class JUCE_API PNGImageFormat : public ImageFileFormat
  42271. {
  42272. public:
  42273. PNGImageFormat() throw();
  42274. ~PNGImageFormat() throw();
  42275. const String getFormatName();
  42276. bool canUnderstand (InputStream& input);
  42277. Image* decodeImage (InputStream& input);
  42278. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  42279. };
  42280. /**
  42281. A type of ImageFileFormat for reading and writing JPEG files.
  42282. @see ImageFileFormat, PNGImageFormat
  42283. */
  42284. class JUCE_API JPEGImageFormat : public ImageFileFormat
  42285. {
  42286. public:
  42287. JPEGImageFormat() throw();
  42288. ~JPEGImageFormat() throw();
  42289. /** Specifies the quality to be used when writing a JPEG file.
  42290. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  42291. any negative value is "default" quality
  42292. */
  42293. void setQuality (const float newQuality);
  42294. const String getFormatName();
  42295. bool canUnderstand (InputStream& input);
  42296. Image* decodeImage (InputStream& input);
  42297. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  42298. private:
  42299. float quality;
  42300. };
  42301. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  42302. /********* End of inlined file: juce_ImageFileFormat.h *********/
  42303. #endif
  42304. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  42305. #endif
  42306. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42307. /********* Start of inlined file: juce_FileBasedDocument.h *********/
  42308. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42309. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42310. /**
  42311. A class to take care of the logic involved with the loading/saving of some kind
  42312. of document.
  42313. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  42314. functions you need for documents that get saved to a file, so this class attempts
  42315. to abstract most of the boring stuff.
  42316. Your subclass should just implement all the pure virtual methods, and you can
  42317. then use the higher-level public methods to do the load/save dialogs, to warn the user
  42318. about overwriting files, etc.
  42319. The document object keeps track of whether it has changed since it was last saved or
  42320. loaded, so when you change something, call its changed() method. This will set a
  42321. flag so it knows it needs saving, and will also broadcast a change message using the
  42322. ChangeBroadcaster base class.
  42323. @see ChangeBroadcaster
  42324. */
  42325. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  42326. {
  42327. public:
  42328. /** Creates a FileBasedDocument.
  42329. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  42330. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  42331. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  42332. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  42333. */
  42334. FileBasedDocument (const String& fileExtension,
  42335. const String& fileWildCard,
  42336. const String& openFileDialogTitle,
  42337. const String& saveFileDialogTitle);
  42338. /** Destructor. */
  42339. virtual ~FileBasedDocument();
  42340. /** Returns true if the changed() method has been called since the file was
  42341. last saved or loaded.
  42342. @see resetChangedFlag, changed
  42343. */
  42344. bool hasChangedSinceSaved() const throw() { return changedSinceSave; }
  42345. /** Called to indicate that the document has changed and needs saving.
  42346. This method will also trigger a change message to be sent out using the
  42347. ChangeBroadcaster base class.
  42348. After calling the method, the hasChangedSinceSaved() method will return true, until
  42349. it is reset either by saving to a file or using the resetChangedFlag() method.
  42350. @see hasChangedSinceSaved, resetChangedFlag
  42351. */
  42352. virtual void changed();
  42353. /** Sets the state of the 'changed' flag.
  42354. The 'changed' flag is set to true when the changed() method is called - use this method
  42355. to reset it or to set it without also broadcasting a change message.
  42356. @see changed, hasChangedSinceSaved
  42357. */
  42358. void setChangedFlag (const bool hasChanged);
  42359. /** Tries to open a file.
  42360. If the file opens correctly, the document's file (see the getFile() method) is set
  42361. to this new one; if it fails, the document's file is left unchanged, and optionally
  42362. a message box is shown telling the user there was an error.
  42363. @returns true if the new file loaded successfully
  42364. @see loadDocument, loadFromUserSpecifiedFile
  42365. */
  42366. bool loadFrom (const File& fileToLoadFrom,
  42367. const bool showMessageOnFailure);
  42368. /** Asks the user for a file and tries to load it.
  42369. This will pop up a dialog box using the title, file extension and
  42370. wildcard specified in the document's constructor, and asks the user
  42371. for a file. If they pick one, the loadFrom() method is used to
  42372. try to load it, optionally showing a message if it fails.
  42373. @returns true if a file was loaded; false if the user cancelled or if they
  42374. picked a file which failed to load correctly
  42375. @see loadFrom
  42376. */
  42377. bool loadFromUserSpecifiedFile (const bool showMessageOnFailure);
  42378. /** A set of possible outcomes of one of the save() methods
  42379. */
  42380. enum SaveResult
  42381. {
  42382. savedOk = 0, /**< indicates that a file was saved successfully. */
  42383. userCancelledSave, /**< indicates that the user aborted the save operation. */
  42384. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  42385. };
  42386. /** Tries to save the document to the last file it was saved or loaded from.
  42387. This will always try to write to the file, even if the document isn't flagged as
  42388. having changed.
  42389. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  42390. true, it will prompt the user to pick a file, as if
  42391. saveAsInteractive() was called.
  42392. @param showMessageOnFailure if true it will show a warning message when if the
  42393. save operation fails
  42394. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  42395. */
  42396. SaveResult save (const bool askUserForFileIfNotSpecified,
  42397. const bool showMessageOnFailure);
  42398. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  42399. it if they say yes.
  42400. If you've got a document open and want to close it (e.g. to quit the app), this is the
  42401. method to call.
  42402. If the document doesn't need saving it'll return the value savedOk so
  42403. you can go ahead and delete the document.
  42404. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  42405. return savedOk, so again, you can safely delete the document.
  42406. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  42407. close-document operation.
  42408. And if they click "save changes", it'll try to save and either return savedOk, or
  42409. failedToWriteToFile if there was a problem.
  42410. @see save, saveAs, saveAsInteractive
  42411. */
  42412. SaveResult saveIfNeededAndUserAgrees();
  42413. /** Tries to save the document to a specified file.
  42414. If this succeeds, it'll also change the document's internal file (as returned by
  42415. the getFile() method). If it fails, the file will be left unchanged.
  42416. @param newFile the file to try to write to
  42417. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  42418. the user first if they want to overwrite it
  42419. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  42420. use the saveAsInteractive() method to ask the user for a
  42421. filename
  42422. @param showMessageOnFailure if true and the write operation fails, it'll show
  42423. a message box to warn the user
  42424. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  42425. */
  42426. SaveResult saveAs (const File& newFile,
  42427. const bool warnAboutOverwritingExistingFiles,
  42428. const bool askUserForFileIfNotSpecified,
  42429. const bool showMessageOnFailure);
  42430. /** Prompts the user for a filename and tries to save to it.
  42431. This will pop up a dialog box using the title, file extension and
  42432. wildcard specified in the document's constructor, and asks the user
  42433. for a file. If they pick one, the saveAs() method is used to try to save
  42434. to this file.
  42435. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  42436. the user first if they want to overwrite it
  42437. @see saveIfNeededAndUserAgrees, save, saveAs
  42438. */
  42439. SaveResult saveAsInteractive (const bool warnAboutOverwritingExistingFiles);
  42440. /** Returns the file that this document was last successfully saved or loaded from.
  42441. When the document object is created, this will be set to File::nonexistent.
  42442. It is changed when one of the load or save methods is used, or when setFile()
  42443. is used to explicitly set it.
  42444. */
  42445. const File getFile() const throw() { return documentFile; }
  42446. /** Sets the file that this document thinks it was loaded from.
  42447. This won't actually load anything - it just changes the file stored internally.
  42448. @see getFile
  42449. */
  42450. void setFile (const File& newFile);
  42451. protected:
  42452. /** Overload this to return the title of the document.
  42453. This is used in message boxes, filenames and file choosers, so it should be
  42454. something sensible.
  42455. */
  42456. virtual const String getDocumentTitle() = 0;
  42457. /** This method should try to load your document from the given file.
  42458. If it fails, it should return an error message. If it succeeds, it should return
  42459. an empty string.
  42460. */
  42461. virtual const String loadDocument (const File& file) = 0;
  42462. /** This method should try to write your document to the given file.
  42463. If it fails, it should return an error message. If it succeeds, it should return
  42464. an empty string.
  42465. */
  42466. virtual const String saveDocument (const File& file) = 0;
  42467. /** This is used for dialog boxes to make them open at the last folder you
  42468. were using.
  42469. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  42470. the last document that was used - you might want to store this value
  42471. in a static variable, or even in your application's properties. It should
  42472. be a global setting rather than a property of this object.
  42473. This method works very well in conjunction with a RecentlyOpenedFilesList
  42474. object to manage your recent-files list.
  42475. As a default value, it's ok to return File::nonexistent, and the document
  42476. object will use a sensible one instead.
  42477. @see RecentlyOpenedFilesList
  42478. */
  42479. virtual const File getLastDocumentOpened() = 0;
  42480. /** This is used for dialog boxes to make them open at the last folder you
  42481. were using.
  42482. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  42483. the last document that was used - you might want to store this value
  42484. in a static variable, or even in your application's properties. It should
  42485. be a global setting rather than a property of this object.
  42486. This method works very well in conjunction with a RecentlyOpenedFilesList
  42487. object to manage your recent-files list.
  42488. @see RecentlyOpenedFilesList
  42489. */
  42490. virtual void setLastDocumentOpened (const File& file) = 0;
  42491. public:
  42492. juce_UseDebuggingNewOperator
  42493. private:
  42494. File documentFile;
  42495. bool changedSinceSave;
  42496. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  42497. FileBasedDocument (const FileBasedDocument&);
  42498. const FileBasedDocument& operator= (const FileBasedDocument&);
  42499. };
  42500. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  42501. /********* End of inlined file: juce_FileBasedDocument.h *********/
  42502. #endif
  42503. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  42504. #endif
  42505. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42506. /********* Start of inlined file: juce_RecentlyOpenedFilesList.h *********/
  42507. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42508. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42509. /**
  42510. Manages a set of files for use as a list of recently-opened documents.
  42511. This is a handy class for holding your list of recently-opened documents, with
  42512. helpful methods for things like purging any non-existent files, automatically
  42513. adding them to a menu, and making persistence easy.
  42514. @see File, FileBasedDocument
  42515. */
  42516. class JUCE_API RecentlyOpenedFilesList
  42517. {
  42518. public:
  42519. /** Creates an empty list.
  42520. */
  42521. RecentlyOpenedFilesList();
  42522. /** Destructor. */
  42523. ~RecentlyOpenedFilesList();
  42524. /** Sets a limit for the number of files that will be stored in the list.
  42525. When addFile() is called, then if there is no more space in the list, the
  42526. least-recently added file will be dropped.
  42527. @see getMaxNumberOfItems
  42528. */
  42529. void setMaxNumberOfItems (const int newMaxNumber);
  42530. /** Returns the number of items that this list will store.
  42531. @see setMaxNumberOfItems
  42532. */
  42533. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  42534. /** Returns the number of files in the list.
  42535. The most recently added file is always at index 0.
  42536. */
  42537. int getNumFiles() const;
  42538. /** Returns one of the files in the list.
  42539. The most recently added file is always at index 0.
  42540. */
  42541. const File getFile (const int index) const;
  42542. /** Returns an array of all the absolute pathnames in the list.
  42543. */
  42544. const StringArray& getAllFilenames() const throw() { return files; }
  42545. /** Clears all the files from the list. */
  42546. void clear();
  42547. /** Adds a file to the list.
  42548. The file will be added at index 0. If this file is already in the list, it will
  42549. be moved up to index 0, but a file can only appear once in the list.
  42550. If the list already contains the maximum number of items that is permitted, the
  42551. least-recently added file will be dropped from the end.
  42552. */
  42553. void addFile (const File& file);
  42554. /** Checks each of the files in the list, removing any that don't exist.
  42555. You might want to call this after reloading a list of files, or before putting them
  42556. on a menu.
  42557. */
  42558. void removeNonExistentFiles();
  42559. /** Adds entries to a menu, representing each of the files in the list.
  42560. This is handy for creating an "open recent file..." menu in your app. The
  42561. menu items are numbered consecutively starting with the baseItemId value,
  42562. and can either be added as complete pathnames, or just the last part of the
  42563. filename.
  42564. If dontAddNonExistentFiles is true, then each file will be checked and only those
  42565. that exist will be added.
  42566. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  42567. pointers to file objects. Any files that appear in this list will not be added to the
  42568. menu - the reason for this is that you might have a number of files already open, so
  42569. might not want these to be shown in the menu.
  42570. It returns the number of items that were added.
  42571. */
  42572. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  42573. const int baseItemId,
  42574. const bool showFullPaths,
  42575. const bool dontAddNonExistentFiles,
  42576. const File** filesToAvoid = 0);
  42577. /** Returns a string that encapsulates all the files in the list.
  42578. The string that is returned can later be passed into restoreFromString() in
  42579. order to recreate the list. This is handy for persisting your list, e.g. in
  42580. a PropertiesFile object.
  42581. @see restoreFromString
  42582. */
  42583. const String toString() const;
  42584. /** Restores the list from a previously stringified version of the list.
  42585. Pass in a stringified version created with toString() in order to persist/restore
  42586. your list.
  42587. @see toString
  42588. */
  42589. void restoreFromString (const String& stringifiedVersion);
  42590. juce_UseDebuggingNewOperator
  42591. private:
  42592. StringArray files;
  42593. int maxNumberOfItems;
  42594. };
  42595. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  42596. /********* End of inlined file: juce_RecentlyOpenedFilesList.h *********/
  42597. #endif
  42598. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  42599. #endif
  42600. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42601. /********* Start of inlined file: juce_SystemClipboard.h *********/
  42602. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42603. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42604. /**
  42605. Handles reading/writing to the system's clipboard.
  42606. */
  42607. class JUCE_API SystemClipboard
  42608. {
  42609. public:
  42610. /** Copies a string of text onto the clipboard */
  42611. static void copyTextToClipboard (const String& text) throw();
  42612. /** Gets the current clipboard's contents.
  42613. Obviously this might have come from another app, so could contain
  42614. anything..
  42615. */
  42616. static const String getTextFromClipboard() throw();
  42617. };
  42618. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  42619. /********* End of inlined file: juce_SystemClipboard.h *********/
  42620. #endif
  42621. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  42622. #endif
  42623. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  42624. #endif
  42625. #endif
  42626. /********* End of inlined file: juce_app_includes.h *********/
  42627. #endif
  42628. #if JUCE_MSVC
  42629. #pragma warning (pop)
  42630. #pragma pack (pop)
  42631. #endif
  42632. #if JUCE_MAC || JUCE_IPHONE
  42633. #pragma align=reset
  42634. #endif
  42635. END_JUCE_NAMESPACE
  42636. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  42637. #ifdef JUCE_NAMESPACE
  42638. // this will obviously save a lot of typing, but can be disabled by
  42639. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  42640. using namespace JUCE_NAMESPACE;
  42641. /* On the Mac, these symbols are defined in the Mac libraries, so
  42642. these macros make it easier to reference them without writing out
  42643. the namespace every time.
  42644. If you run into difficulties where these macros interfere with the contents
  42645. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  42646. the comments in that file for more information.
  42647. */
  42648. #if JUCE_MAC && ! JUCE_DONT_DEFINE_MACROS
  42649. #define Component JUCE_NAMESPACE::Component
  42650. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  42651. #define Point JUCE_NAMESPACE::Point
  42652. #define Button JUCE_NAMESPACE::Button
  42653. #endif
  42654. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  42655. it easier to use the juce version explicitly.
  42656. If you run into difficulties where this macro interferes with other 3rd party header
  42657. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  42658. file for more information.
  42659. */
  42660. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  42661. #define Rectangle JUCE_NAMESPACE::Rectangle
  42662. #endif
  42663. #endif
  42664. #endif
  42665. /* Easy autolinking to the right JUCE libraries under win32.
  42666. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  42667. including this header file.
  42668. */
  42669. #if JUCE_MSVC
  42670. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  42671. /** If you want your application to link to Juce as a DLL instead of
  42672. a static library (on win32), just define the JUCE_DLL macro before
  42673. including juce.h
  42674. */
  42675. #ifdef JUCE_DLL
  42676. #ifdef JUCE_DEBUG
  42677. #define AUTOLINKEDLIB "JUCE_debug.lib"
  42678. #else
  42679. #define AUTOLINKEDLIB "JUCE.lib"
  42680. #endif
  42681. #else
  42682. #ifdef JUCE_DEBUG
  42683. #ifdef _WIN64
  42684. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  42685. #else
  42686. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  42687. #endif
  42688. #else
  42689. #ifdef _WIN64
  42690. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  42691. #else
  42692. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  42693. #endif
  42694. #endif
  42695. #endif
  42696. #pragma comment(lib, AUTOLINKEDLIB)
  42697. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  42698. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  42699. #endif
  42700. // Auto-link the other win32 libs that are needed by library calls..
  42701. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  42702. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  42703. // Auto-links to various win32 libs that are needed by library calls..
  42704. #pragma comment(lib, "kernel32.lib")
  42705. #pragma comment(lib, "user32.lib")
  42706. #pragma comment(lib, "shell32.lib")
  42707. #pragma comment(lib, "gdi32.lib")
  42708. #pragma comment(lib, "vfw32.lib")
  42709. #pragma comment(lib, "comdlg32.lib")
  42710. #pragma comment(lib, "winmm.lib")
  42711. #pragma comment(lib, "wininet.lib")
  42712. #pragma comment(lib, "ole32.lib")
  42713. #pragma comment(lib, "advapi32.lib")
  42714. #pragma comment(lib, "ws2_32.lib")
  42715. #pragma comment(lib, "comsupp.lib")
  42716. #pragma comment(lib, "version.lib")
  42717. #if JUCE_OPENGL
  42718. #pragma comment(lib, "OpenGL32.Lib")
  42719. #pragma comment(lib, "GlU32.Lib")
  42720. #endif
  42721. #if JUCE_QUICKTIME
  42722. #pragma comment (lib, "QTMLClient.lib")
  42723. #endif
  42724. #if JUCE_USE_CAMERA
  42725. #pragma comment (lib, "Strmiids.lib")
  42726. #endif
  42727. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  42728. #endif
  42729. #endif
  42730. #endif
  42731. /*
  42732. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  42733. AppSubClass is the name of a class derived from JUCEApplication.
  42734. See the JUCEApplication class documentation (juce_Application.h) for more details.
  42735. */
  42736. #if defined (JUCE_GCC) || defined (__MWERKS__)
  42737. #define START_JUCE_APPLICATION(AppClass) \
  42738. int main (int argc, char* argv[]) \
  42739. { \
  42740. return JUCE_NAMESPACE::JUCEApplication::main (argc, argv, new AppClass()); \
  42741. }
  42742. #elif JUCE_WINDOWS
  42743. #ifdef _CONSOLE
  42744. #define START_JUCE_APPLICATION(AppClass) \
  42745. int main (int, char* argv[]) \
  42746. { \
  42747. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  42748. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  42749. }
  42750. #elif ! defined (_AFXDLL)
  42751. #ifdef _WINDOWS_
  42752. #define START_JUCE_APPLICATION(AppClass) \
  42753. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  42754. { \
  42755. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  42756. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  42757. }
  42758. #else
  42759. #define START_JUCE_APPLICATION(AppClass) \
  42760. int __stdcall WinMain (int, int, const char*, int) \
  42761. { \
  42762. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  42763. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  42764. }
  42765. #endif
  42766. #endif
  42767. #endif
  42768. #endif // __JUCE_JUCEHEADER__
  42769. /********* End of inlined file: juce.h *********/
  42770. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__